aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service
diff options
context:
space:
mode:
Diffstat (limited to 'bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service')
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java421
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/ProcessEngineAwareService.java64
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java83
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java249
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java33
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java289
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java52
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java96
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java188
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java108
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java615
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java46
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java97
13 files changed, 0 insertions, 2341 deletions
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java
deleted file mode 100644
index f61c692775..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.camunda.bpm.BpmPlatform;
-import org.camunda.bpm.engine.MismatchingMessageCorrelationException;
-import org.camunda.bpm.engine.OptimisticLockingException;
-import org.camunda.bpm.engine.RuntimeService;
-import org.camunda.bpm.engine.runtime.Execution;
-import org.camunda.bpm.engine.runtime.MessageCorrelationResult;
-import org.openecomp.mso.bpmn.core.PropertyConfiguration;
-import org.openecomp.mso.logger.MessageEnum;
-import org.openecomp.mso.logger.MsoLogger;
-
-/**
- * Abstract base class for callback services.
- */
-public abstract class AbstractCallbackService extends ProcessEngineAwareService {
- public static final long DEFAULT_TIMEOUT_SECONDS = 60;
- public static final long FAST_POLL_DUR_SECONDS = 5;
- public static final long FAST_POLL_INT_MS = 100;
- public static final long SLOW_POLL_INT_MS = 1000;
-
- private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
-
- /**
- * Parameterized callback handler.
- */
- protected CallbackResult handleCallback(String method, Object message,
- String messageEventName, String messageVariable,
- String correlationVariable, String correlationValue,
- String logMarker) {
-
- return handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker, null);
- }
-
- /**
- * Parameterized callback handler.
- */
- protected CallbackResult handleCallback(String method, Object message,
- String messageEventName, String messageVariable,
- String correlationVariable, String correlationValue,
- String logMarker, Map<String, Object> injectedVariables) {
-
- long startTime = System.currentTimeMillis();
-
- LOGGER.debug(logMarker + " " + method + " received message: "
- + (message == null ? "" : System.lineSeparator()) + message);
-
- try {
- Map<String, Object> variables = new HashMap<>();
-
- if (injectedVariables != null) {
- variables.putAll(injectedVariables);
- }
-
- variables.put(correlationVariable, correlationValue);
- variables.put(messageVariable, message == null ? null : message.toString());
-
- boolean ok = correlate(messageEventName, correlationVariable,
- correlationValue, variables, logMarker);
-
- if (!ok) {
- String msg = "No process is waiting for " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue + "'";
- logCallbackError(method, startTime, msg);
- return new CallbackError(msg);
- }
-
- logCallbackSuccess(method, startTime);
- return new CallbackSuccess();
- } catch (Exception e) {
- LOGGER.debug("Exception :",e);
- String msg = "Caught " + e.getClass().getSimpleName()
- + " processing " + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "'";
- logCallbackError(method, startTime, msg);
- return new CallbackError(msg);
- }
- }
-
- /**
- * Performs message correlation. Waits a limited amount of time for
- * a process to become ready for correlation. The return value indicates
- * whether or not a process was found to receive the message. Due to the
- * synchronous nature of message injection in Camunda, by the time this
- * method returns, one of 3 things will have happened: (1) the process
- * received the message and ended, (2) the process received the message
- * and reached an activity that suspended, or (3) an exception occurred
- * during correlation or while the process was executing. Correlation
- * exceptions are handled differently from process execution exceptions.
- * Correlation exceptions are thrown so the client knows something went
- * wrong with the delivery of the message. Process execution exceptions
- * are logged but not thrown.
- * @param messageEventName the message event name
- * @param correlationVariable the process variable used as the correlator
- * @param correlationValue the correlation value
- * @param variables variables to inject into the process
- * @param logMarker a marker for debug logging
- * @return true if a process could be found, false if not
- * @throws Exception for correlation errors
- */
- protected boolean correlate(String messageEventName, String correlationVariable,
- String correlationValue, Map<String, Object> variables, String logMarker)
- throws Exception {
- try{
- LOGGER.debug(logMarker + " Attempting to find process waiting"
- + " for " + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "'");
-
- RuntimeService runtimeService =
- getProcessEngineServices().getRuntimeService();
-
- Map<String, String> properties =
- PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties");
-
- long timeout = DEFAULT_TIMEOUT_SECONDS;
-
- // The code is here in case we ever need to change the default.
- String s = properties.get("mso.correlation.timeout");
- if (s != null) {
- try {
- timeout = Long.parseLong(s);
- } catch (NumberFormatException e) {
- // Ignore
- }
- }
-
- long now = System.currentTimeMillis();
- long fastPollEndTime = now + (FAST_POLL_DUR_SECONDS * 1000);
- long endTime = now + (timeout * 1000);
- long sleep = FAST_POLL_INT_MS;
-
- List<Execution> waitingProcesses = null;
- Exception queryException = null;
- int queryCount = 0;
- int queryFailCount = 0;
-
- while (true) {
- try {
- ++queryCount;
- waitingProcesses = runtimeService.createExecutionQuery()
- .messageEventSubscriptionName(messageEventName)
- .processVariableValueEquals(correlationVariable, correlationValue)
- .list();
- } catch (Exception e) {
- ++queryFailCount;
- queryException = e;
- }
-
- if (waitingProcesses != null && waitingProcesses.size() > 0) {
- break;
- }
-
- if (now > endTime - sleep) {
- break;
- }
-
- Thread.sleep(sleep);
- now = System.currentTimeMillis();
-
- if (now > fastPollEndTime) {
- sleep = SLOW_POLL_INT_MS;
- }
- }
-
- if (waitingProcesses == null) {
- waitingProcesses = new ArrayList<Execution>(0);
- }
-
- int count = waitingProcesses.size();
-
- List<ExecInfo> execInfoList = new ArrayList<>(count);
- for (Execution execution : waitingProcesses) {
- execInfoList.add(new ExecInfo(execution));
- }
-
- LOGGER.debug(logMarker + " Found " + count + " process(es) waiting"
- + " for " + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "': " + execInfoList);
-
- if (count == 0) {
- if (queryFailCount > 0) {
- String msg = queryFailCount + "/" + queryCount
- + " execution queries failed attempting to correlate "
- + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "'; last exception was:"
- + queryException;
- LOGGER.debug(msg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, msg, queryException);
- }
-
- return false;
- }
-
- if (count > 1) {
- // Only one process should be waiting. Throw an exception back to the client.
- throw new MismatchingMessageCorrelationException(messageEventName,
- "more than 1 process is waiting with " + correlationVariable
- + " = '" + correlationValue + "'");
- }
-
- // We prototyped an asynchronous solution, i.e. resuming the process
- // flow in a separate thread, but this affected too many existing tests,
- // and we went back to the synchronous solution. The synchronous solution
- // has some troublesome characteristics though. For example, the
- // resumed flow may send request #2 to a remote system before MSO has
- // acknowledged the notification associated with request #1.
-
- try {
- LOGGER.debug(logMarker + " Running " + execInfoList.get(0) + " to receive "
- + messageEventName + " with " + correlationVariable + " = '"
- + correlationValue + "'");
-
- @SuppressWarnings("unused")
- MessageCorrelationResult result = runtimeService
- .createMessageCorrelation(messageEventName)
- .setVariables(variables)
- .processInstanceVariableEquals(correlationVariable, correlationValue)
- .correlateWithResult();
-
- } catch (MismatchingMessageCorrelationException e) {
- // A correlation exception occurred even after we identified
- // one waiting process. Throw it back to the client.
- throw e;
- } catch (OptimisticLockingException ole) {
-
- String msg = "Caught " + ole.getClass().getSimpleName() + " after receiving " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue
- + "': " + ole;
- LOGGER.debug(msg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN CORRELATION ERROR -", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, msg, ole);
-
- //Retry for OptimisticLocking Exceptions
- int retryCount = 0;
- String retryStr = properties.get("mso.bpmn.optimisticlockingexception.retrycount");
- if (retryStr != null) {
- try {
- retryCount = Integer.parseInt(retryStr);
- } catch (NumberFormatException e) {
- // Ignore
- }
- }
-
- LOGGER.debug("Retry correlate for OptimisticLockingException, retryCount:" + retryCount);
-
- for (; retryCount >0 ; retryCount--) {
-
- try{
- Thread.sleep(SLOW_POLL_INT_MS);
-
- @SuppressWarnings("unused")
- MessageCorrelationResult result = runtimeService
- .createMessageCorrelation(messageEventName)
- .setVariables(variables)
- .processInstanceVariableEquals(correlationVariable, correlationValue)
- .correlateWithResult();
- retryCount = 0;
- LOGGER.debug("OptimisticLockingException retry was successful, seting retryCount: " + retryCount);
- } catch (OptimisticLockingException olex) {
- //oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
- String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + olex;
- LOGGER.debug(strMsg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, strMsg, olex);
- } catch (Exception excep) {
- retryCount = 0;
- //oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
- String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + excep;
- LOGGER.debug(strMsg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, strMsg, excep);
- }
-
- }
-
- }catch (Exception e) {
- // This must be an exception from the flow itself. Log it, but don't
- // report it back to the client.
- String msg = "Caught " + e.getClass().getSimpleName() + " running "
- + execInfoList.get(0) + " after receiving " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue
- + "': " + e;
- LOGGER.debug(msg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, msg, e);
- }
- } catch (Exception e) {
- // This must be an exception from the flow itself. Log it, but don't
- // report it back to the client.
- String msg = "Caught " + e.getClass().getSimpleName() + " after receiving " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue
- + "': " + e;
- LOGGER.debug(msg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN CORRELATION ERROR -", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, msg, e);
- }
-
- return true;
- }
-
- /**
- * Records audit and metric events in the log for a callback success.
- * @param method the method name
- * @param startTime the request start time
- */
- protected void logCallbackSuccess(String method, long startTime) {
- LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE,
- MsoLogger.ResponseCode.Suc, "Completed " + method);
-
- LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE,
- MsoLogger.ResponseCode.Suc, "Completed " + method,
- "BPMN", MsoLogger.getServiceName(), null);
- }
-
- /**
- * Records error, audit and metric events in the log for a callback
- * internal error.
- * @param method the method name
- * @param startTime the request start time
- * @param msg the error message
- */
- protected void logCallbackError(String method, long startTime, String msg) {
- logCallbackError(method, startTime, msg, null);
- }
-
- /**
- * Records error, audit and metric events in the log for a callback
- * internal error.
- * @param method the method name
- * @param startTime the request start time
- * @param msg the error message
- * @param e the exception
- */
- protected void logCallbackError(String method, long startTime, String msg, Exception e) {
- if (e == null) {
- LOGGER.error(MessageEnum.BPMN_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, msg);
- } else {
- LOGGER.error(MessageEnum.BPMN_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, msg, e);
- }
-
- LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE,
- MsoLogger.ResponseCode.InternalError, "Completed " + method);
-
- LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE,
- MsoLogger.ResponseCode.InternalError, "Completed " + method,
- "BPMN", MsoLogger.getServiceName(), null);
- }
-
- /**
- * Abstract callback result object.
- */
- protected abstract class CallbackResult {
- }
-
- /**
- * Indicates that callback handling was successful.
- */
- protected class CallbackSuccess extends CallbackResult {
- }
-
- /**
- * Indicates that callback handling failed.
- */
- protected class CallbackError extends CallbackResult {
- private final String errorMessage;
-
- public CallbackError(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
- /**
- * Gets the error message.
- */
- public String getErrorMessage() {
- return errorMessage;
- }
- }
-
- private static class ExecInfo {
- private final Execution execution;
-
- public ExecInfo(Execution execution) {
- this.execution = execution;
- }
-
- @Override
- public String toString() {
- return "Process[" + execution.getProcessInstanceId()
- + ":" + execution.getId() + "]";
- }
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/ProcessEngineAwareService.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/ProcessEngineAwareService.java
deleted file mode 100644
index dbb6674a64..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/ProcessEngineAwareService.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.common.workflow.service;
-
-import java.util.Optional;
-
-import org.camunda.bpm.engine.ProcessEngineServices;
-import org.camunda.bpm.engine.ProcessEngines;
-
-/**
- * Base class for services that must be process-engine aware. The only
- * process engine currently supported is the "default" process engine.
- */
-public class ProcessEngineAwareService {
-
- private final String processEngineName = "default";
- private volatile Optional<ProcessEngineServices> pes4junit = Optional.empty();
-
- /**
- * Gets the process engine name.
- * @return the process engine name
- */
- public String getProcessEngineName() {
- return processEngineName;
- }
-
- /**
- * Gets process engine services.
- * @return process engine services
- */
- public ProcessEngineServices getProcessEngineServices() {
- return pes4junit.orElse(ProcessEngines.getProcessEngine(
- getProcessEngineName()));
- }
-
- /**
- * Allows a particular process engine to be specified, overriding the
- * usual process engine lookup by name. Intended primarily for the
- * unit test environment.
- * @param pes process engine services
- */
- public void setProcessEngineServices4junit(ProcessEngineServices pes) {
- pes4junit = Optional.ofNullable(pes);
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java
deleted file mode 100644
index c5f0d02dff..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import javax.jws.WebMethod;
-import javax.jws.WebParam;
-import javax.jws.WebResult;
-import javax.jws.WebService;
-import javax.ws.rs.core.Context;
-import javax.xml.ws.WebServiceContext;
-
-import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest;
-import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse;
-import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCCallbackAdapterPortType;
-import org.openecomp.mso.logger.MsoLogger;
-
-/**
- * Implementation of SDNCAdapterCallbackService.
- */
-@WebService(serviceName="SDNCAdapterCallbackService", targetNamespace="http://org.openecomp/workflow/sdnc/adapter/schema/v1")
-public class SDNCAdapterCallbackServiceImpl extends AbstractCallbackService implements SDNCCallbackAdapterPortType {
-
- private final String logMarker = "[SDNC-CALLBACK]";
-
- @Context WebServiceContext wsContext;
-
- @WebMethod(operationName = "SDNCAdapterCallback")
- @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse")
- public SDNCAdapterResponse sdncAdapterCallback(
- @WebParam(name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackRequest")
- SDNCAdapterCallbackRequest sdncAdapterCallbackRequest) {
-
- String method = "sdncAdapterCallback";
- Object message = sdncAdapterCallbackRequest;
- String messageEventName = "sdncAdapterCallbackRequest";
- String messageVariable = "sdncAdapterCallbackRequest";
- String correlationVariable = "SDNCA_requestId";
- String correlationValue = sdncAdapterCallbackRequest.getCallbackHeader().getRequestId();
-
- MsoLogger.setServiceName("MSO." + method);
- MsoLogger.setLogContext(correlationValue, "N/A");
-
- CallbackResult result = handleCallback(method, message, messageEventName,
- messageVariable, correlationVariable, correlationValue, logMarker);
-
- if (result instanceof CallbackError) {
- return new SDNCAdapterErrorResponse(((CallbackError)result).getErrorMessage());
- } else {
- return new SDNCAdapterResponse();
- }
- }
-
- // This subclass allows unit tests to extract the error
- public class SDNCAdapterErrorResponse extends SDNCAdapterResponse {
- private String error;
-
- public SDNCAdapterErrorResponse(String error) {
- this.error = error;
- }
-
- public String getError() {
- return error;
- }
- }
-} \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java
deleted file mode 100644
index 621e35e57d..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import javax.jws.Oneway;
-import javax.jws.WebMethod;
-import javax.jws.WebParam;
-import javax.jws.WebService;
-import javax.ws.rs.core.Context;
-import javax.xml.ws.Action;
-import javax.xml.ws.RequestWrapper;
-import javax.xml.ws.WebServiceContext;
-
-import org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification;
-import org.openecomp.mso.bpmn.common.adapter.vnf.DeleteVnfNotification;
-import org.openecomp.mso.bpmn.common.adapter.vnf.MsoExceptionCategory;
-import org.openecomp.mso.bpmn.common.adapter.vnf.QueryVnfNotification;
-import org.openecomp.mso.bpmn.common.adapter.vnf.RollbackVnfNotification;
-import org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification;
-import org.openecomp.mso.bpmn.common.adapter.vnf.VnfAdapterNotify;
-import org.openecomp.mso.bpmn.common.adapter.vnf.VnfRollback;
-import org.openecomp.mso.bpmn.common.adapter.vnf.VnfStatus;
-import org.openecomp.mso.logger.MsoLogger;
-
-/**
- * Implementation of the VnfAdapterNotify service.
- */
-@WebService(serviceName = "vnfAdapterNotify", targetNamespace = "http://org.openecomp.mso/vnfNotify")
-public class VnfAdapterNotifyServiceImpl extends AbstractCallbackService implements VnfAdapterNotify{
-
- private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
-
- private final String logMarker = "[VNF-NOTIFY]";
-
- @Context WebServiceContext wsContext;
-
- @WebMethod(operationName = "rollbackVnfNotification")
- @Oneway
- @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.openecomp.mso/vnfNotify", className = "org.openecomp.mso.adapters.vnf.async.client.RollbackVnfNotification")
- @Action(input = "http://org.openecomp.mso/notify/adapterNotify/rollbackVnfNotificationRequest")
- public void rollbackVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage) {
-
- RollbackVnfNotification rollbackVnfNotification = new RollbackVnfNotification();
-
- rollbackVnfNotification.setMessageId(messageId);
- rollbackVnfNotification.setCompleted(completed);
- rollbackVnfNotification.setException(exception);
- rollbackVnfNotification.setErrorMessage(errorMessage);
-
- String method = "rollbackVnfNotification";
- Object message = rollbackVnfNotification;
- String messageEventName = "rollbackVnfNotificationCallback";
- String messageVariable = "rollbackVnfNotificationCallback";
- String correlationVariable = "VNFRB_messageId";
- String correlationValue = messageId;
-
- handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
-
- @WebMethod(operationName = "queryVnfNotification")
- @Oneway
- @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.openecomp.mso/vnfNotify", className = "org.openecomp.mso.adapters.vnf.async.client.QueryVnfNotification")
- @Action(input = "http://org.openecomp.mso/notify/adapterNotify/queryVnfNotificationRequest")
- public void queryVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfExists", targetNamespace = "")
- Boolean vnfExists,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "status", targetNamespace = "")
- VnfStatus status,
- @WebParam(name = "outputs", targetNamespace = "")
- QueryVnfNotification.Outputs outputs){
-
- String method = "queryVnfNotification";
- String messageEventName = "queryVnfNotificationCallback";
- String messageVariable = "queryVnfNotificationCallback";
- String correlationVariable = "VNFQ_messageId";
- String correlationValue = messageId;
-
- MsoLogger.setServiceName("MSO." + method);
- MsoLogger.setLogContext(correlationValue, "N/A");
-
- QueryVnfNotification message = new QueryVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
- message.setVnfExists(vnfExists);
- message.setVnfId(vnfId);
- message.setStatus(status);
- message.setOutputs(outputs);
-
- handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
-
- @WebMethod(operationName = "createVnfNotification")
- @Oneway
- @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.openecomp.mso/vnfNotify", className = "org.openecomp.mso.adapters.vnf.async.client.CreateVnfNotification")
- @Action(input = "http://org.openecomp.mso/notify/adapterNotify/createVnfNotificationRequest")
- public void createVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "outputs", targetNamespace = "")
- CreateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback){
-
- String method = "createVnfNotification";
- String messageEventName = "createVnfNotificationCallback";
- String messageVariable = "createVnfNotificationCallback";
- String correlationVariable = "VNFC_messageId";
- String correlationValue = messageId;
-
- MsoLogger.setServiceName("MSO." + method);
- MsoLogger.setLogContext(correlationValue, "N/A");
-
- CreateVnfNotification message = new CreateVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
- message.setVnfId(vnfId);
- message.setOutputs(outputs);
- message.setRollback(rollback);
-
- handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
-
- @WebMethod(operationName = "updateVnfNotification")
- @Oneway
- @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.openecomp.mso/vnfNotify", className = "org.openecomp.mso.adapters.vnf.async.client.UpdateVnfNotification")
- @Action(input = "http://org.openecomp.mso/notify/adapterNotify/updateVnfNotificationRequest")
- public void updateVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "outputs", targetNamespace = "")
- UpdateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback){
-
- String method = "updateVnfNotification";
- String messageEventName = "updateVnfNotificationCallback";
- String messageVariable = "updateVnfNotificationCallback";
- String correlationVariable = "VNFU_messageId";
- String correlationValue = messageId;
-
- MsoLogger.setServiceName("MSO." + method);
- MsoLogger.setLogContext(correlationValue, "N/A");
-
- UpdateVnfNotification message = new UpdateVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
- message.setOutputs(outputs);
- message.setRollback(rollback);
-
- handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
-
- @WebMethod(operationName = "deleteVnfNotification")
- @Oneway
- @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.openecomp.mso/vnfNotify", className = "org.openecomp.mso.adapters.vnf.async.client.DeleteVnfNotification")
- @Action(input = "http://org.openecomp.mso/notify/adapterNotify/deleteVnfNotificationRequest")
- public void deleteVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage) {
-
- String method = "deleteVnfNotification";
- String messageEventName = "deleteVnfACallback";
- String messageVariable = "deleteVnfACallback";
- String correlationVariable = "VNFDEL_uuid";
- String correlationValue = messageId;
-
- MsoLogger.setServiceName("MSO." + method);
- MsoLogger.setLogContext(correlationValue, "N/A");
-
- DeleteVnfNotification message = new DeleteVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
-
- handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
-} \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java
deleted file mode 100644
index cd98860efe..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import org.camunda.bpm.engine.ProcessEngineServices;
-import org.camunda.bpm.engine.ProcessEngines;
-
-
-public class WorkflowAsyncCommonResource extends WorkflowAsyncResource {
-
- @Override
- public String getProcessEngineName() {
- return "default";
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java
deleted file mode 100644
index b4543b1445..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.UUID;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Response;
-
-import org.camunda.bpm.engine.ProcessEngineServices;
-import org.camunda.bpm.engine.RuntimeService;
-import org.camunda.bpm.engine.runtime.ProcessInstance;
-import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
-import org.jboss.resteasy.annotations.Suspend;
-import org.jboss.resteasy.spi.AsynchronousResponse;
-import org.openecomp.mso.logger.MessageEnum;
-import org.openecomp.mso.logger.MsoLogger;
-import org.slf4j.MDC;
-
-/**
- *
- * @version 1.0
- * Asynchronous Workflow processing using JAX RS RESTeasy implementation
- * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background
- * and the server thread is freed up, server scales better to process more incoming requests
- *
- * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response
- * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process
- */
-@Path("/async")
-public class WorkflowAsyncResource extends ProcessEngineAwareService {
-
- private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
- protected Optional<ProcessEngineServices> pes4junit = Optional.empty();
-
- private final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
-
- private static final String logMarker = "[WRKFLOW-RESOURCE]";
- private static final long DEFAULT_WAIT_TIME = 30000; //default wait time
-
- /**
- * Asynchronous JAX-RS method that starts a process instance.
- * @param asyncResponse an object that will receive the asynchronous response
- * @param processKey the process key
- * @param variableMap input variables to the process
- */
- @POST
- @Path("/services/{processKey}")
- @Produces("application/json")
- @Consumes("application/json")
- public void startProcessInstanceByKey(final @Suspend(180000) AsynchronousResponse asyncResponse,
- @PathParam("processKey") String processKey, VariableMapImpl variableMap) {
-
- long startTime = System.currentTimeMillis();
- Map<String, Object> inputVariables = null;
- WorkflowContext workflowContext = null;
-
- try {
- inputVariables = getInputVariables(variableMap);
- setLogContext(processKey, inputVariables);
-
- // This variable indicates that the flow was invoked asynchronously
- inputVariables.put("isAsyncProcess", "true");
-
- workflowContext = new WorkflowContext(processKey, getRequestId(inputVariables),
- asyncResponse, getWaitTime(inputVariables));
-
- msoLogger.debug("Adding the workflow context into holder: "
- + workflowContext.getProcessKey() + ":"
- + workflowContext.getRequestId() + ":"
- + workflowContext.getTimeout());
-
- contextHolder.put(workflowContext);
-
- ProcessThread processThread = new ProcessThread(processKey, inputVariables);
- processThread.start();
- } catch (Exception e) {
- setLogContext(processKey, inputVariables);
-
- if (workflowContext != null) {
- contextHolder.remove(workflowContext);
- }
-
- msoLogger.debug(logMarker + "Exception in startProcessInstance by key");
- WorkflowResponse response = new WorkflowResponse();
- response.setMessage("Fail" );
- response.setContent("Error occurred while executing the process: " + e);
- response.setMessageCode(500);
- recordEvents(processKey, response, startTime);
-
- msoLogger.error (MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logMarker
- + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent());
-
- Response errorResponse = Response.serverError().entity(response).build();
- asyncResponse.setResponse(errorResponse);
- }
- }
-
- /**
- *
- * @version 1.0
- *
- */
- class ProcessThread extends Thread {
- private final String processKey;
- private final Map<String,Object> inputVariables;
-
- public ProcessThread(String processKey, Map<String, Object> inputVariables) {
- this.processKey = processKey;
- this.inputVariables = inputVariables;
- }
-
- public void run() {
-
- String processInstanceId = null;
- long startTime = System.currentTimeMillis();
-
- try {
- setLogContext(processKey, inputVariables);
-
- // Note: this creates a random businessKey if it wasn't specified.
- String businessKey = getBusinessKey(inputVariables);
-
- msoLogger.debug(logMarker + "***Received MSO startProcessInstanceByKey with processKey: "
- + processKey + " and variables: " + inputVariables);
-
- msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker
- + "Call to MSO workflow/services in Camunda. Received MSO startProcessInstanceByKey with processKey:"
- + processKey + " and variables: " + inputVariables);
-
- RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
- processKey, businessKey, inputVariables);
- processInstanceId = processInstance.getId();
-
- msoLogger.debug(logMarker + "Process " + processKey + ":" + processInstanceId + " " +
- (processInstance.isEnded() ? "ENDED" : "RUNNING"));
- } catch (Exception e) {
-
- msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
- logMarker + "Error in starting the process: "+ e.getMessage());
-
- WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
- callbackResponse.setStatusCode(500);
- callbackResponse.setMessage("Fail");
- callbackResponse.setResponse("Error occurred while executing the process: " + e);
-
- // TODO: is the processInstanceId used by the API handler? I don't think so.
- // It may be null here.
- WorkflowContextHolder.getInstance().processCallback(
- processKey, processInstanceId,
- getRequestId(inputVariables),
- callbackResponse);
- }
- }
- }
-
-
- /**
- * Callback resource which is invoked from BPMN to process to send the workflow response
- *
- * @param processKey
- * @param processInstanceId
- * @param requestId
- * @param callbackResponse
- * @return
- */
- @POST
- @Path("/services/callback/{processKey}/{processInstanceId}/{requestId}")
- @Produces("application/json")
- @Consumes("application/json")
- public Response processWorkflowCallback(
- @PathParam("processKey") String processKey,
- @PathParam("processInstanceId") String processInstanceId,
- @PathParam("requestId")String requestId,
- WorkflowCallbackResponse callbackResponse) {
-
- msoLogger.debug(logMarker + "Process instance ID:" + processInstanceId + ":" + requestId + ":" + processKey + ":" + isProcessEnded(processInstanceId));
- msoLogger.debug(logMarker + "About to process the callback request:" + callbackResponse.getResponse() + ":" + callbackResponse.getMessage() + ":" + callbackResponse.getStatusCode());
- return contextHolder.processCallback(processKey, processInstanceId, requestId, callbackResponse);
- }
-
- private static String getOrCreate(Map<String, Object> inputVariables, String key) {
- String value = Objects.toString(inputVariables.get(key), null);
- if (value == null) {
- value = UUID.randomUUID().toString();
- inputVariables.put(key, value);
- }
- return value;
- }
-
- // Note: the business key is used to identify the process in unit tests
- private static String getBusinessKey(Map<String, Object> inputVariables) {
- return getOrCreate(inputVariables, "mso-business-key");
- }
-
- private static String getRequestId(Map<String, Object> inputVariables) {
- return getOrCreate(inputVariables, "mso-request-id");
- }
-
- private long getWaitTime(Map<String, Object> inputVariables)
- {
-
- String timeout = Objects.toString(inputVariables.get("mso-service-request-timeout"), null);
-
- if (timeout != null) {
- try {
- return Long.parseLong(timeout)*1000;
- } catch (NumberFormatException nex) {
- msoLogger.debug("Invalid input for mso-service-request-timeout");
- }
- }
-
- return DEFAULT_WAIT_TIME;
- }
-
- private void recordEvents(String processKey, WorkflowResponse response,
- long startTime) {
-
- msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
- logMarker + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent(), "BPMN", MDC.get(processKey), null);
-
- msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
- logMarker + response.getMessage() + "for processKey: " + processKey + " with content: " + response.getContent());
-
- }
-
- private static void setLogContext(String processKey,
- Map<String, Object> inputVariables) {
- MsoLogger.setServiceName("MSO." + processKey);
- if (inputVariables != null) {
- MsoLogger.setLogContext(getKeyValueFromInputVariables(inputVariables,"mso-request-id"), getKeyValueFromInputVariables(inputVariables,"mso-service-instance-id"));
- }
- }
-
- private static String getKeyValueFromInputVariables(Map<String,Object> inputVariables, String key) {
- if (inputVariables == null) {
- return "";
- }
-
- return Objects.toString(inputVariables.get(key), "N/A");
- }
-
- private boolean isProcessEnded(String processInstanceId) {
- ProcessEngineServices pes = getProcessEngineServices();
- return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;
- }
-
- private static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
- Map<String, Object> inputVariables = new HashMap<>();
- @SuppressWarnings("unchecked")
- Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
- for (Map.Entry<String, Object> entry : vMap.entrySet()) {
- String vName = entry.getKey();
- Object value = entry.getValue();
- @SuppressWarnings("unchecked")
- Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
- inputVariables.put(vName, valueMap.get("value"));
- }
- return inputVariables;
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java
deleted file mode 100644
index 25669d7625..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-/**
- * @version 1.0
- * Workflow Response bean to generate workflow response in JSON format
- */
-public class WorkflowCallbackResponse {
-
- private String response;
- private int statusCode;
- private String message;
-
- public String getResponse() {
- return response;
- }
- public void setResponse(String response) {
- this.response = response;
- }
- public int getStatusCode() {
- return statusCode;
- }
- public void setStatusCode(int statusCode) {
- this.statusCode = statusCode;
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
-
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java
deleted file mode 100644
index fc0ba44974..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import java.util.concurrent.Delayed;
-import java.util.concurrent.TimeUnit;
-
-import org.jboss.resteasy.spi.AsynchronousResponse;
-
-/**
- * @version 1.0
- * Workflow context object used to send timeout response, if workflow instance does not write the response in time
- */
-public class WorkflowContext implements Delayed {
- private final String processKey;
- private final String requestId;
- private final AsynchronousResponse asynchronousResponse;
- private final long startTime;
- private final long timeout;
-
- public WorkflowContext(String processKey, String requestId,
- AsynchronousResponse asynchronousResponse, long timeout) {
- this.processKey = processKey;
- this.requestId = requestId;
- this.asynchronousResponse = asynchronousResponse;
- this.timeout = timeout;
- this.startTime = System.currentTimeMillis();
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public String getProcessKey() {
- return processKey;
- }
-
- public AsynchronousResponse getAsynchronousResponse() {
- return asynchronousResponse;
- }
-
- public long getTimeout() {
- return timeout;
- }
-
- public long getStartTime() {
- return startTime;
- }
-
- /**
- * Required implementation by Delay queue
- * Returns the elapsed time for this context
- */
- @Override
- public long getDelay(TimeUnit unit) {
- // 0 or negative means this object is considered to be expired
- return unit.convert(startTime + timeout - System.currentTimeMillis(), unit);
- }
-
- /**
- * Required implementation by Delay queue
- * Compares the object to determine whether the object can be marked as expired
- */
- @Override
- public int compareTo(Delayed object) {
- WorkflowContext that = (WorkflowContext) object;
- long thisEndTime = startTime + timeout;
- long thatEndTime = that.startTime + that.timeout;
-
- if (thisEndTime < thatEndTime) {
- return -1;
- } else if (thisEndTime > thatEndTime) {
- return 1;
- } else {
- return 0;
- }
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java
deleted file mode 100644
index 4dfae8b2a3..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import java.util.concurrent.DelayQueue;
-import java.util.concurrent.TimeUnit;
-
-import javax.ws.rs.core.Response;
-
-import org.jboss.resteasy.spi.AsynchronousResponse;
-import org.slf4j.MDC;
-
-import org.openecomp.mso.logger.MessageEnum;
-import org.openecomp.mso.logger.MsoLogger;
-
-/**
- * Workflow Context Holder instance which can be accessed elsewhere either in groovy scripts or Java
- * @version 1.0
- *
- */
-public class WorkflowContextHolder {
-
- private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
- private static final String logMarker = "[WORKFLOW-CONTEXT-HOLDER]";
- private static WorkflowContextHolder instance = null;
-
- /**
- * Delay Queue which holds workflow context holder objects
- */
- private final DelayQueue<WorkflowContext> responseQueue = new DelayQueue<>();
- private final TimeoutThread timeoutThread = new TimeoutThread();
-
- private WorkflowContextHolder() {
- timeoutThread.start();
- }
-
- /**
- * Singleton holder which eliminates hot lock
- * Since the JVM synchronizes static method there is no synchronization needed for this method
- * @return
- */
- public static synchronized WorkflowContextHolder getInstance() {
- if (instance == null) {
- instance = new WorkflowContextHolder();
- }
- return instance;
- }
-
- public void put(WorkflowContext context) {
- msoLogger.debug(logMarker + " Adding context to the queue: "
- + context.getRequestId());
- responseQueue.put(context);
- }
-
- public void remove(WorkflowContext context) {
- msoLogger.debug(logMarker + " Removing context from the queue: "
- + context.getRequestId());
- responseQueue.remove(context);
- }
-
- public WorkflowContext getWorkflowContext(String requestId) {
- // Note: DelayQueue interator is threadsafe
- for (WorkflowContext context : responseQueue) {
- if (requestId.equals(context.getRequestId())) {
- msoLogger.debug("Found context for request id: " + requestId);
- return context;
- }
- }
-
- msoLogger.debug("Unable to find context for request id: " + requestId);
- return null;
- }
-
- /**
- * Builds the callback response object to respond to client
- * @param processKey
- * @param processInstanceId
- * @param requestId
- * @param callbackResponse
- * @return
- */
- public Response processCallback(String processKey, String processInstanceId,
- String requestId, WorkflowCallbackResponse callbackResponse) {
- WorkflowResponse workflowResponse = new WorkflowResponse();
- WorkflowContext workflowContext = getWorkflowContext(requestId);
-
- if (workflowContext == null) {
- msoLogger.debug("Unable to correlate workflow context for request id: " + requestId
- + ":processInstance Id:" + processInstanceId
- + ":process key:" + processKey);
- workflowResponse.setMessage("Fail");
- workflowResponse.setMessageCode(400);
- workflowResponse.setContent("Unable to correlate workflow context, bad request. Request Id: " + requestId);
- return Response.serverError().entity(workflowResponse).build();
- }
-
- responseQueue.remove(workflowContext);
-
- msoLogger.debug("Using callback response for request id: " + requestId);
- workflowResponse.setContent(callbackResponse.getResponse());
- workflowResponse.setProcessInstanceId(processInstanceId);
- workflowResponse.setMessageCode(callbackResponse.getStatusCode());
- workflowResponse.setMessage(callbackResponse.getMessage());
- sendWorkflowResponseToClient(processKey, workflowContext, workflowResponse);
- return Response.ok().entity(workflowResponse).build();
- }
-
- /**
- * Send the response to client asynchronously when invoked by the BPMN process
- * @param processKey
- * @param workflowContext
- * @param workflowResponse
- */
- private void sendWorkflowResponseToClient(String processKey, WorkflowContext workflowContext,
- WorkflowResponse workflowResponse) {
- msoLogger.debug(logMarker + "Sending the response for request id: " + workflowContext.getRequestId());
- recordEvents(processKey, workflowResponse, workflowContext.getStartTime());
- Response response = Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build();
- AsynchronousResponse asyncResp = workflowContext.getAsynchronousResponse();
- asyncResp.setResponse(response);
- }
-
- /**
- * Timeout thread which monitors the delay queue for expired context and send timeout response
- * to client
- *git review -R
- * */
- private class TimeoutThread extends Thread {
- public void run() {
- while (!isInterrupted()) {
- try {
- WorkflowContext requestObject = responseQueue.take();
- msoLogger.debug("Time remaining for request id: " + requestObject.getRequestId() + ":" + requestObject.getDelay(TimeUnit.MILLISECONDS));
- msoLogger.debug("Preparing timeout response for " + requestObject.getProcessKey() + ":" + ":" + requestObject.getRequestId());
- WorkflowResponse response = new WorkflowResponse();
- response.setMessage("Fail");
- response.setContent("Request timedout, request id:" + requestObject.getRequestId());
- //response.setProcessInstanceID(requestObject.getProcessInstance().getProcessInstanceId());
- recordEvents(requestObject.getProcessKey(), response, requestObject.getStartTime());
- response.setMessageCode(500);
- Response result = Response.status(500).entity(response).build();
- requestObject.getAsynchronousResponse().setResponse(result);
- msoLogger.debug("Sending timeout response for request id:" + requestObject.getRequestId() + ":response:" + response);
- } catch (InterruptedException e) {
- break;
- } catch (Exception e) {
- msoLogger.debug("WorkflowContextHolder timeout thread caught exception: " + e);
- msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.UnknownError, "Error in WorkflowContextHolder timeout thread");
-
- }
- }
-
- msoLogger.debug("WorkflowContextHolder timeout thread interrupted, quitting");
- }
- }
-
- private static void recordEvents(String processKey, WorkflowResponse response,
- long startTime) {
-
- msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
- logMarker + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent(), "BPMN", MDC.get(processKey), null);
-
- msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker
- + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent());
-
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java
deleted file mode 100644
index 4ba35907b9..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.openecomp.mso.logger.MessageEnum;
-import org.openecomp.mso.logger.MsoLogger;
-
-/**
- * Generalized REST interface that injects a message event into a waiting BPMN process.
- * Examples:
- * <pre>
- * /WorkflowMessage/SDNCAResponse/6d10d075-100c-42d0-9d84-a52432681cae-1478486185286
- * /WorkflowMessage/SDNCAEvent/USOSTCDALTX0101UJZZ01
- * </pre>
- */
-@Path("/")
-public class WorkflowMessageResource extends AbstractCallbackService {
- private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
- private static final String LOGMARKER = "[WORKFLOW-MESSAGE]";
-
- @POST
- @Path("/WorkflowMessage/{messageType}/{correlator}")
- @Consumes("*/*")
- @Produces(MediaType.TEXT_PLAIN)
- public Response deliver(
- @HeaderParam("Content-Type") String contentType,
- @PathParam("messageType") String messageType,
- @PathParam("correlator") String correlator,
- String message) {
-
- String method = "receiveWorkflowMessage";
- MsoLogger.setServiceName("MSO." + method);
- MsoLogger.setLogContext(correlator, "N/A");
-
- LOGGER.debug(LOGMARKER + " Received workflow message"
- + " type='" + messageType + "'"
- + " correlator='" + correlator + "'"
- + (contentType == null ? "" : " contentType='" + contentType + "'")
- + " message=" + System.lineSeparator() + message);
-
- if (messageType == null || messageType.isEmpty()) {
- String msg = "Missing message type";
- LOGGER.debug(LOGMARKER + " " + msg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.DataError, LOGMARKER + ":" + msg);
- return Response.status(400).entity(msg).build();
- }
-
- if (correlator == null || correlator.isEmpty()) {
- String msg = "Missing correlator";
- LOGGER.debug(LOGMARKER + " " + msg);
- LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
- MsoLogger.ErrorCode.DataError, LOGMARKER + ":" + msg);
- return Response.status(400).entity(msg).build();
- }
-
- String messageEventName = "WorkflowMessage";
- String messageVariable = messageType + "_MESSAGE";
- String correlationVariable = messageType + "_CORRELATOR";
- String correlationValue = correlator;
- String contentTypeVariable = messageType + "_CONTENT_TYPE";
-
- Map<String, Object> variables = new HashMap<>();
-
- if (contentType != null) {
- variables.put(contentTypeVariable, contentType);
- }
-
- CallbackResult result = handleCallback(method, message, messageEventName,
- messageVariable, correlationVariable, correlationValue, LOGMARKER, variables);
-
- if (result instanceof CallbackError) {
- return Response.status(500).entity(((CallbackError)result).getErrorMessage()).build();
- } else {
- return Response.status(204).build();
- }
- }
-} \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java
deleted file mode 100644
index 25c67fed63..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java
+++ /dev/null
@@ -1,615 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.common.workflow.service;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.camunda.bpm.engine.HistoryService;
-import org.camunda.bpm.engine.ProcessEngineException;
-import org.camunda.bpm.engine.ProcessEngineServices;
-import org.camunda.bpm.engine.RuntimeService;
-import org.camunda.bpm.engine.history.HistoricVariableInstance;
-import org.camunda.bpm.engine.runtime.ProcessInstance;
-import org.camunda.bpm.engine.variable.VariableMap;
-import org.camunda.bpm.engine.variable.Variables;
-import org.camunda.bpm.engine.variable.Variables.SerializationDataFormats;
-import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
-import org.openecomp.mso.bpmn.core.WorkflowException;
-import org.openecomp.mso.logger.MessageEnum;
-import org.openecomp.mso.logger.MsoLogger;
-import org.slf4j.MDC;
-
-@Path("/workflow")
-public class WorkflowResource extends ProcessEngineAwareService {
-
- private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
- private static final String LOGMARKER = "[WRKFLOW-RESOURCE]";
-
- private static final int DEFAULT_WAIT_TIME = 30000;
-
- @Context
- private UriInfo uriInfo = null;
-
- /**
- * Starts the process instance and responds to client synchronously
- * If the request does not contain mso-service-request-timeout then it waits for the value specified in DEFAULT_WAIT_TIME
- * Note: value specified in mso-service-request-timeout is in seconds
- * During polling time, if there is an exception encountered in the process execution then polling is stopped and the error response is
- * returned to the client
- * @param processKey
- * @param variableMap
- * @return
- */
- @POST
- @Path("/services/{processKey}")
- @Produces("application/json")
- @Consumes("application/json")
- public Response startProcessInstanceByKey(@PathParam("processKey") String processKey,
- VariableMapImpl variableMap) {
-
- Map<String, Object> inputVariables = getInputVariables(variableMap);
- setLogContext(processKey, inputVariables);
-
- WorkflowResponse workflowResponse = new WorkflowResponse();
- long startTime = System.currentTimeMillis();
- ProcessInstance processInstance = null;
-
- try {
- //Kickoff the process
- ProcessThread thread = new ProcessThread(inputVariables,processKey,msoLogger);
- thread.start();
-
- Map<String, Object> responseMap = null;
-
- //wait for process to be completed
- long waitTime = getWaitTime(inputVariables);
- long now = System.currentTimeMillis();
- long start = now;
- long endTime = start + waitTime;
- long pollingInterval = 500;
-
- // TEMPORARY LOGIC FOR UNIT TEST REFACTORING
- // If this is a unit test (method is invoked directly), wait a max
- // of 5 seconds after process ended for a result. In production,
- // wait up to 60 seconds.
- long timeToWaitAfterProcessEnded = uriInfo == null ? 5000 : 60000;
- AtomicLong timeProcessEnded = new AtomicLong(0);
- boolean endedWithNoResponse = false;
-
- while (now <= endTime) {
- Thread.sleep(pollingInterval);
-
- now = System.currentTimeMillis();
-
- // Increase the polling interval over time
-
- long elapsed = now - start;
-
- if (elapsed > 60000) {
- pollingInterval = 5000;
- } else if (elapsed > 10000) {
- pollingInterval = 1000;
- }
- Exception exception = thread.getException();
- if (exception != null) {
- throw new Exception(exception);
- }
-
- processInstance = thread.getProcessInstance();
-
- if (processInstance == null) {
- msoLogger.debug(LOGMARKER + processKey + " process has not been created yet");
- continue;
- }
-
- String processInstanceId = processInstance.getId();
- workflowResponse.setProcessInstanceId(processInstanceId);
-
- responseMap = getResponseMap(processInstance, processKey, timeProcessEnded);
-
- if (responseMap == null) {
- msoLogger.debug(LOGMARKER + processKey + " has not produced a response yet");
-
- if (timeProcessEnded.longValue() != 0) {
- long elapsedSinceEnded = System.currentTimeMillis() - timeProcessEnded.longValue();
-
- if (elapsedSinceEnded > timeToWaitAfterProcessEnded) {
- endedWithNoResponse = true;
- break;
- }
- }
- } else {
- processResponseMap(workflowResponse, responseMap);
- recordEvents(processKey, workflowResponse, startTime);
- return Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build();
- }
- }
-
- //if we dont get response after waiting then send timeout response
-
- String state;
- String processInstanceId;
-
- if (processInstance == null) {
- processInstanceId = "N/A";
- state = "NOT STARTED";
- } else {
- processInstanceId = processInstance.getProcessInstanceId();
- state = isProcessEnded(processInstanceId) ? "ENDED" : "NOT ENDED";
- }
-
- workflowResponse.setMessage("Fail");
- if (endedWithNoResponse) {
- workflowResponse.setContent("Process ended without producing a response");
- } else {
- workflowResponse.setContent("Request timed out, process state: " + state);
- }
- workflowResponse.setProcessInstanceId(processInstanceId);
- recordEvents(processKey, workflowResponse, startTime);
- workflowResponse.setMessageCode(500);
- return Response.status(500).entity(workflowResponse).build();
- } catch (Exception ex) {
- msoLogger.debug(LOGMARKER + "Exception in startProcessInstance by key",ex);
- workflowResponse.setMessage("Fail" );
- workflowResponse.setContent("Error occurred while executing the process: " + ex.getMessage());
- if (processInstance != null) workflowResponse.setProcessInstanceId(processInstance.getId());
-
- msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MDC.get(processKey),
- MsoLogger.ErrorCode.UnknownError, LOGMARKER + workflowResponse.getMessage()
- + " for processKey: " + processKey + " with content: " + workflowResponse.getContent());
-
- workflowResponse.setMessageCode(500);
- recordEvents(processKey, workflowResponse, startTime);
- return Response.status(500).entity(workflowResponse).build();
- }
- }
-
- /**
- * Returns the wait time, this is used by the resource on how long it should wait to send a response
- * If none specified DEFAULT_WAIT_TIME is used
- * @param inputVariables
- * @return
- */
- private int getWaitTime(Map<String, Object> inputVariables)
- {
- String timeout = inputVariables.get("mso-service-request-timeout") == null
- ? null : inputVariables.get("mso-service-request-timeout").toString();
-
- if (timeout != null) {
- try {
- return Integer.parseInt(timeout)*1000;
- } catch (NumberFormatException nex) {
- msoLogger.debug("Invalid input for mso-service-request-timeout");
- }
- }
- return DEFAULT_WAIT_TIME;
- }
-
- private void recordEvents(String processKey, WorkflowResponse response, long startTime) {
-
- msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
- LOGMARKER + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent(), "BPMN", MDC.get(processKey), null);
-
- msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
- LOGMARKER + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent());
- }
-
- private void setLogContext(String processKey, Map<String, Object> inputVariables) {
- MsoLogger.setServiceName("MSO." + processKey);
- if (inputVariables != null) {
- MsoLogger.setLogContext(getValueFromInputVariables(inputVariables, "mso-request-id"),
- getValueFromInputVariables(inputVariables, "mso-service-instance-id"));
- }
- }
-
- private String getValueFromInputVariables(Map<String,Object> inputVariables, String key) {
- Object value = inputVariables.get(key);
- if (value == null) {
- return "N/A";
- } else {
- return value.toString();
- }
- }
-
- /**
- * Checks to see if the specified process is ended.
- * @param processInstanceId the process instance ID
- * @return true if the process is ended
- */
- private boolean isProcessEnded(String processInstanceId) {
- ProcessEngineServices pes = getProcessEngineServices();
- try {
- return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null ? true : false ;
- } catch (Exception e) {
- msoLogger.debug("Exception :",e);
- return true;
- }
- }
-
- private void processResponseMap(WorkflowResponse workflowResponse, Map<String, Object> responseMap) {
- Object object = responseMap.get("Response");
- String content = object == null ? null : String.valueOf(object);
- if (content == null){
- object = responseMap.get("WorkflowResponse");
- content = object == null ? null : String.valueOf(object);
- }
-
- workflowResponse.setContent(content);
-
- object = responseMap.get("ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
-
- try {
- workflowResponse.setMessageCode(Integer.parseInt(responseCode));
- } catch(NumberFormatException nex) {
- msoLogger.debug(LOGMARKER + "Failed to parse ResponseCode: " + responseCode);
- workflowResponse.setMessageCode(-1);
- }
-
- Object status = responseMap.get("Status");
-
- if ("Success".equalsIgnoreCase(String.valueOf(status))) {
- workflowResponse.setMessage("Success");
- } else if ("Fail".equalsIgnoreCase(String.valueOf(status))) {
- workflowResponse.setMessage("Fail");
- } else {
- msoLogger.debug(LOGMARKER + "Unrecognized Status: " + responseCode);
- workflowResponse.setMessage("Fail");
- }
- }
-
- /**
- * @version 1.0
- * Triggers the workflow in a separate thread
- */
- private class ProcessThread extends Thread {
- private final Map<String,Object> inputVariables;
- private final String processKey;
- private final MsoLogger msoLogger;
- private final String businessKey;
- private ProcessInstance processInstance = null;
- private Exception exception = null;
-
- public ProcessThread(Map<String, Object> inputVariables, String processKey, MsoLogger msoLogger) {
- this.inputVariables = inputVariables;
- this.processKey = processKey;
- this.msoLogger = msoLogger;
- this.businessKey = UUID.randomUUID().toString();
- }
-
- /**
- * If an exception occurs when starting the process instance, it may
- * be obtained by calling this method. Note that exceptions are only
- * recorded while the process is executing in its original thread.
- * Once a process is suspended, exception recording stops.
- * @return the exception, or null if none has occurred
- */
- public Exception getException() {
- return exception;
- }
-
-
- public ProcessInstance getProcessInstance() {
- return this.processInstance;
- }
-
- /**
- * Sets the process instance exception.
- * @param exception the exception
- */
- private void setException(Exception exception) {
- this.exception = exception;
- }
-
- public void run() {
- setLogContext(processKey, inputVariables);
-
- long startTime = System.currentTimeMillis();
-
- try {
- msoLogger.debug(LOGMARKER + "***Received MSO startProcessInstanceByKey with processKey:"
- + processKey + " and variables: " + inputVariables);
-
- msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, LOGMARKER
- + "Call to MSO workflow/services in Camunda. Received MSO startProcessInstanceByKey with"
- + " processKey:" + processKey
- + " businessKey:" + businessKey
- + " variables: " + inputVariables);
-
- RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
-
- // Note that this method doesn't return until the process suspends
- // itself or finishes. We provide a business key so we can identify
- // the process instance immediately.
- processInstance = runtimeService.startProcessInstanceByKey(
- processKey, inputVariables);
-
- } catch (Exception e) {
- msoLogger.debug(LOGMARKER + "ProcessThread caught an exception executing "
- + processKey + ": " + e);
- setException(e);
- }
- }
-
- }
-
- private Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
- VariableMap inputVariables = Variables.createVariables();
- @SuppressWarnings("unchecked")
- Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
- for (String key : vMap.keySet()) { //variabe name vn
- @SuppressWarnings("unchecked")
- Map<String, Object> valueMap = (Map<String,Object>)vMap.get(key); //value, type
- inputVariables.putValueTyped(key, Variables
- .objectValue(valueMap.get("value"))
- .serializationDataFormat(SerializationDataFormats.JAVA) // tells the engine to use java serialization for persisting the value
- .create());
- }
- return inputVariables;
- }
-
- /**
- * Attempts to get a response map from the specified process instance.
- * @return the response map, or null if it is unavailable
- */
- private Map<String, Object> getResponseMap(ProcessInstance processInstance,
- String processKey, AtomicLong timeProcessEnded) {
-
- String responseMapVariable = processKey + "ResponseMap";
- String processInstanceId = processInstance.getId();
-
- // Query the runtime service to see if a response map is ready.
-
-/* RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
- List<Execution> executions = runtimeService.createExecutionQuery()
- .processInstanceId(processInstanceId).list();
-
- for (Execution execution : executions) {
- @SuppressWarnings("unchecked")
- Map<String, Object> responseMap = (Map<String, Object>)
- getVariableFromExecution(runtimeService, execution.getId(),
- responseMapVariable);
-
- if (responseMap != null) {
- msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable
- + " from process " + processInstanceId + " execution "
- + execution.getId());
- return responseMap;
- }
- }
-*/
- //Querying history seem to return consistent results compared to querying the runtime service
-
- boolean alreadyEnded = timeProcessEnded.longValue() != 0;
-
- if (alreadyEnded || isProcessEnded(processInstance.getId())) {
- if (!alreadyEnded) {
- timeProcessEnded.set(System.currentTimeMillis());
- }
-
- // Query the history service to see if a response map exists.
-
- HistoryService historyService = getProcessEngineServices().getHistoryService();
- @SuppressWarnings("unchecked")
- Map<String, Object> responseMap = (Map<String, Object>)
- getVariableFromHistory(historyService, processInstance.getId(),
- responseMapVariable);
-
- if (responseMap != null) {
- msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable
- + " from process " + processInstanceId + " history");
- return responseMap;
- }
-
- // Query the history service for old-style response variables.
-
- String prefix = (String) getVariableFromHistory(historyService, processInstanceId, "prefix");
-
- if (prefix != null) {
-
- // Check for 'WorkflowResponse' variable
- Object workflowResponseObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowResponse");
- String workflowResponse = workflowResponseObject == null ? null : String.valueOf(workflowResponseObject);
- msoLogger.debug(LOGMARKER + "WorkflowResponse: " + workflowResponse);
-
- if (workflowResponse != null) {
- Object responseCodeObject = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = responseCodeObject == null ? null : String.valueOf(responseCodeObject);
- msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
- responseMap = new HashMap<>();
- responseMap.put("WorkflowResponse", workflowResponse);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Success");
- return responseMap;
- }
-
-
- // Check for 'WorkflowException' variable
- WorkflowException workflowException = null;
- String workflowExceptionText = null;
-
- Object workflowExceptionObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowException");
- if(workflowExceptionObject != null) {
- if(workflowExceptionObject instanceof WorkflowException) {
- workflowException = (WorkflowException) workflowExceptionObject;
- workflowExceptionText = workflowException.toString();
- responseMap = new HashMap<>();
- responseMap.put("WorkflowException", workflowExceptionText);
- responseMap.put("ResponseCode", workflowException.getErrorCode());
- responseMap.put("Status", "Fail");
- return responseMap;
- }
- else if (workflowExceptionObject instanceof String) {
- Object object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
- workflowExceptionText = (String) workflowExceptionObject;
- responseMap = new HashMap<>();
- responseMap.put("WorkflowException", workflowExceptionText);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Fail");
- return responseMap;
- }
-
- }
- msoLogger.debug(LOGMARKER + "WorkflowException: " + workflowExceptionText);
-
- // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE
- Object object = getVariableFromHistory(historyService, processInstanceId, processKey + "Response");
- String response = object == null ? null : String.valueOf(object);
- msoLogger.debug(LOGMARKER + processKey + "Response: " + response);
-
- if (response != null) {
- object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
- msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
- responseMap = new HashMap<>();
- responseMap.put("Response", response);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Success");
- return responseMap;
- }
-
- object = getVariableFromHistory(historyService, processInstanceId, prefix + "ErrorResponse");
- String errorResponse = object == null ? null : String.valueOf(object);
- msoLogger.debug(LOGMARKER + prefix + "ErrorResponse: " + errorResponse);
-
- if (errorResponse != null) {
- object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
- msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
- responseMap = new HashMap<>();
- responseMap.put("Response", errorResponse);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Fail");
- return responseMap;
- }
- // END LEGACY SUPPORT. TODO: REMOVE THIS CODE
- }
- }
- return null;
- }
-
- /**
- * Gets a variable value from the specified execution.
- * @return the variable value, or null if the variable could not be
- * obtained
- */
- private Object getVariableFromExecution(RuntimeService runtimeService,
- String executionId, String variableName) {
- try {
- return runtimeService.getVariable(executionId, variableName);
- } catch (ProcessEngineException e) {
- // Most likely cause is that the execution no longer exists.
- msoLogger.debug("Error retrieving execution " + executionId
- + " variable " + variableName + ": " + e);
- return null;
- }
- }
- /**
- * Gets a variable value from specified historical process instance.
- * @return the variable value, or null if the variable could not be
- * obtained
- */
- private Object getVariableFromHistory(HistoryService historyService,
- String processInstanceId, String variableName) {
- try {
- HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery()
- .processInstanceId(processInstanceId).variableName(variableName).singleResult();
- return v == null ? null : v.getValue();
- } catch (Exception e) {
- msoLogger.debug("Error retrieving process " + processInstanceId
- + " variable " + variableName + " from history: " + e);
- return null;
- }
- }
-
- @POST
- @Path("/services/{processKey}/{processInstanceId}")
- @Produces("application/json")
- @Consumes("application/json")
- public WorkflowResponse getProcessVariables(@PathParam("processKey") String processKey, @PathParam("processInstanceId") String processInstanceId) {
- //TODO filter only set of variables
- WorkflowResponse response = new WorkflowResponse();
-
- long startTime = System.currentTimeMillis();
- try {
- ProcessEngineServices engine = getProcessEngineServices();
- List<HistoricVariableInstance> variables = engine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
- Map<String,String> variablesMap = new HashMap<>();
- for (HistoricVariableInstance variableInstance: variables) {
- variablesMap.put(variableInstance.getName(), variableInstance.getValue().toString());
- }
-
- msoLogger.debug(LOGMARKER + "***Received MSO getProcessVariables with processKey:" + processKey + " and variables: " + variablesMap.toString());
-
- msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, LOGMARKER
- + "Call to MSO workflow/services in Camunda. Received MSO getProcessVariables with processKey:"
- + processKey + " and variables: "
- + variablesMap.toString());
-
-
- response.setVariables(variablesMap);
- response.setMessage("Success");
- response.setContent("Successfully retrieved the variables");
- response.setProcessInstanceId(processInstanceId);
-
- msoLogger.debug(LOGMARKER + response.getMessage() + " for processKey: " + processKey + " with content: " + response.getContent());
- } catch (Exception ex) {
- response.setMessage("Fail");
- response.setContent("Failed to retrieve the variables," + ex.getMessage());
- response.setProcessInstanceId(processInstanceId);
-
- msoLogger.error (MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MDC.get(processKey), MsoLogger.ErrorCode.UnknownError, LOGMARKER
- + response.getMessage()
- + " for processKey: "
- + processKey
- + " with content: "
- + response.getContent());
- msoLogger.debug("Exception :",ex);
- }
-
- msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
- LOGMARKER + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent(), "BPMN", MDC.get(processKey), null);
-
- msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
- LOGMARKER + response.getMessage() + " for processKey: "
- + processKey + " with content: " + response.getContent());
-
- return response;
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java
deleted file mode 100644
index 64e5adc091..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.ws.rs.ApplicationPath;
-import javax.ws.rs.core.Application;
-
-@ApplicationPath("/")
-public class WorkflowResourceApplication extends Application {
- private Set<Object> singletons = new HashSet<>();
- private Set<Class<?>> classes = new HashSet<>();
-
- public WorkflowResourceApplication() {
- }
-
- @Override
- public Set<Class<?>> getClasses() {
- return classes;
- }
-
- @Override
- public Set<Object> getSingletons() {
- return singletons;
- }
-}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java
deleted file mode 100644
index 02702e3b3c..0000000000
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.common.workflow.service;
-
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-/**
- * A synchronous response from a workflow.
- */
-public class WorkflowResponse {
-
- @JsonProperty("processInstanceId")
- private String processInstanceId;
-
- @JsonProperty("messageCode")
- private int messageCode;
-
- @JsonProperty("message")
- private String message;
-
- @JsonProperty("variables")
- private Map<String,String> variables;
-
- @JsonProperty("content")
- private String content;
-
- public String getProcessInstanceId() {
- return processInstanceId;
- }
-
- public void setProcessInstanceId(String processInstanceId) {
- this.processInstanceId = processInstanceId;
- }
-
- public int getMessageCode() {
- return messageCode;
- }
-
- public void setMessageCode(int messageCode) {
- this.messageCode = messageCode;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public Map<String,String> getVariables() {
- return variables;
- }
-
- public void setVariables(Map<String,String> variables) {
- this.variables = variables;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "["
- + "processInstanceId=" + processInstanceId
- + ",messageCode=" + messageCode
- + ",message=" + message
- + ",variables=" + variables
- + ",content=" + content
- + "]";
- }
-} \ No newline at end of file