Merge "Refactor RequestsDatabase method"
authorChristophe Closset <cc697w@intl.att.com>
Tue, 6 Jun 2017 15:16:42 +0000 (15:16 +0000)
committerGerrit Code Review <gerrit@onap.org>
Tue, 6 Jun 2017 15:16:42 +0000 (15:16 +0000)
LICENSE.txt
bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java
bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java
bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/BaseTask.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/ReadConfigTask.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/ReadFileTask.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java
bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowAsyncInfrastructureResource.java

index cf1d4b6..c847859 100644 (file)
@@ -15,8 +15,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * ============LICENSE_END============================================
- *
- * ECOMP and OpenECOMP are trademarks
- * and service marks of AT&T Intellectual Property.
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  *
  */
\ No newline at end of file
index c0ea0cf..f3ad810 100644 (file)
@@ -26,11 +26,7 @@ import org.camunda.bpm.engine.ProcessEngines;
 \r
 public class WorkflowAsyncCommonResource extends WorkflowAsyncResource {\r
 \r
-       protected ProcessEngineServices getProcessEngineServices() {\r
-               if (pes4junit == null) {\r
-                       return ProcessEngines.getProcessEngine("common");\r
-               } else {\r
-                       return pes4junit;\r
-               }\r
-       }\r
+    protected ProcessEngineServices getProcessEngineServices() {\r
+        return pes4junit.orElse(ProcessEngines.getProcessEngine("common"));\r
+    }\r
 }\r
index b13ac46..1bd1dfd 100644 (file)
@@ -21,6 +21,8 @@ package org.openecomp.mso.bpmn.common.workflow.service;
 \r
 import java.util.HashMap;\r
 import java.util.Map;\r
+import java.util.Objects;\r
+import java.util.Optional;\r
 import java.util.UUID;\r
 \r
 import javax.ws.rs.Consumes;\r
@@ -31,7 +33,6 @@ import javax.ws.rs.Produces;
 import javax.ws.rs.core.Response;\r
 \r
 import org.camunda.bpm.engine.ProcessEngineServices;\r
-import org.camunda.bpm.engine.ProcessEngines;\r
 import org.camunda.bpm.engine.RuntimeService;\r
 import org.camunda.bpm.engine.runtime.ProcessInstance;\r
 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;\r
@@ -54,13 +55,13 @@ import org.slf4j.MDC;
 @Path("/async")\r
 public abstract class WorkflowAsyncResource {
 \r
-       private WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();\r
-       protected ProcessEngineServices pes4junit = null;\r
+       private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();\r
+       protected Optional<ProcessEngineServices> pes4junit = Optional.empty();\r
 \r
-       private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);\r
+       private final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);\r
 \r
        private static final String logMarker = "[WRKFLOW-RESOURCE]";\r
-       private static final int DEFAULT_WAIT_TIME = 30000;     //default wait time\r
+       private static final long DEFAULT_WAIT_TIME = 30000;    //default wait time\r
        \r
        /**\r
         * Asynchronous JAX-RS method that starts a process instance.\r
@@ -75,7 +76,6 @@ public abstract class WorkflowAsyncResource {
        public void startProcessInstanceByKey(final @Suspend(180000) AsynchronousResponse asyncResponse,\r
                        @PathParam("processKey") String processKey, VariableMapImpl variableMap) {\r
        \r
-               WorkflowResponse response = new WorkflowResponse();\r
                long startTime = System.currentTimeMillis();\r
                Map<String, Object> inputVariables = null;\r
                WorkflowContext workflowContext = null;\r
@@ -107,6 +107,7 @@ public abstract class WorkflowAsyncResource {
                        }\r
 \r
                        msoLogger.debug(logMarker + "Exception in startProcessInstance by key");\r
+               WorkflowResponse response = new WorkflowResponse();\r
                        response.setMessage("Fail" );\r
                        response.setResponse("Error occurred while executing the process: " + e);\r
                        response.setMessageCode(500);\r
@@ -205,29 +206,28 @@ public abstract class WorkflowAsyncResource {
                return contextHolder.processCallback(processKey, processInstanceId, requestId, callbackResponse);\r
        }\r
        \r
+    private static String getOrCreate(Map<String, Object> inputVariables, String key) {\r
+        String value = Objects.toString(inputVariables.get(key), null);\r
+        if (value == null) {\r
+            value = UUID.randomUUID().toString();\r
+            inputVariables.put(key, value);\r
+        }\r
+        return value;\r
+    }\r
+       \r
        // Note: the business key is used to identify the process in unit tests\r
-       private String getBusinessKey(Map<String, Object> inputVariables) {\r
-               Object businessKey = inputVariables.get("mso-business-key");\r
-               if (businessKey == null ) {\r
-                       businessKey = UUID.randomUUID().toString();\r
-                       inputVariables.put("mso-business-key",  businessKey);\r
-               }\r
-               return businessKey.toString();\r
+       private static String getBusinessKey(Map<String, Object> inputVariables) {\r
+        return getOrCreate(inputVariables, "mso-business-key");\r
        }\r
 \r
-       private String getRequestId(Map<String, Object> inputVariables) {\r
-               Object requestId = inputVariables.get("mso-request-id");\r
-               if (requestId == null ) {\r
-                       requestId = UUID.randomUUID().toString();\r
-                       inputVariables.put("mso-request-id",  requestId);\r
-               } \r
-               return requestId.toString();\r
+       private static String getRequestId(Map<String, Object> inputVariables) {\r
+        return getOrCreate(inputVariables, "mso-request-id");\r
        }\r
 \r
        private long getWaitTime(Map<String, Object> inputVariables)\r
        {\r
-               String timeout = inputVariables.get("mso-service-request-timeout") == null\r
-                               ? null : inputVariables.get("mso-service-request-timeout").toString();          \r
+           \r
+               String timeout = Objects.toString(inputVariables.get("mso-service-request-timeout"), null);\r
 \r
                if (timeout != null) {\r
                        try {\r
@@ -252,7 +252,7 @@ public abstract class WorkflowAsyncResource {
                \r
        }\r
 \r
-       private void setLogContext(String processKey,\r
+       private static void setLogContext(String processKey,\r
                        Map<String, Object> inputVariables) {\r
                MsoLogger.setServiceName("MSO." + processKey);\r
                if (inputVariables != null) {\r
@@ -260,26 +260,24 @@ public abstract class WorkflowAsyncResource {
                }\r
        }\r
 \r
-       private String getKeyValueFromInputVariables(Map<String,Object> inputVariables, String key) {\r
+       private static String getKeyValueFromInputVariables(Map<String,Object> inputVariables, String key) {\r
                if (inputVariables == null) return "";\r
-               Object requestId = inputVariables.get(key);\r
-               if (requestId != null) return requestId.toString();\r
-               return "N/A";\r
+               return Objects.toString(inputVariables.get(key), "N/A");\r
        }\r
 \r
        private boolean isProcessEnded(String processInstanceId) {\r
                ProcessEngineServices pes = getProcessEngineServices();\r
-               return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null ? true : false ;                \r
+               return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;\r
        }\r
        \r
        \r
        protected abstract ProcessEngineServices getProcessEngineServices();
        \r
        public void setProcessEngineServices4junit(ProcessEngineServices pes) {\r
-               pes4junit = pes;\r
+               pes4junit = Optional.ofNullable(pes);\r
        }\r
 \r
-       private Map<String, Object> getInputVariables(VariableMapImpl variableMap) {\r
+       private static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {\r
                Map<String, Object> inputVariables = new HashMap<String,Object>();\r
                @SuppressWarnings("unchecked")\r
                Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");\r
index 3d7e333..93aa15c 100644 (file)
@@ -72,7 +72,7 @@ public class WorkflowContext implements Delayed {
        @Override\r
        public long getDelay(TimeUnit unit) {\r
                // 0 or negative means this object is considered to be expired\r
-               return unit.convert(startTime + timeout - System.currentTimeMillis(), unit);\r
+               return unit.convert(startTime + timeout - System.currentTimeMillis(), TimeUnit.MILLISECONDS);\r
        }\r
 \r
        /**\r
index 849c8ba..5b43c3f 100644 (file)
@@ -20,6 +20,9 @@
 
 package org.openecomp.mso.bpmn.core;
 
+import java.util.Objects;
+
+import org.camunda.bpm.engine.ProcessEngineException;
 import org.camunda.bpm.engine.delegate.DelegateExecution;
 import org.camunda.bpm.engine.delegate.Expression;
 import org.camunda.bpm.engine.delegate.JavaDelegate;
@@ -185,13 +188,7 @@ public abstract class BaseTask implements JavaDelegate {
        protected String getOptionalStringField(Expression expression,
                        DelegateExecution execution, String fieldName) {
                Object o = getFieldImpl(expression, execution, fieldName, true);
-               if (o instanceof String) {
-                       return (String) o;
-               } else if (o == null) {
-                       return null;
-               } else {
-                       return o.toString();
-               }
+               return Objects.toString(o, null);
        }
        
        /**
@@ -526,4 +523,15 @@ public abstract class BaseTask implements JavaDelegate {
        public String getTaskName() {
                return getClass().getSimpleName();
        }
+
+
+       /**
+        * Check if shouldFail variable is set to true.
+        * @param execution
+        * @return
+        */
+    protected boolean shouldFail(DelegateExecution execution) {
+        Boolean shouldFail = (Boolean) execution.getVariable("shouldFail");
+        return shouldFail != null && shouldFail;
+    }
 }
index b46ffcd..09288f0 100644 (file)
@@ -27,7 +27,6 @@ import java.util.Properties;
 import org.camunda.bpm.engine.ProcessEngineException;
 import org.camunda.bpm.engine.delegate.DelegateExecution;
 import org.camunda.bpm.engine.delegate.Expression;
-
 import org.openecomp.mso.logger.MsoLogger;
 
 /**
@@ -57,38 +56,20 @@ public class ReadConfigTask extends BaseTask {
                        msoLogger.debug("propertiesFile = " + thePropertiesFile);
                }
 
-               Boolean shouldFail = (Boolean) execution.getVariable("shouldFail");
-
-               if (shouldFail != null && shouldFail) {
-                       throw new ProcessEngineException(getClass().getSimpleName() + " Failed");
-               }
+        if (shouldFail(execution)) {
+            throw new ProcessEngineException(getTaskName() + " Failed");
+        }
 
                synchronized (ReadConfigTask.class) {
                        if (properties == null) {
                                properties = new Properties();
 
-                               InputStream stream = null;
-
-                               try {
-                                       stream = getClass().getResourceAsStream(thePropertiesFile);
-
+                               try(InputStream stream = getClass().getResourceAsStream(thePropertiesFile)) {
                                        if (stream == null) {
                                                throw new IOException("Resource not found: " + thePropertiesFile);
                                        }
 
                                        properties.load(stream);
-
-                                       stream.close();
-                                       stream = null;
-
-                               } finally {
-                                       if (stream != null) {
-                                               try {
-                                                       stream.close();
-                                               } catch (Exception e) {
-                                                       // Do nothing
-                                               }
-                                       }
                                }
                        }
                }
index 389fdc0..3adba19 100644 (file)
@@ -24,11 +24,11 @@ import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.util.stream.Collectors;
 
 import org.camunda.bpm.engine.ProcessEngineException;
 import org.camunda.bpm.engine.delegate.DelegateExecution;
 import org.camunda.bpm.engine.delegate.Expression;
-
 import org.openecomp.mso.logger.MsoLogger;
 
 /**
@@ -66,45 +66,21 @@ public class ReadFileTask extends BaseTask {
                                + "file = " + theFile);
                }
 
-               Boolean shouldFail = (Boolean) execution.getVariable("shouldFail");
-
-               if (shouldFail != null && shouldFail) {
-                       throw new ProcessEngineException(getClass().getSimpleName() + " Failed");
-               }
+        if (shouldFail(execution)) {
+            throw new ProcessEngineException(getTaskName() + " Failed");
+        }
 
                Object value = execution.getVariable(theInputVariable);
 
                if (value == null) {
-                       InputStream xmlStream = null;
-
-                       try {
-                               xmlStream = getClass().getResourceAsStream(theFile);
+                       try(InputStream xmlStream = getClass().getResourceAsStream(theFile)) {
 
                                if (xmlStream == null) {
                                        throw new IOException("Resource not found: " + theFile);
                                }
 
                                BufferedReader reader = new BufferedReader(new InputStreamReader(xmlStream));
-                               StringBuilder output = new StringBuilder();
-                               String line;
-
-                               while ((line = reader.readLine()) != null) {
-                                       output.append(line);
-                               }
-
-                               xmlStream.close();
-                               xmlStream = null;
-
-                               value = output.toString();
-
-                       } finally {
-                               if (xmlStream != null) {
-                                       try {
-                                               xmlStream.close();
-                                       } catch (Exception e) {
-                                               // Do nothing
-                                       }
-                               }
+                               value = reader.lines().collect(Collectors.joining());
                        }
                }
                execution.setVariable(theInputVariable, value);
index 31da737..e42806e 100644 (file)
@@ -25,7 +25,6 @@ import java.io.IOException;
 import java.io.InputStream;\r
 import java.math.BigDecimal;\r
 import java.net.URI;\r
-import java.util.Iterator;\r
 \r
 import javax.xml.transform.stream.StreamSource;\r
 \r
@@ -33,7 +32,6 @@ import org.camunda.bpm.engine.ProcessEngineException;
 import org.camunda.bpm.engine.delegate.DelegateExecution;\r
 //import java.util.logging.Logger;\r
 import org.camunda.bpm.engine.delegate.Expression;\r
-\r
 import org.openecomp.mso.logger.MessageEnum;\r
 import org.openecomp.mso.logger.MsoLogger;\r
 \r
@@ -97,11 +95,9 @@ public class XQueryScriptTask extends BaseTask {
                String[] atomicInputVariableArray = (theAtomicInputVariables == null)\r
                        ? new String[0] : theAtomicInputVariables.split(",[ ]*");\r
 \r
-               Boolean shouldFail = (Boolean) execution.getVariable("shouldFail");\r
-\r
-               if (shouldFail != null && shouldFail) {\r
-                       throw new ProcessEngineException(getClass().getSimpleName() + " Failed");\r
-               }\r
+        if (shouldFail(execution)) {\r
+            throw new ProcessEngineException(getTaskName() + " Failed");\r
+        }\r
 \r
                // The script could be compiled once and reused, but we are reading it\r
                // and compiling it every time.\r
@@ -190,9 +186,7 @@ public class XQueryScriptTask extends BaseTask {
 \r
                // Evaluate the query and collect the output.\r
                StringBuilder output = new StringBuilder();\r
-               Iterator<XdmItem> xdmItems = evaluator.iterator();\r
-               while (xdmItems.hasNext()) {\r
-                       XdmItem item = xdmItems.next();\r
+               for(XdmItem item : evaluator) {\r
                        \r
                        if (msoLogger.isDebugEnabled()) {\r
                                msoLogger.debug("XQuery result item = " + item);\r
@@ -218,26 +212,13 @@ public class XQueryScriptTask extends BaseTask {
         */\r
        private XQueryExecutable compile(XQueryCompiler compiler, String resource)\r
                        throws Exception {\r
-               InputStream xqStream = null;\r
-               try {\r
-                       xqStream = getClass().getResourceAsStream(resource);\r
+               try(InputStream xqStream = getClass().getResourceAsStream(resource)) {\r
 \r
                        if (xqStream == null) {\r
                                throw new IOException("Resource not found: " + resource);\r
                        }\r
 \r
-                       XQueryExecutable executable = compiler.compile(xqStream);\r
-                       xqStream.close();\r
-                       xqStream = null;\r
-                       return executable;\r
-               } finally {\r
-                       if (xqStream != null) {\r
-                               try {\r
-                                       xqStream.close();\r
-                               } catch (Exception e) {\r
-                                       // Do nothing\r
-                               }\r
-                       }\r
+                       return compiler.compile(xqStream);\r
                }\r
        }\r
 }
\ No newline at end of file
index 09454f0..0cc81bf 100644 (file)
@@ -40,11 +40,7 @@ import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncResource;
 @Path("/async")\r
 public class WorkflowAsyncInfrastructureResource extends WorkflowAsyncResource {\r
        \r
-       protected ProcessEngineServices getProcessEngineServices() {\r
-               if (pes4junit == null) {\r
-                       return ProcessEngines.getProcessEngine("infrastructure");\r
-               } else {\r
-                       return pes4junit;\r
-               }\r
-       }\r
+    protected ProcessEngineServices getProcessEngineServices() {\r
+        return pes4junit.orElse(ProcessEngines.getProcessEngine("infrastructure"));\r
+    }\r
 }\r