From b6b7bef8bdcad15af01ac88a038dd763ce59f68f Mon Sep 17 00:00:00 2001 From: xg353y Date: Tue, 11 Apr 2017 13:30:42 +0200 Subject: [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 --- .../openecomp/mso/bpmn/core/CamundaDBSetup.java | 88 +++++ .../mso/bpmn/core/HealthCheckHandler.java | 144 +++++-- .../mso/bpmn/core/PropertyConfiguration.java | 24 +- .../mso/bpmn/core/PropertyConfigurationSetup.java | 295 ++++++++++++++ .../openecomp/mso/bpmn/core/XQueryScriptTask.java | 2 +- .../openecomp/mso/bpmn/core/json/JsonUtils.java | 439 +++++++++++++++++++-- .../core/plugins/LoggingAndURNMappingPlugin.java | 4 +- .../openecomp/mso/bpmn/test/CamundaDBSetup.java | 108 ----- .../mso/bpmn/test/PropertyConfigurationSetup.java | 315 --------------- 9 files changed, 927 insertions(+), 492 deletions(-) create mode 100644 bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java create mode 100644 bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfigurationSetup.java delete mode 100644 bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/CamundaDBSetup.java delete mode 100644 bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/PropertyConfigurationSetup.java (limited to 'bpmn/MSOCoreBPMN/src/main/java/org') diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java new file mode 100644 index 0000000000..aba43eb522 --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java @@ -0,0 +1,88 @@ +package org.openecomp.mso.bpmn.core; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +/** + * Sets up the unit test (H2) database for Camunda. + */ +public class CamundaDBSetup { + private static boolean isDBConfigured = false; + + public static synchronized void configure() throws SQLException { + if (isDBConfigured) { + return; + } + + System.out.println("Configuring the Camunda H2 database for MSO"); + + Connection connection = null; + PreparedStatement stmt = null; + + try { + connection = DriverManager.getConnection( + "jdbc:h2:mem:camunda;DB_CLOSE_DELAY=-1", "sa", ""); + + stmt = connection.prepareStatement("delete from ACT_HI_VARINST"); + stmt.executeUpdate(); + stmt.close(); + stmt = null; + + stmt = connection.prepareStatement("ALTER TABLE ACT_HI_VARINST alter column TEXT_ 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(); + stmt.close(); + stmt = null; + + stmt = connection.prepareStatement("ALTER TABLE ACT_HI_DETAIL alter column TEXT_ 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(); + stmt.close(); + stmt = null; + + connection.close(); + connection = null; + + isDBConfigured = true; + } catch (SQLException e) { + System.out.println("CamundaDBSetup caught " + e.getClass().getSimpleName()); + e.printStackTrace(); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (Exception e) { + // Ignore + } + } + + if (connection != null) { + try { + connection.close(); + } catch (Exception e) { + // Ignore + } + } + } + } +} \ 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 = "Health CheckApplication ready"; private static final String NOT_FOUND = "Application Not StartedApplication not started. Properties file missing or invalid or database Connection failed"; @@ -66,6 +76,59 @@ public class HealthCheckHandler { .entity (NOT_FOUND) .build (); + @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 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") @@ -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("\n"); + payload.append("\n"); payload.append("\n"); payload.append("\n"); payload.append("\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("") + 8, result.indexOf("")); + 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("") + 8, result.indexOf("")); + + 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 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 timerTaskMap = new HashMap(); - + /** * 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/core/PropertyConfigurationSetup.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfigurationSetup.java new file mode 100644 index 0000000000..f58efe79c8 --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/PropertyConfigurationSetup.java @@ -0,0 +1,295 @@ +package org.openecomp.mso.bpmn.core; + +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.openecomp.mso.bpmn.core.PropertyConfiguration; + +/** + * Sets up mso.bpmn.properties and mso.bpmn.urn.properties for unit tests. + */ +public class PropertyConfigurationSetup { + + private static Path msoConfigPath = null; + private static Path bpmnPropertiesPath = null; + private static Path bpmnUrnPropertiesPath = null; + private static boolean modifiedConfiguration = false; + + /** + * Ensures that the the PropertyConfiguration is initialized and that the + * property data is reset to initial values. Any extra properties that are + * specified will be merged with the initial values. The following example + * shows how a test can specify a replacement URN mapping property. + *
+	 *     Map urnProperties =
+	 *         PropertyConfigurationSetup.createBpmnUrnProperties();
+	 *     urnProperties.add("mso.po.timeout", "PT1M");
+	 *     PropertyConfiguration.init(urnProperties);
+	 * 
+ * @param args one or more maps created with createBpmnProperties() + * and/or createBpmnUrnProperties() + */ + public static synchronized void init(Object ... args) throws IOException { + + Map extraBpmnProperties = null; + Map extraBpmnUrnProperties = null; + + boolean propertiesSpecified = false; + + for (Object arg : args) { + @SuppressWarnings("unchecked") + Map properties = (Map) arg; + + String type = properties.get("PROPERTIES-TYPE"); + + if (PropertyConfiguration.MSO_BPMN_PROPERTIES.equals(type)) { + if (properties.size() > 1) { + extraBpmnProperties = properties; + propertiesSpecified = false; + } + } else if (PropertyConfiguration.MSO_BPMN_URN_PROPERTIES.equals(type)) { + if (properties.size() > 1) { + extraBpmnUrnProperties = properties; + propertiesSpecified = false; + } + } else { + throw new IllegalArgumentException("Not a supported PROPERTIES-TYPE map"); + } + } + + // There are three cases in which we need to change the existing configuration: + // 1) There is no existing configuration, i.e. first time setup + // 2) The existing configuration was modified, i.e. it has non-default values + // 3) Non-default values are specified for this initialization + + if (msoConfigPath == null || modifiedConfiguration || propertiesSpecified) { + modifiedConfiguration = propertiesSpecified; + + Path bpmnPropertiesSourcePath = Paths.get("src", "test", "resources", "mso.bpmn.properties"); + Path bpmnUrnPropertiesSourcePath = Paths.get("src", "test", "resources", "mso.bpmn.urn.properties"); + + if (msoConfigPath == null) { + // Initialize from scratch. + msoConfigPath = Files.createTempDirectory("mso-config-path-"); + System.setProperty("mso.config.path", msoConfigPath.toString()); + msoConfigPath.toFile().deleteOnExit(); + + bpmnPropertiesPath = msoConfigPath.resolve("mso.bpmn.properties"); + mergeCopy(bpmnPropertiesSourcePath, extraBpmnProperties, bpmnPropertiesPath); + bpmnPropertiesPath.toFile().deleteOnExit(); + + bpmnUrnPropertiesPath = msoConfigPath.resolve("mso.bpmn.urn.properties"); + mergeCopy(bpmnUrnPropertiesSourcePath, extraBpmnUrnProperties, bpmnUrnPropertiesPath); + bpmnUrnPropertiesPath.toFile().deleteOnExit(); + + PropertyConfiguration.getInstance(); + } else { + // Just reset the data. + PropertyConfiguration.getInstance().clearCache(); + mergeCopy(bpmnPropertiesSourcePath, extraBpmnProperties, bpmnPropertiesPath); + mergeCopy(bpmnUrnPropertiesSourcePath, extraBpmnUrnProperties, bpmnUrnPropertiesPath); + } + } + } + + /** + * Resets the PropertyConfiguration to its initial state, as if it had never + * been started. Note that this is a very expensive option and should not + * be needed by most unit tests. + * @throws IOException + */ + public static synchronized void nuke() throws IOException { + if (msoConfigPath == null) { + return; + } + + PropertyConfiguration.getInstance().shutDown(); + + bpmnUrnPropertiesPath.toFile().delete(); + bpmnUrnPropertiesPath = null; + + bpmnPropertiesPath.toFile().delete(); + bpmnPropertiesPath = null; + + msoConfigPath.toFile().delete(); + msoConfigPath = null; + + System.setProperty("mso.config.path", null); + + modifiedConfiguration = false; + } + + /** + * Create a map to hold properties to be added to mso.bpmn.properties. + */ + public static Map createBpmnProperties() { + Map properties = new HashMap(); + properties.put("PROPERTIES-TYPE", PropertyConfiguration.MSO_BPMN_PROPERTIES); + return properties; + } + + /** + * Create a map to hold properties to be added to mso.bpmn.urn.properties. + */ + public static Map createBpmnUrnProperties() { + Map properties = new HashMap(); + properties.put("PROPERTIES-TYPE", PropertyConfiguration.MSO_BPMN_URN_PROPERTIES); + return properties; + } + + /** + * Adds (or replaces) the specified values in the mso.bpmn.urn.properties file. + * Note that properties added this way may take some time to be loaded by the + * PropertyConfiguration, just like they do when a property file is updated on + * a real MSO system. This method will optionally wait for the new properties + * to be loaded. Timeout results in an IOException. + * @param values new properties + * @param wait maximum amount of time to wait for new properties to be loaded, + * in milliseconds. A value of zero means, "Do not wait." + * @throws IOException + */ + public static synchronized void addProperties(Map properties, long wait) + throws IOException, InterruptedException { + + if (msoConfigPath == null) { + throw new IllegalStateException(); + } + + String type = properties.get("PROPERTIES-TYPE"); + Path path; + + if (PropertyConfiguration.MSO_BPMN_PROPERTIES.equals(type)) { + path = bpmnPropertiesPath; + } else if (PropertyConfiguration.MSO_BPMN_URN_PROPERTIES.equals(type)) { + path = bpmnUrnPropertiesPath; + } else { + throw new IllegalArgumentException("Not a supported PROPERTIES-TYPE map"); + } + + String oldTimestamp = PropertyConfiguration.getInstance().getProperties(type) + .get(PropertyConfiguration.TIMESTAMP_PROPERTY); + + modifiedConfiguration = true; + addProperties(properties, path); + + if (wait <= 0) { + return; + } + + long endTime = System.currentTimeMillis() + wait; + + while (true) { + Thread.sleep(250); + + String newTimestamp = PropertyConfiguration.getInstance().getProperties(type) + .get(PropertyConfiguration.TIMESTAMP_PROPERTY); + + if (newTimestamp != oldTimestamp) { + return; + } + + long now = System.currentTimeMillis(); + + if (now >= endTime) { + throw new IOException("Timed out after " + wait + + "ms waiting for PropertyConfiguration change"); + } + } + } + + /** + * Helper method that adds properties to the specified file. + */ + private static void addProperties(Map values, Path path) + throws IOException { + + FileReader fileReader = null; + FileOutputStream outputStream = null; + + try { + fileReader = new FileReader(path.toFile()); + Properties properties = new Properties(); + properties.load(fileReader); + + for (String key : values.keySet()) { + if (!key.equals("PROPERTIES-TYPE")) { + properties.setProperty(key, values.get(key)); + } + } + + outputStream = new FileOutputStream(path.toFile()); + properties.store(outputStream, "Custom Test Properties"); + } finally { + if (fileReader != null) { + try { + fileReader.close(); + } catch (IOException e) { + // Ignore + } + } + + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + // Ignore + } + } + } + } + + /** + * Helper method that copies properties from the specified source file, and + * optionally merges them with the specified extra values, then writes the + * whole mess to the destination file. + */ + private static void mergeCopy(Path sourcePath, Map extraValues, Path destPath) + throws IOException { + if (extraValues == null || extraValues.isEmpty()) { + Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING); + return; + } + + FileReader fileReader = null; + FileOutputStream outputStream = null; + + try { + fileReader = new FileReader(sourcePath.toFile()); + Properties properties = new Properties(); + properties.load(fileReader); + + for (String key : extraValues.keySet()) { + if (!key.equals("PROPERTIES-TYPE")) { + properties.setProperty(key, extraValues.get(key)); + } + } + + outputStream = new FileOutputStream(destPath.toFile()); + properties.store(outputStream, "Custom Test Properties"); + } finally { + if (fileReader != null) { + try { + fileReader.close(); + } catch (IOException e) { + // Ignore + } + } + + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + // Ignore + } + } + } + } +} \ 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()); @@ -102,6 +107,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 keys; + int len; + String str; + Object curObj; + if (obj instanceof JSONObject) { + // msoLogger.debug("toXMLString(): is a JSONObject"); + // append "" 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(""); + } 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(""); + } + } + } + } else if (curObj.equals("")) { + // append a closing tag "" 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 "" to the XML output +// msoLogger.debug("toXMLString(): adding closing tagName: " + 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 + ""; + } + } + + /** + * 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. * @@ -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 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 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 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()); @@ -275,6 +539,49 @@ public class JsonUtils { return keyValue; } + /** + * 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 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 entryArrayToMap(Execution execution, String entryArray) { + msoLogger.debug("Started Entry Array To Map Util Method"); + + Map map = new HashMap(); + + //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); 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/test/CamundaDBSetup.java deleted file mode 100644 index 13eed2d530..0000000000 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/CamundaDBSetup.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============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; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -/** - * Sets up the unit test (H2) database for Camunda. - */ -public class CamundaDBSetup { - private static boolean isDBConfigured = false; - - public static synchronized void configure() throws SQLException { - if (isDBConfigured) { - return; - } - - System.out.println("Configuring the Camunda H2 database for MSO"); - - Connection connection = null; - PreparedStatement stmt = null; - - try { - connection = DriverManager.getConnection( - "jdbc:h2:mem:camunda;DB_CLOSE_DELAY=-1", "sa", ""); - - stmt = connection.prepareStatement("delete from ACT_HI_VARINST"); - stmt.executeUpdate(); - stmt.close(); - stmt = null; - - stmt = connection.prepareStatement("ALTER TABLE ACT_HI_VARINST alter column TEXT_ 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(); - stmt.close(); - stmt = null; - - stmt = connection.prepareStatement("ALTER TABLE ACT_HI_DETAIL alter column TEXT_ 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(); - stmt.close(); - stmt = null; - - connection.close(); - connection = null; - - isDBConfigured = true; - } catch (SQLException e) { - System.out.println("CamundaDBSetup caught " + e.getClass().getSimpleName()); - e.printStackTrace(); - } finally { - if (stmt != null) { - try { - stmt.close(); - } catch (Exception e) { - // Ignore - } - } - - if (connection != null) { - try { - connection.close(); - } catch (Exception e) { - // Ignore - } - } - } - } -} 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/test/PropertyConfigurationSetup.java deleted file mode 100644 index 6f1cd7d8cc..0000000000 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/test/PropertyConfigurationSetup.java +++ /dev/null @@ -1,315 +0,0 @@ -/*- - * ============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; - -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.openecomp.mso.bpmn.core.PropertyConfiguration; - -/** - * Sets up mso.bpmn.properties and mso.bpmn.urn.properties for unit tests. - */ -public class PropertyConfigurationSetup { - - private static Path msoConfigPath = null; - private static Path bpmnPropertiesPath = null; - private static Path bpmnUrnPropertiesPath = null; - private static boolean modifiedConfiguration = false; - - /** - * Ensures that the the PropertyConfiguration is initialized and that the - * property data is reset to initial values. Any extra properties that are - * specified will be merged with the initial values. The following example - * shows how a test can specify a replacement URN mapping property. - *
-	 *     Map urnProperties =
-	 *         PropertyConfigurationSetup.createBpmnUrnProperties();
-	 *     urnProperties.add("mso.po.timeout", "PT1M");
-	 *     PropertyConfiguration.init(urnProperties);
-	 * 
- * @param args one or more maps created with createBpmnProperties() - * and/or createBpmnUrnProperties() - */ - public static synchronized void init(Object ... args) throws IOException { - - Map extraBpmnProperties = null; - Map extraBpmnUrnProperties = null; - - boolean propertiesSpecified = false; - - for (Object arg : args) { - @SuppressWarnings("unchecked") - Map properties = (Map) arg; - - String type = properties.get("PROPERTIES-TYPE"); - - if (PropertyConfiguration.MSO_BPMN_PROPERTIES.equals(type)) { - if (properties.size() > 1) { - extraBpmnProperties = properties; - propertiesSpecified = false; - } - } else if (PropertyConfiguration.MSO_BPMN_URN_PROPERTIES.equals(type)) { - if (properties.size() > 1) { - extraBpmnUrnProperties = properties; - propertiesSpecified = false; - } - } else { - throw new IllegalArgumentException("Not a supported PROPERTIES-TYPE map"); - } - } - - // There are three cases in which we need to change the existing configuration: - // 1) There is no existing configuration, i.e. first time setup - // 2) The existing configuration was modified, i.e. it has non-default values - // 3) Non-default values are specified for this initialization - - if (msoConfigPath == null || modifiedConfiguration || propertiesSpecified) { - modifiedConfiguration = propertiesSpecified; - - Path bpmnPropertiesSourcePath = Paths.get("src", "test", "resources", "mso.bpmn.properties"); - Path bpmnUrnPropertiesSourcePath = Paths.get("src", "test", "resources", "mso.bpmn.urn.properties"); - - if (msoConfigPath == null) { - // Initialize from scratch. - msoConfigPath = Files.createTempDirectory("mso-config-path-"); - System.setProperty("mso.config.path", msoConfigPath.toString()); - msoConfigPath.toFile().deleteOnExit(); - - bpmnPropertiesPath = msoConfigPath.resolve("mso.bpmn.properties"); - mergeCopy(bpmnPropertiesSourcePath, extraBpmnProperties, bpmnPropertiesPath); - bpmnPropertiesPath.toFile().deleteOnExit(); - - bpmnUrnPropertiesPath = msoConfigPath.resolve("mso.bpmn.urn.properties"); - mergeCopy(bpmnUrnPropertiesSourcePath, extraBpmnUrnProperties, bpmnUrnPropertiesPath); - bpmnUrnPropertiesPath.toFile().deleteOnExit(); - - PropertyConfiguration.getInstance(); - } else { - // Just reset the data. - PropertyConfiguration.getInstance().clearCache(); - mergeCopy(bpmnPropertiesSourcePath, extraBpmnProperties, bpmnPropertiesPath); - mergeCopy(bpmnUrnPropertiesSourcePath, extraBpmnUrnProperties, bpmnUrnPropertiesPath); - } - } - } - - /** - * Resets the PropertyConfiguration to its initial state, as if it had never - * been started. Note that this is a very expensive option and should not - * be needed by most unit tests. - * @throws IOException - */ - public static synchronized void nuke() throws IOException { - if (msoConfigPath == null) { - return; - } - - PropertyConfiguration.getInstance().shutDown(); - - bpmnUrnPropertiesPath.toFile().delete(); - bpmnUrnPropertiesPath = null; - - bpmnPropertiesPath.toFile().delete(); - bpmnPropertiesPath = null; - - msoConfigPath.toFile().delete(); - msoConfigPath = null; - - System.setProperty("mso.config.path", null); - - modifiedConfiguration = false; - } - - /** - * Create a map to hold properties to be added to mso.bpmn.properties. - */ - public static Map createBpmnProperties() { - Map properties = new HashMap(); - properties.put("PROPERTIES-TYPE", PropertyConfiguration.MSO_BPMN_PROPERTIES); - return properties; - } - - /** - * Create a map to hold properties to be added to mso.bpmn.urn.properties. - */ - public static Map createBpmnUrnProperties() { - Map properties = new HashMap(); - properties.put("PROPERTIES-TYPE", PropertyConfiguration.MSO_BPMN_URN_PROPERTIES); - return properties; - } - - /** - * Adds (or replaces) the specified values in the mso.bpmn.urn.properties file. - * Note that properties added this way may take some time to be loaded by the - * PropertyConfiguration, just like they do when a property file is updated on - * a real MSO system. This method will optionally wait for the new properties - * to be loaded. Timeout results in an IOException. - * @param values new properties - * @param wait maximum amount of time to wait for new properties to be loaded, - * in milliseconds. A value of zero means, "Do not wait." - * @throws IOException - */ - public static synchronized void addProperties(Map properties, long wait) - throws IOException, InterruptedException { - - if (msoConfigPath == null) { - throw new IllegalStateException(); - } - - String type = properties.get("PROPERTIES-TYPE"); - Path path; - - if (PropertyConfiguration.MSO_BPMN_PROPERTIES.equals(type)) { - path = bpmnPropertiesPath; - } else if (PropertyConfiguration.MSO_BPMN_URN_PROPERTIES.equals(type)) { - path = bpmnUrnPropertiesPath; - } else { - throw new IllegalArgumentException("Not a supported PROPERTIES-TYPE map"); - } - - String oldTimestamp = PropertyConfiguration.getInstance().getProperties(type) - .get(PropertyConfiguration.TIMESTAMP_PROPERTY); - - modifiedConfiguration = true; - addProperties(properties, path); - - if (wait <= 0) { - return; - } - - long endTime = System.currentTimeMillis() + wait; - - while (true) { - Thread.sleep(250); - - String newTimestamp = PropertyConfiguration.getInstance().getProperties(type) - .get(PropertyConfiguration.TIMESTAMP_PROPERTY); - - if (newTimestamp != oldTimestamp) { - return; - } - - long now = System.currentTimeMillis(); - - if (now >= endTime) { - throw new IOException("Timed out after " + wait - + "ms waiting for PropertyConfiguration change"); - } - } - } - - /** - * Helper method that adds properties to the specified file. - */ - private static void addProperties(Map values, Path path) - throws IOException { - - FileReader fileReader = null; - FileOutputStream outputStream = null; - - try { - fileReader = new FileReader(path.toFile()); - Properties properties = new Properties(); - properties.load(fileReader); - - for (String key : values.keySet()) { - if (!key.equals("PROPERTIES-TYPE")) { - properties.setProperty(key, values.get(key)); - } - } - - outputStream = new FileOutputStream(path.toFile()); - properties.store(outputStream, "Custom Test Properties"); - } finally { - if (fileReader != null) { - try { - fileReader.close(); - } catch (IOException e) { - // Ignore - } - } - - if (outputStream != null) { - try { - outputStream.close(); - } catch (IOException e) { - // Ignore - } - } - } - } - - /** - * Helper method that copies properties from the specified source file, and - * optionally merges them with the specified extra values, then writes the - * whole mess to the destination file. - */ - private static void mergeCopy(Path sourcePath, Map extraValues, Path destPath) - throws IOException { - if (extraValues == null || extraValues.isEmpty()) { - Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING); - return; - } - - FileReader fileReader = null; - FileOutputStream outputStream = null; - - try { - fileReader = new FileReader(sourcePath.toFile()); - Properties properties = new Properties(); - properties.load(fileReader); - - for (String key : extraValues.keySet()) { - if (!key.equals("PROPERTIES-TYPE")) { - properties.setProperty(key, extraValues.get(key)); - } - } - - outputStream = new FileOutputStream(destPath.toFile()); - properties.store(outputStream, "Custom Test Properties"); - } finally { - if (fileReader != null) { - try { - fileReader.close(); - } catch (IOException e) { - // Ignore - } - } - - if (outputStream != null) { - try { - outputStream.close(); - } catch (IOException e) { - // Ignore - } - } - } - } -} -- cgit 1.2.3-korg