diff options
author | xg353y <xg353y@intl.att.com> | 2017-04-11 13:30:42 +0200 |
---|---|---|
committer | xg353y <xg353y@intl.att.com> | 2017-04-11 15:34:19 +0200 |
commit | b6b7bef8bdcad15af01ac88a038dd763ce59f68f (patch) | |
tree | 399d39da23aaa37701e487df064e3e0c27709ef3 /bpmn/MSOCoreBPMN/src/main/java | |
parent | 19340cad94eeaa1b580f7c0c99531de499e8ca14 (diff) |
[MSO-8] Update the maven dependency
Update the maven depenency for sdc-distribution-client to cooperate with the sdc changes.
Change-Id: I2da936e5c40cb68c7181bb78307192dd5655b5dc
Signed-off-by: xg353y <xg353y@intl.att.com>
Diffstat (limited to 'bpmn/MSOCoreBPMN/src/main/java')
-rw-r--r-- | bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java (renamed from bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/CamundaDBSetup.java) | 40 | ||||
-rw-r--r-- | bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java | 144 | ||||
-rw-r--r-- | bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfiguration.java | 24 | ||||
-rw-r--r-- | bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfigurationSetup.java (renamed from bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/PropertyConfigurationSetup.java) | 24 | ||||
-rw-r--r-- | bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java | 2 | ||||
-rw-r--r-- | bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java | 439 | ||||
-rw-r--r-- | bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java | 4 |
7 files changed, 556 insertions, 121 deletions
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/CamundaDBSetup.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java index 13eed2d530..aba43eb522 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/CamundaDBSetup.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java @@ -1,24 +1,4 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.bpmn.test; +package org.openecomp.mso.bpmn.core; import java.sql.Connection; import java.sql.DriverManager; @@ -55,10 +35,10 @@ public class CamundaDBSetup { stmt.close(); stmt = null; - stmt = connection.prepareStatement("ALTER TABLE ACT_HI_VARINST alter column NAME_ clob"); - stmt.executeUpdate(); - stmt.close(); - stmt = null; +// stmt = connection.prepareStatement("ALTER TABLE ACT_HI_VARINST alter column NAME_ clob"); +// stmt.executeUpdate(); +// stmt.close(); +// stmt = null; stmt = connection.prepareStatement("delete from ACT_HI_DETAIL"); stmt.executeUpdate(); @@ -70,10 +50,10 @@ public class CamundaDBSetup { stmt.close(); stmt = null; - stmt = connection.prepareStatement("ALTER TABLE ACT_HI_DETAIL alter column NAME_ clob"); - stmt.executeUpdate(); - stmt.close(); - stmt = null; +// stmt = connection.prepareStatement("ALTER TABLE ACT_HI_DETAIL alter column NAME_ clob"); +// stmt.executeUpdate(); +// stmt.close(); +// stmt = null; stmt = connection.prepareStatement("ALTER TABLE ACT_RU_VARIABLE alter column TEXT_ clob"); stmt.executeUpdate(); @@ -105,4 +85,4 @@ public class CamundaDBSetup { } } } -} +}
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java index df6213284c..2edbc99a77 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/HealthCheckHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,12 +30,18 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import java.io.BufferedReader; +import java.io.InputStream; import java.io.InputStreamReader; +import java.util.Base64; import java.util.Map; +import java.util.Properties; import java.util.UUID; import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.utils.UUIDChecker; +import org.openecomp.mso.HealthCheckUtils; import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.utils.CryptoUtils; import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.Path; @@ -48,10 +54,14 @@ import org.camunda.bpm.engine.ProcessEngines; @Path("/") public class HealthCheckHandler { - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); private static final String SITENAME = "mso.sitename"; private static final String ADPTER_ENDPOINT = "mso.adapters.db.endpoint"; private static final String CONFIG = "mso.bpmn.urn.properties"; + private static final String PENGINE_PROPERTY = "processengine.properties"; + private static final String PENGINE_PARAM = "processEngineName"; + private static final String CREDENTIAL = "mso.adapters.db.auth"; + private static final String MSOKEY = "mso.msoKey"; private static final String CHECK_HTML = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>"; private static final String NOT_FOUND = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Application Not Started</title></head><body>Application not started. Properties file missing or invalid or database Connection failed</body></html>"; @@ -68,6 +78,59 @@ public class HealthCheckHandler { @HEAD @GET + @Path("/nodehealthcheck") + @Produces("text/html") + public Response nodeHealthcheck () { + MsoLogger.setServiceName ("NodeHealthcheck"); + // Generate a Request Id + String requestId = UUIDChecker.generateUUID(msoLogger); + + PropertyConfiguration propertyConfiguration = PropertyConfiguration.getInstance(); + Map<String,String> props = propertyConfiguration.getProperties(CONFIG); + + if (props == null) { + + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.AvailabilityError, "Unable to load " + CONFIG); + + return NOT_STARTED_RESPONSE; + } + + String siteName = props.get(SITENAME); + String endpoint = props.get(ADPTER_ENDPOINT); + + if (null == siteName || siteName.length () == 0 || null == endpoint || endpoint.length () == 0) { + + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, "Unable to load key attributes (" + SITENAME + " or " + ADPTER_ENDPOINT + ") from the config file:" + CONFIG); + + return NOT_STARTED_RESPONSE; + } + + try { + if (!this.getSiteStatus (endpoint, siteName, props.get(CREDENTIAL), props.get(MSOKEY))) { + msoLogger.debug("This site is currently disabled for maintenance."); + return HEALTH_CHECK_NOK_RESPONSE; + } + } catch (Exception e) { + + msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception while getting SiteStatus", e); + + msoLogger.debug("Exception while getting SiteStatus"); + return NOT_STARTED_RESPONSE; + } + + + HealthCheckUtils healthCheck = new HealthCheckUtils (); + if (healthCheck.verifyNodeHealthCheck(HealthCheckUtils.NodeType.BPMN, requestId)) { + msoLogger.debug("nodeHealthcheck - Successful"); + return HealthCheckUtils.HEALTH_CHECK_RESPONSE; + } else { + msoLogger.debug("nodeHealthcheck - At leaset one of the sub-modules is not available."); + return HealthCheckUtils.HEALTH_CHECK_NOK_RESPONSE; + } + } + + @HEAD + @GET @Path("/healthcheck") @Produces("text/html") public Response healthcheck (@QueryParam("requestId") String requestId) { @@ -95,7 +158,7 @@ public class HealthCheckHandler { } try { - if (!this.getSiteStatus (endpoint, siteName)) { + if (!this.getSiteStatus (endpoint, siteName, props.get(CREDENTIAL), props.get(MSOKEY))) { msoLogger.debug("This site is currently disabled for maintenance."); return HEALTH_CHECK_NOK_RESPONSE; } @@ -108,7 +171,13 @@ public class HealthCheckHandler { } try { - ProcessEngines.getDefaultProcessEngine().getIdentityService().createGroupQuery().list(); + InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PENGINE_PROPERTY); + Properties prop = new Properties(); + prop.load(stream); + String [] engineNames = prop.getProperty(PENGINE_PARAM).split(","); + for (String engine : engineNames) { + ProcessEngines.getProcessEngine(engine).getIdentityService().createGroupQuery().list(); + } } catch (final Exception e) { msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception while verifying Camunda engine", e); @@ -144,8 +213,18 @@ public class HealthCheckHandler { } } - private boolean getSiteStatus (String url, String site) throws Exception { - HttpResponse response; + private String decrypt(String encryptedString, String key){ + try { + if (encryptedString != null || !encryptedString.isEmpty() && key != null && !key.isEmpty()) { + return CryptoUtils.decrypt(encryptedString, key); + } + } catch (Exception e) { + msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Failed to decrypt credentials", e); + } + return null; + } + + private boolean getSiteStatus (String url, String site, String credential, String key) throws Exception { // set the connection timeout value to 30 seconds (30000 milliseconds) RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(30000); @@ -154,12 +233,17 @@ public class HealthCheckHandler { builder.setDefaultRequestConfig (requestBuilder.build ()); HttpPost post = new HttpPost(url); + + String cred = decrypt(credential, key); + if (cred != null && !cred.isEmpty()) { + post.setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(cred.getBytes())); + } msoLogger.debug("Post url is: " + url); //now create a soap request message as follows: final StringBuffer payload = new StringBuffer(); payload.append("\n"); - payload.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:req=\"http://com.att.mso/requestsdb\">\n"); + payload.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:req=\"http://org.openecomp.mso/requestsdb\">\n"); payload.append("<soapenv:Header/>\n"); payload.append("<soapenv:Body>\n"); payload.append("<req:getSiteStatus>\n"); @@ -173,31 +257,31 @@ public class HealthCheckHandler { HttpEntity entity = new StringEntity(payload.toString(),"UTF-8"); post.setEntity(entity); - try (CloseableHttpClient client = builder.build()) { - response = client.execute(post); - msoLogger.debug("Response received is:" + response); - - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode != 200) { + CloseableHttpClient client = builder.build (); + HttpResponse response = client.execute(post); + msoLogger.debug("Response received is:" + response); - msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, - "Communication with DB Adapter failed, The response received from DB Adapter is with failed status code:" + statusCode); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { - Exception e = new Exception("Communication with DB Adapter failed"); - throw e; - } - BufferedReader rd = new BufferedReader( - new InputStreamReader(response.getEntity().getContent())); + msoLogger.error(MessageEnum.GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, + "Communication with DB Adapter failed, The response received from DB Adapter is with failed status code:" + statusCode); - StringBuffer result = new StringBuffer(); - String line = ""; - while ((line = rd.readLine()) != null) { - result.append(line); - } - msoLogger.debug("Content of the response is:" + result); - String status = result.substring(result.indexOf("<return>") + 8, result.indexOf("</return>")); + Exception e = new Exception("Communication with DB Adapter failed"); + throw e; + } + BufferedReader rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); - return Boolean.valueOf(status); + StringBuffer result = new StringBuffer(); + String line = ""; + while ((line = rd.readLine()) != null) { + result.append(line); } + msoLogger.debug("Content of the response is:" + result); + String status = result.substring(result.indexOf("<return>") + 8, result.indexOf("</return>")); + + client.close (); //shut down the connection + return Boolean.valueOf(status); } -} +}
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfiguration.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfiguration.java index 90df1da7e5..d58d046598 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfiguration.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -51,11 +51,11 @@ import org.openecomp.mso.logger.MsoLogger; /** * Loads the property configuration from file system and refreshes the * properties when the property gets changed. - * + * * WARNING: automatic refreshes might not work on network filesystems. */ public class PropertyConfiguration { - + /** * The base name of the MSO BPMN properties file (mso.bpmn.properties). */ @@ -65,7 +65,11 @@ public class PropertyConfiguration { * The base name of the MSO BPMN URN-Mappings properties file (mso.bpmn.urn.properties). */ public static final String MSO_BPMN_URN_PROPERTIES = "mso.bpmn.urn.properties"; - + + /** + * The base name of the MSO Topology properties file (topology.properties). + */ + public static final String MSO_TOPOLOGY_PROPERTIES = "topology.properties"; /** * The name of the meta-property holding the time the properties were loaded * from the file. @@ -75,7 +79,7 @@ public class PropertyConfiguration { private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); private static final List<String> SUPPORTED_FILES = - Arrays.asList(MSO_BPMN_PROPERTIES, MSO_BPMN_URN_PROPERTIES); + Arrays.asList(MSO_BPMN_PROPERTIES, MSO_BPMN_URN_PROPERTIES, MSO_TOPOLOGY_PROPERTIES); private volatile String msoConfigPath = null; @@ -87,7 +91,7 @@ public class PropertyConfiguration { // The key is the file name private Map<String, TimerTask> timerTaskMap = new HashMap<String, TimerTask>(); - + /** * Singleton holder pattern eliminates locking when accessing the instance * and still provides for lazy initialization. @@ -116,7 +120,7 @@ public class PropertyConfiguration { private PropertyConfiguration() { startUp(); } - + /** * May be called to restart the PropertyConfiguration if it was previously shut down. */ @@ -228,7 +232,7 @@ public class PropertyConfiguration { return Collections.unmodifiableMap(properties); } - + /** * Reads properties from the specified file, updates the property file cache, and * returns the properties in a map. @@ -270,7 +274,7 @@ public class PropertyConfiguration { return properties; } - + /** * File watcher thread which monitors a directory for file modification. */ diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/PropertyConfigurationSetup.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfigurationSetup.java index 6f1cd7d8cc..f58efe79c8 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/PropertyConfigurationSetup.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfigurationSetup.java @@ -1,24 +1,4 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.bpmn.test; +package org.openecomp.mso.bpmn.core; import java.io.FileOutputStream; import java.io.FileReader; @@ -312,4 +292,4 @@ public class PropertyConfigurationSetup { } } } -} +}
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java index 8a7b20016b..926f2af9aa 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java @@ -240,4 +240,4 @@ public class XQueryScriptTask extends BaseTask { } } } -} +}
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java index 8329746347..462bda8077 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java @@ -21,8 +21,11 @@ package org.openecomp.mso.bpmn.core.json; import java.util.Iterator; +import java.util.Map; +import java.util.HashMap; import java.util.StringTokenizer; +import org.camunda.bpm.engine.runtime.Execution; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -79,7 +82,7 @@ public class JsonUtils { /** * Uses the JSONObject static method to convert a JSON doc to XML. - * Note: this method will not generate valid XML if the JSONObject + * Note: this method may not generate valid XML if the JSONObject * contains JSONArrays which are used to represent XML attributes * in the JSON doc. * @@ -92,9 +95,11 @@ public class JsonUtils { try { JSONObject jsonObj = new JSONObject(jsonStr); if (pretty) { - return XmlTool.normalize(XML.toString(jsonObj)); + // use the local class method which properly handles certain JSONArray content + return XmlTool.normalize(toXMLString(jsonObj, null)); } else { - return XML.toString(jsonObj); +// use the local class method which properly handles certain JSONArray content + return toXMLString(jsonObj, null); } } catch (Exception e){ msoLogger.debug("json2xml(): unable to parse json and convert to xml. Exception was: " + e.toString()); @@ -103,6 +108,154 @@ public class JsonUtils { } /** + * Uses a modified version of the org.json.XML toString() algorithm + * to convert a JSONObject to an XML Doc. The intent of this is to + * correctly generate XML from JSON including TAGs for JSONArrays + * + * @param jsonObj org.json.JSON object to be converted to XML + * @param tagName optional XML tagname supplied primarily during recursive calls + * @return String containing the XML translation + */ + public static String toXMLString(Object obj, String tagName) throws JSONException { + StringBuffer strBuf = new StringBuffer(); + int i; + JSONArray jsonArr; + JSONObject jsonObj; + String key; + Iterator<String> keys; + int len; + String str; + Object curObj; + if (obj instanceof JSONObject) { + // msoLogger.debug("toXMLString(): is a JSONObject"); + // append "<tagName>" to the XML output + if (tagName != null) { +// msoLogger.debug("toXMLString(): adding opening tagName: " + tagName); + strBuf.append("<"); + strBuf.append(tagName); + strBuf.append(">"); + } + // iterate thru the keys. + jsonObj = (JSONObject) obj; + keys = jsonObj.keys(); + while (keys.hasNext()) { + key = keys.next().toString(); + // msoLogger.debug("toXMLString(): key is " + k); + curObj = jsonObj.opt(key); + if (curObj == null) { + curObj = ""; + } + if (curObj instanceof String) { + str = (String) curObj; + } else { + str = null; + } + // append the content to the XML output + if (key.equals("content")) { + if (curObj instanceof JSONArray) { + jsonArr = (JSONArray) curObj; + len = jsonArr.length(); + for (i = 0; i < len; i += 1) { + if (i > 0) { + strBuf.append('\n'); + } + strBuf.append(XML.escape(jsonArr.get(i).toString())); + } + } else { + strBuf.append(XML.escape(curObj.toString())); + } + // append an array of similar keys to the XML output + } else if (curObj instanceof JSONArray) { + jsonArr = (JSONArray) curObj; + len = jsonArr.length(); +// msoLogger.debug("toXMLString(): found JSONArray: " + key + ", size: " + len); + for (i = 0; i < len; i += 1) { + curObj = jsonArr.get(i); + if (curObj instanceof JSONArray) { +// The XML tags for the nested array should be generated below when this method +// is called recursively and the JSONArray object is passed +// strBuf.append("<"); +// strBuf.append(key); +// strBuf.append(">"); + strBuf.append(toXMLString(curObj, null)); +// strBuf.append("</"); +// strBuf.append(key); +// strBuf.append(">"); + } else { +// msoLogger.debug("toXMLString(): recursive call toXML() with tagName null"); + // append the opening tag for the array (before 1st element) + if (i == 0) { + strBuf.append("<"); + strBuf.append(key); + strBuf.append(">"); + } + // append the opening tag for the array + strBuf.append(toXMLString(curObj, null)); + // append the closing tag for the array (after last element) + if (i == (len - 1)) { + strBuf.append("</"); + strBuf.append(key); + strBuf.append(">"); + } + } + } + } else if (curObj.equals("")) { + // append a closing tag "<key>" to the XML output + strBuf.append("<"); + strBuf.append(key); + strBuf.append("/>"); + } else { +// msoLogger.debug("toXMLString(): recursive call toXMLString() with tagName: " + key); + strBuf.append(toXMLString(curObj, key)); + } + // msoLogger.debug("toXML(): partial XML: " + strBuf.toString()); + } + if (tagName != null) { + // append the closing tag "</tagName>" to the XML output +// msoLogger.debug("toXMLString(): adding closing tagName: " + tagName); + strBuf.append("</"); + strBuf.append(tagName); + strBuf.append(">"); + } + return strBuf.toString(); + // XML does not have good support for arrays. If an array appears in a place + // where XML is lacking, synthesize an < array > element. + } else if (obj instanceof JSONArray) { + jsonArr = (JSONArray) obj; + len = jsonArr.length(); + for (i = 0; i < len; ++i) { + curObj = jsonArr.opt(i); + strBuf.append(toXMLString(curObj, (tagName == null) ? "array" + : tagName)); + } + return strBuf.toString(); + } else { +// msoLogger.debug("toXML(): in else block with tagName: " + tagName); + str = (obj == null) ? "null" : XML.escape(obj.toString()); + return (tagName == null) ? "\"" + str + "\"" + : (str.length() == 0) ? "<" + tagName + "/>" : "<" + + tagName + ">" + str + "</" + tagName + ">"; + } + } + + /** + * Formats the JSON String using the value of MSOJsonIndentFactor. + * + * @param jsonStr String containing the JSON doc + * @return String containing the formatted JSON doc + */ + public static String prettyJson(String jsonStr) { +// String isDebugLogEnabled = "true"; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + return jsonObj.toString(MSOJsonIndentFactor); + } catch (Exception e){ + msoLogger.debug("prettyJson(): unable to parse/format json input. Exception was: " + e.toString()); + return null; + } + } + + /** * Invokes json2xml(String, Boolean) defaulting to 'pretty' output. * * @param jsonStr String containing the XML doc @@ -111,23 +264,43 @@ public class JsonUtils { public static String json2xml(String jsonStr) { return json2xml(jsonStr, true); } - + /** - * Uses the JSONObject static method to convert a JSON doc to XML. + * Returns an Iterator over the JSON keys in the specified JSON doc. * * @param jsonStr String containing the JSON doc * @return Iterator over the JSON keys + * @throws JSONException if the doc cannot be parsed */ - public static Iterator <String> getJsonIterator(String jsonStr) { -// String isDebugLogEnabled = "true"; - try { - JSONObject json = new JSONObject(jsonStr); - return json.keys(); - - } catch (Exception e){ - msoLogger.debug("getJsonIterator(): unable to parse json to retrieve the keys iterator. Exception was: " + e.toString()); - return null; + public static Iterator <String> getJsonIterator(String jsonStr) throws JSONException { + return new JSONObject(jsonStr).keys(); + } + + /** + * Returns the name of the "root" property in the specified JSON doc. The + * "root" property is the single top-level property in the JSON doc. An + * exception is thrown if the doc is empty or if it contains more than one + * top-level property. + * + * @param jsonStr String containing the JSON doc + * @return the name of the "root" property + * @throws JSONException if the doc cannot be parsed, or if it is empty, or if + * it contains more than one top-level property + */ + public static String getJsonRootProperty(String jsonStr) throws JSONException { + Iterator<String> iter = getJsonIterator(jsonStr); + + if (!iter.hasNext()) { + throw new JSONException("Empty JSON object"); } + + String rootPropertyName = iter.next(); + + if (iter.hasNext()) { + throw new JSONException("JSON object has more than one root property"); + } + + return rootPropertyName; } /** @@ -161,11 +334,73 @@ public class JsonUtils { } return null; } + + + /** + * Invokes the getJsonRawValue() method with the wrap flag set to true + * and returns the String equivalent of the json node object returned. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static String getJsonNodeValue(String jsonStr, String keys) { +// String isDebugLogEnabled = "true"; + try { + Object rawValue = getJsonRawValue(jsonStr, keys, true); + if (rawValue == null) { + return null; + } else { + if (rawValue instanceof String) { + msoLogger.debug("getJsonNodeValue(): the raw value is a String Object=" + ((String) rawValue).toString()); + return (String) rawValue; + } else { + msoLogger.debug("getJsonNodeValue(): the raw value is NOT a String Object=" + rawValue.toString()); + return rawValue.toString(); + } + } + } catch (Exception e) { + msoLogger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field=" + keys + ". Exception was: " + e.toString()); + } + return null; + } /** - * Invokes the getJsonRawValue() method to obtain the JSONArray associated with - * the specified keys. The JSONArray is then walked to retrieve the content value of - * the specified field name. + * Invokes the getJsonRawValue() method and returns the String equivalent of + * the object returned. + * + * TBD: May need separate methods for boolean, float, and integer fields if the + * String representation is not sufficient to meet client needs. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static int getJsonIntValue(String jsonStr, String keys) { +// String isDebugLogEnabled = "true"; + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return 0; + } else { + if (rawValue instanceof Integer) { + msoLogger.debug("getJsonValue(): the raw value is an Integer Object=" + ((String) rawValue).toString()); + return (Integer) rawValue; + } else { + msoLogger.debug("getJsonValue(): the raw value is NOT an Integer Object=" + rawValue.toString()); + return 0; + } + } + } catch (Exception e) { + msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); + } + return 0; + } + + /** + * Invokes the getJsonParamValue() method to obtain the JSONArray associated with + * the specified keys. The JSONArray is then walked to retrieve the first array + * value associated with the specified field name (index=0). * * @param jsonStr String containing the JSON doc * @param keys full key path to the target value in the format of "key1.key2.key3..." @@ -173,6 +408,21 @@ public class JsonUtils { * @return String param value associated with field name */ public static String getJsonParamValue(String jsonStr, String keys, String name) { + return getJsonParamValue(jsonStr, keys, name, 0); + } + + /** + * Invokes the getJsonRawValue() method to obtain the JSONArray associated with + * the specified keys. The JSONArray is then walked to retrieve the nth array + * value associated with the specified field name and index + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @param name field name for the param to be retrieved + * @param index the nth param associated with name starting at 0 + * @return String param value associated with field name + */ + public static String getJsonParamValue(String jsonStr, String keys, String name, int index) { // String isDebugLogEnabled = "true"; try { Object rawValue = getJsonRawValue(jsonStr, keys); @@ -181,14 +431,28 @@ public class JsonUtils { } else { if (rawValue instanceof JSONArray) { msoLogger.debug("getJsonParamValue(): keys=" + keys + " points to JSONArray: " + ((JSONArray) rawValue).toString()); - for (int i = 0; i < ((JSONArray) rawValue).length(); i++) { + int arrayLen = ((JSONArray) rawValue).length(); + if (index < 0 || arrayLen < index+1) { + msoLogger.debug("getJsonParamValue(): index: " + index + " is out of bounds for array size of " + arrayLen); + return null; + } + int foundCnt = 0; + for (int i = 0; i < arrayLen; i++) { msoLogger.debug("getJsonParamValue(): index: " + i + ", value: " + ((JSONArray) rawValue).get(i).toString()); if (((JSONArray) rawValue).get(i) instanceof JSONObject) { msoLogger.debug("getJsonParamValue(): index: " + i + " is a JSONObject"); JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i); - if (jsonObj.get("name").equals(name)) { - msoLogger.debug("getJsonParamValue(): found value: " + (String) jsonObj.get("content") + " for name: " + name); - return (String) jsonObj.get("content"); + String parmValue = jsonObj.get(name).toString(); + if (parmValue != null) { + msoLogger.debug("getJsonParamValue(): found value: " + parmValue + " for name: " + name + " and index: " + i); + if (foundCnt == index) { + return parmValue; + } else { + foundCnt++; + continue; + } + } else { + continue; } } else { msoLogger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject=" + rawValue.toString()); @@ -276,6 +540,49 @@ public class JsonUtils { } /** + * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the + * single key/field name specified. Returns the associated value if found or null if the key is not found + * + * @param jsonObj JSONObject representation of the the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) { +// String isDebugLogEnabled = "true"; + Integer keyValue = 0; + try { + if (jsonObj.has(key)) { + msoLogger.debug("getJsonValueForKey(): found value for key=" + key); + return ((Integer) jsonObj.get(key)); + } else { + msoLogger.debug("getJsonValueForKey(): iterating over the keys"); + Iterator <String> itr = jsonObj.keys(); + while (itr.hasNext()) { + String nextKey = (String) itr.next(); + Object obj = jsonObj.get(nextKey); + if (obj instanceof JSONObject) { + msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call"); + keyValue = getJsonIntValueForKey((JSONObject) obj, key); + if (keyValue != null) { + msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key); + break; + } + } else { + msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key"); + } + } + } + } catch (JSONException je) { + // JSONObject::get() throws this exception if one of the specified keys is not found + msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key); + keyValue = null; + } catch (Exception e) { + msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString()); + } + return keyValue; + } + + /** * Boolean method to determine if a key path is valid for the JSON doc. Invokes * getJsonValue(). * @@ -365,6 +672,22 @@ public class JsonUtils { * @return Object field value associated with keys */ private static Object getJsonRawValue(String jsonStr, String keys) { + return getJsonRawValue(jsonStr, keys, false); + } + + /** + * Walks the JSON doc using the full key path to retrieve the associated + * value. All but the last key points to the 'parent' object name(s) in order + * in the JSON hierarchy with the last key pointing to the target value. + * The value returned is a Java object. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped" + * Note: wrap does not apply to returned scalar values + * @return Object field value associated with keys + */ + private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) { // String isDebugLogEnabled = "true"; String keyStr = ""; try { @@ -383,11 +706,19 @@ public class JsonUtils { return keyValue; } } - // we should not hit this point: either the key points to a valid value and - // we return it above or the key is invalid and we handle the JSONException - // below and return null - return null; - + // return the json 'node' that the key points to + // note: since this is a json object and not a scalar value, + // use the wrap flag to determine if the object should + // be wrapped with a root node value + // (the last key in the keys String) + if (wrap) { + JSONObject wrappedJsonObj = new JSONObject(); + wrappedJsonObj.put(keyStr, jsonObj); + return wrappedJsonObj.toString(); + } else { + return jsonObj.toString(); + } + } catch (JSONException je) { // JSONObject::get() throws this exception if one of the specified keys is not found msoLogger.debug("getJsonRawValue(): caught JSONException attempting to retrieve raw value for key=" + keyStr); @@ -439,5 +770,61 @@ public class JsonUtils { } return null; } + + /** + * This json util method converts a json "Key" and "Value" + * entry Array to a Java map. + * + * @param execution + * @param entryArray - the json value of the entry Array + * + * @return map - a Map containing the entries + * + */ + public Map<String, String> entryArrayToMap(Execution execution, String entryArray) { + msoLogger.debug("Started Entry Array To Map Util Method"); + + Map<String, String> map = new HashMap<String, String>(); + + //Populate Map + String entryListJson = "{ \"entry\":" + entryArray + "}"; + JSONObject obj = new JSONObject(entryListJson); + JSONArray arr = obj.getJSONArray("entry"); + for (int i = 0; i < arr.length(); i++){ + JSONObject jo = arr.getJSONObject(i); + String key = jo.getString("key"); + String value =jo.getString("value"); + map.put(key, value); + } + msoLogger.debug("Outgoing Map is: " + map); + msoLogger.debug("Completed Entry Array To Map Util Method"); + return map; + } + + + /** + * Invokes the getJsonRawValue() method to determine if the + * json element/variable exist. Returns true if the + * json element exist + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return boolean field value associated with keys + */ + public static boolean jsonElementExist(String jsonStr, String keys) { + + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return false; + } else { + return true; + } + } catch (Exception e) { + msoLogger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: " + e.toString()); + } + return true; + } + } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java index 8e3f254def..2453700bce 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java @@ -399,8 +399,8 @@ public class LoggingAndURNMappingPlugin extends AbstractProcessEnginePlugin { MsoLogger.setServiceName("MSO." + prefix.substring(0,prefix.length()-1)); } - String requestId = (String) execution.getVariable("att-mso-request-id"); - String svcid = (String) execution.getVariable("att-mso-service-instance-id"); + String requestId = (String) execution.getVariable("mso-request-id"); + String svcid = (String) execution.getVariable("mso-service-instance-id"); MsoLogger.setLogContext(requestId, svcid); long startTime = startTimes.remove(id); |