aboutsummaryrefslogtreecommitdiffstats
path: root/appc-dispatcher
diff options
context:
space:
mode:
authorDunietz, Irwin <id1681@att.com>2020-01-16 15:13:14 -0500
committerTakamune Cho <takamune.cho@att.com>2020-01-29 19:44:48 +0000
commitb5fe8a69e90b950c07dc11af481eab7e9bab52c6 (patch)
tree3da81ce60554e65b93776b9aea647f3c6d8679ab /appc-dispatcher
parent9b32cb60360a2a2973c621053510718de0072111 (diff)
Change code in appc dispatcher for new LCMs in R6
Also introduce some minor improvements to robustness, efficiency, & formatting. Issue-ID: APPC-1789 Signed-off-by: Dunietz, Irwin <id1681@att.com> Change-Id: I82d970c2f7cde6c8dab1222af86ea70ce93b7e50
Diffstat (limited to 'appc-dispatcher')
-rw-r--r--appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java27
-rw-r--r--appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java91
-rw-r--r--appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandExecutor.java59
-rw-r--r--appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandTask.java110
-rw-r--r--appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcDatabaseConnectionPool.java11
-rw-r--r--appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/api/DBConnectionPoolService.java15
-rw-r--r--appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/dbcp/DBConnectionPool.java26
-rw-r--r--appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/AppcDatabaseConnectionPoolTest.java7
-rw-r--r--appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/dbcp/DBConnectionPoolTest.java12
-rw-r--r--appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/test/java/org/onap/appc/domainmodel/lcm/TestRequestContext.java35
-rw-r--r--appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java252
-rw-r--r--appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java218
-rw-r--r--appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/LicenseManagerImplTest.java20
-rw-r--r--appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/XmlToLicenseModelConverterTest.java12
-rw-r--r--appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/resources/test-vf-license-model.xml2
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java34
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java92
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java131
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java89
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java84
-rwxr-xr-xappc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java30
-rwxr-xr-xappc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java7
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java81
-rw-r--r--appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java367
-rw-r--r--appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/impl/TestWorkFlowManager.java183
25 files changed, 1144 insertions, 851 deletions
diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java
index 9c12f4741..4c7698cb1 100644
--- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java
+++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandExecutorImpl.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,14 @@
* 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=========================================================
*/
@@ -29,6 +28,7 @@ package org.onap.appc.executor.impl;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.apache.commons.lang.ObjectUtils;
+import org.onap.appc.domainmodel.lcm.CommonHeader;
import org.onap.appc.exceptions.APPCException;
import org.onap.appc.executionqueue.ExecutionQueueService;
import org.onap.appc.executor.CommandExecutor;
@@ -54,7 +54,7 @@ public class CommandExecutorImpl implements CommandExecutor {
* <p>Used through blueprint.
*/
public void initialize() {
- logger.info("initialization started of CommandExecutorImpl");
+ logger.info("initialization of CommandExecutorImpl started");
}
public void setExecutionQueueService(ExecutionQueueService executionQueueService) {
@@ -78,24 +78,27 @@ public class CommandExecutorImpl implements CommandExecutor {
*/
@Override
public void executeCommand (CommandExecutorInput commandExecutorInput) throws APPCException{
- logger.trace("Entering to executeCommand with CommandExecutorInput = "+ ObjectUtils.toString(commandExecutorInput));
+ logger.trace("Entering executeCommand with CommandExecutorInput = "
+ + ObjectUtils.toString(commandExecutorInput));
CommandTask commandTask;
try {
- commandTask= getCommandTask(requestHandler, workflowManager);
+ commandTask = getCommandTask(requestHandler, workflowManager);
commandTask.setCommandRequest(new CommandRequest(commandExecutorInput));
long remainingTTL = getRemainingTTL(commandTask.getCommandRequest());
- logger.trace("Queuing request with CommandRequest = "+ ObjectUtils.toString(commandTask.getCommandRequest()));
- executionQueueService.putMessage(commandTask,remainingTTL, TimeUnit.MILLISECONDS);
+ logger.trace("Queuing request with CommandRequest = "
+ + ObjectUtils.toString(commandTask.getCommandRequest()));
+ executionQueueService.putMessage(commandTask, remainingTTL, TimeUnit.MILLISECONDS);
} catch (Exception e) {
- logger.error("Exception: "+e.getMessage());
+ logger.error("Exception: " + e.getMessage());
throw new APPCException(e);
}
logger.trace("Exiting from executeCommand");
}
private long getRemainingTTL(CommandRequest request) {
- Date requestTimestamp = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getTimeStamp();
- int ttl = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getFlags().getTtl();
+ CommonHeader hdr = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader();
+ Date requestTimestamp = hdr.getTimeStamp();
+ int ttl = hdr.getFlags().getTtl();
return ttl*1000 + requestTimestamp.getTime() - System.currentTimeMillis();
}
diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java
index cfd4ff8d0..8cf5930f7 100644
--- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java
+++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/onap/appc/executor/impl/CommandTask.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,15 @@
* 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=========================================================
*/
@@ -30,27 +30,29 @@ import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.net.InetAddress;
import java.util.UUID;
+import org.onap.appc.domainmodel.lcm.CommonHeader;
+import org.onap.appc.domainmodel.lcm.RequestContext;
+import org.onap.appc.domainmodel.lcm.ResponseContext;
+import org.onap.appc.domainmodel.lcm.RuntimeContext;
import org.onap.appc.domainmodel.lcm.Status;
import org.onap.appc.domainmodel.lcm.VNFOperation;
import org.onap.appc.executor.impl.objects.CommandRequest;
import org.onap.appc.logging.LoggingConstants;
import org.onap.appc.requesthandler.RequestHandler;
-import org.onap.appc.domainmodel.lcm.RuntimeContext;
import org.onap.appc.workflow.WorkFlowManager;
import org.onap.appc.workflow.objects.WorkflowRequest;
-import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import org.onap.ccsdk.sli.core.sli.SvcLogicException;
-import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
import org.onap.ccsdk.sli.adaptors.aai.AAIRequest;
import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
+import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.slf4j.MDC;
-
/**
* This abstract class is base class for all Command tasks. All command task must inherit this class.
*/
@@ -81,8 +83,7 @@ public class CommandTask implements Runnable {
this.requestHandler = requestHandler;
}
- public CommandTask(RequestHandler requestHandler,
- WorkFlowManager workflowManager){
+ public CommandTask(RequestHandler requestHandler, WorkFlowManager workflowManager) {
this.requestHandler = requestHandler;
this.workflowManager = workflowManager;
getAAIservice();
@@ -104,19 +105,21 @@ public class CommandTask implements Runnable {
@Override
public void run() {
- logger.debug("Starting execution of command :" + commandRequest);
+ logger.debug("Starting execution of command: " + commandRequest);
setInitialLogProperties(commandRequest);
final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
WorkflowRequest workflowRequest = new WorkflowRequest();
- workflowRequest.setRequestContext(runtimeContext.getRequestContext());
- workflowRequest.setResponseContext(runtimeContext.getResponseContext());
+ final RequestContext reqContext = runtimeContext.getRequestContext();
+ workflowRequest.setRequestContext(reqContext);
+ final ResponseContext respContext = runtimeContext.getResponseContext();
+ workflowRequest.setResponseContext(respContext);
workflowRequest.setVnfContext(runtimeContext.getVnfContext());
- logger.debug("Executing workflow :" + workflowRequest);
+ logger.debug("Executing workflow: " + workflowRequest);
workflowManager.executeWorkflow(workflowRequest);
- logger.debug("Completed execution workflow with response:"+ commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext());
+ logger.debug("Completed execution workflow with response: " + respContext);
try {
- if (VNFOperation.Terminate == commandRequest.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction())
+ if (VNFOperation.Terminate == reqContext.getAction())
updateAAIForTerminate(commandRequest);
} catch (AAIServiceException e) {
logger.error("Exception = " + e);
@@ -124,36 +127,37 @@ public class CommandTask implements Runnable {
Status updatedStatus = new Status();
updatedStatus.setCode(401);
updatedStatus.setMessage("Failed to update VNF status in A&AI");
- commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(updatedStatus);
+ respContext.setStatus(updatedStatus);
throw new RuntimeException(e);
- }finally {
- requestHandler.onRequestExecutionEnd(commandRequest.getCommandExecutorInput().getRuntimeContext());
+ } finally {
+ requestHandler.onRequestExecutionEnd(runtimeContext);
clearRequestLogProperties();
}
}
private void updateAAIForTerminate(CommandRequest commandRequest) throws AAIServiceException {
- final int statusCode = commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus().getCode();
+ final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
+ final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
- logger.debug("Workflow Execution Status = "+ statusCode);
+ logger.debug("Workflow Execution Status = " + statusCode);
if (statusCode == 100 || statusCode == 400) {
+ String id = runtimeContext.getVnfContext().getId();
SvcLogicContext ctx = new SvcLogicContext();
- ctx = getVnfdata(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), "vnf", ctx);
- deleteGenericVnfData(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(),
- ctx.getAttribute("vnf.resource-version"));
+ ctx = getVnfdata(id, "vnf", ctx);
+ deleteGenericVnfData(id, ctx.getAttribute("vnf.resource-version"));
}
}
- private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
- String key="generic-vnf.vnf-id = '" + vnf_id + "'" + " AND http-header.Real-Time = 'true'";
+ private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) {
+ String key = "generic-vnf.vnf-id = '" + vnf_id + "'" + " AND http-header.Real-Time = 'true'";
logger.debug("inside getVnfdata=== " + key);
try {
- SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
- if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
+ SvcLogicResource.QueryStatus response =
+ aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
+ if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
logger.warn("VNF " + vnf_id + " not found while updating A&AI");
throw new RuntimeException("VNF not found for vnf_id = " + vnf_id);
- }
- else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
+ } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
}
logger.info("AAIResponse: " + response.toString());
@@ -166,24 +170,24 @@ public class CommandTask implements Runnable {
private void setInitialLogProperties(CommandRequest request) {
- String reqId = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getRequestId();
+ RequestContext reqContext = request.getCommandExecutorInput().getRuntimeContext().getRequestContext();
+ CommonHeader reqHdr = reqContext.getCommonHeader();
+ String reqId = reqHdr.getRequestId();
try {
MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.fromString(reqId).toString());
//reaching here without exception means existing RequestId is
- //valid UUID as per ECOMP logging standards
+ //valid UUID as per ONAP logging standards
} catch (Exception e) {
String reqIdUUID = UUID.randomUUID().toString();
MDC.put(Configuration.MDC_KEY_REQUEST_ID, reqIdUUID);
logger.info("Replaced invalid requestID of " + reqId + ". New value is " + reqIdUUID + ".");
}
- if (request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId() != null) {
- MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID,
- request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId());
- MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME,
- request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getOriginatorId());
- MDC.put(Configuration.MDC_SERVICE_NAME,
- request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction().name());
+ String svcInstanceId = reqContext.getActionIdentifiers().getServiceInstanceId();
+ if (svcInstanceId != null) {
+ MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID, svcInstanceId);
+ MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, reqHdr.getOriginatorId());
+ MDC.put(Configuration.MDC_SERVICE_NAME, reqContext.getAction().name());
}
try {
MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
@@ -191,11 +195,10 @@ public class CommandTask implements Runnable {
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
- MDC.put(Configuration.MDC_INSTANCE_UUID, ""); // make instanse_UUID generation once during APPC-instance deploying
+ MDC.put(Configuration.MDC_INSTANCE_UUID, ""); // confine instance_UUID generation to APPC-instance deployment
}
- private void clearRequestLogProperties()
- {
+ private void clearRequestLogProperties() {
try {
MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
MDC.remove(Configuration.MDC_SERVICE_INSTANCE_ID);
@@ -213,7 +216,7 @@ public class CommandTask implements Runnable {
AAIRequest request = aaiService.getRequestFromResource("generic-vnf");
request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
response = aaiService.delete(request, resourceVersion);
- } catch(AAIServiceException aaiexc) {
+ } catch (AAIServiceException aaiexc) {
throw aaiexc;
} catch (Exception exc) {
logger.warn("deleteGenericVnfData", exc);
diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandExecutor.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandExecutor.java
index 83c6a0f42..3385b8489 100644
--- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandExecutor.java
+++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandExecutor.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,23 +11,19 @@
* 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.onap.appc.executor.impl;
-/**
- *
- */
-
import org.junit.Assert;
import org.junit.Before;
@@ -48,8 +44,8 @@ import java.util.concurrent.TimeUnit;
public class TestCommandExecutor {
- private static final String API_VERSION= "2.0.0";
- private static final String ORIGINATOR_ID= "1";
+ private static final String API_VERSION = "2.0.0";
+ private static final String ORIGINATOR_ID = "1";
private CommandExecutorImpl commandExecutor;
@@ -59,16 +55,16 @@ public class TestCommandExecutor {
private Date timeStamp = new Date();
private String requestId = "1";
- private CommandExecutorInput commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30000, "1.0",
- timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ;
- private CommandExecutorInput commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0",
- timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ;
+ private CommandExecutorInput commandExecutorInputConfigure = populateCommandExecutorInput("FIREWALL", 30000, "1.0",
+ timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure, "15", "");
+ private CommandExecutorInput commandExecutorInputSync = populateCommandExecutorInput("FIREWALL", 30, "1.0",
+ timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync, "15", "");
private CommandTask commandTask;
@Before
- public void init()throws Exception {
- requestHandler= Mockito.mock(RequestHandler.class);
- workflowManager= Mockito.mock(WorkFlowManager.class);
+ public void init() throws Exception {
+ requestHandler = Mockito.mock(RequestHandler.class);
+ workflowManager = Mockito.mock(WorkFlowManager.class);
executionQueueService = Mockito.mock(ExecutionQueueService.class);
@@ -79,7 +75,10 @@ public class TestCommandExecutor {
commandExecutor.initialize();
commandTask = Mockito.mock(CommandTask.class);
Mockito.when(commandTask.getCommandRequest()).thenReturn(new CommandRequest(commandExecutorInputConfigure));
- PowerMockito.whenNew(CommandTask.class).withParameterTypes(RequestHandler.class,WorkFlowManager.class).withArguments(requestHandler,workflowManager).thenReturn(commandTask);
+ PowerMockito.whenNew(CommandTask.class)
+ .withParameterTypes(RequestHandler.class, WorkFlowManager.class)
+ .withArguments(requestHandler, workflowManager)
+ .thenReturn(commandTask);
}
@Test
@@ -93,21 +92,26 @@ public class TestCommandExecutor {
}
@Test(expected = APPCException.class)
- public void testNegativeFlow_LCM() throws APPCException{
- Mockito.doThrow(new APPCException("Failed to enqueue request")).when(executionQueueService).putMessage((Runnable) Mockito.anyObject(),Mockito.anyLong(),(TimeUnit) Mockito.anyObject());
+ public void testNegativeFlow_LCM() throws APPCException {
+ Mockito.doThrow(new APPCException("Failed to enqueue request"))
+ .when(executionQueueService)
+ .putMessage((Runnable) Mockito.anyObject(), Mockito.anyLong(), (TimeUnit) Mockito.anyObject());
commandExecutor.executeCommand(commandExecutorInputSync);
}
- private CommandExecutorInput pouplateCommandExecutorInput(String vnfType, int ttl, String vnfVersion, Date timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload){
+ private CommandExecutorInput populateCommandExecutorInput(String vnfType, int ttl, String vnfVersion,
+ Date timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID,
+ VNFOperation action, String vnfId, String payload) {
CommandExecutorInput commandExecutorInput = createCommandExecutorInputWithSubObjects();
RuntimeContext runtimeContext = commandExecutorInput.getRuntimeContext();
RequestContext requestContext = runtimeContext.getRequestContext();
- requestContext.getCommonHeader().getFlags().setTtl(ttl);
- requestContext.getCommonHeader().setApiVer(apiVersion);
- requestContext.getCommonHeader().setTimestamp(timeStamp);
- requestContext.getCommonHeader().setRequestId(requestId);
- requestContext.getCommonHeader().setSubRequestId(subRequestID);
- requestContext.getCommonHeader().setOriginatorId(originatorID);
+ CommonHeader commonHeader = requestContext.getCommonHeader();
+ commonHeader.getFlags().setTtl(ttl);
+ commonHeader.setApiVer(apiVersion);
+ commonHeader.setTimestamp(timeStamp);
+ commonHeader.setRequestId(requestId);
+ commonHeader.setSubRequestId(subRequestID);
+ commonHeader.setOriginatorId(originatorID);
requestContext.setAction(action);
requestContext.setPayload(payload);
requestContext.getActionIdentifiers().setVnfId(vnfId);
@@ -135,4 +139,3 @@ public class TestCommandExecutor {
return commandExecutorInput;
}
}
-
diff --git a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandTask.java b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandTask.java
index 1bcf8d3f1..4b94282ab 100644
--- a/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandTask.java
+++ b/appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/onap/appc/executor/impl/TestCommandTask.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,15 @@
* 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=========================================================
*/
@@ -72,7 +72,7 @@ import java.util.Map;
@RunWith(PowerMockRunner.class)
@PrepareForTest({FrameworkUtil.class, InetAddress.class})
public class TestCommandTask {
- CommandTask task ;
+ CommandTask task;
private RequestHandler requestHandler;
private WorkFlowManager workflowManager;
private AAIService aaiService;
@@ -81,66 +81,72 @@ public class TestCommandTask {
private Bundle bundleService = Mockito.mock(Bundle.class);
private ServiceReference sref = Mockito.mock(ServiceReference.class);
- private static final String TTL_FLAG= "TTL";
- private static final String API_VERSION= "2.0.0";
- private static final String ORIGINATOR_ID= "1";
+ private static final String TTL_FLAG = "TTL";
+ private static final String API_VERSION = "2.0.0";
+ private static final String ORIGINATOR_ID = "1";
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Before
- public void init() throws UnknownHostException{
- aaiService = Mockito.mock(AAIService.class);
+ public void init() throws UnknownHostException {
+ aaiService = Mockito.mock(AAIService.class);
PowerMockito.mockStatic(FrameworkUtil.class);
PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService);
PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref);
PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService);
- requestHandler = Mockito.mock(RequestHandler.class);
+ requestHandler = Mockito.mock(RequestHandler.class);
workflowManager = Mockito.mock(WorkFlowManager.class);
task = Mockito.spy(new CommandTask(requestHandler, workflowManager));
}
@Test
- public void testRunPositive(){
+ public void testRunPositive() {
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "11", setTTLInFlags("30"), VNFOperation.Sync, "1", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "11", setTTLInFlags("30"),
+ VNFOperation.Sync, "1", "1.0"));
task.run();
- Assert.assertNotNull(task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
+ Assert.assertNotNull(
+ task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
}
@Test
- public void testRunPositiveTerminateFailed(){
+ public void testRunPositiveTerminateFailed() {
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(300, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
task.run();
- Assert.assertNotNull(task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
+ Assert.assertNotNull(
+ task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
}
@Test
- public void testRunPositiveTerminateSucceeded() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveTerminateSucceeded() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
- Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class))).thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
+ Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class)))
+ .thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
Mockito.when(mockAai.getRequestFromResource("generic-vnf")).thenReturn(Mockito.mock(AAIRequest.class));
Mockito.when(mockAai.delete(Mockito.any(AAIRequest.class), Mockito.anyString())).thenReturn(true);
Whitebox.setInternalState(task, "aaiService", mockAai);
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
task.run();
}
@Test
- public void testRunPositiveTerminateNotFound() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveTerminateNotFound() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
@@ -152,7 +158,8 @@ public class TestCommandTask {
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("VNF not found for vnf_id = ");
@@ -160,7 +167,7 @@ public class TestCommandTask {
}
@Test
- public void testRunPositiveTerminateFailure() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveTerminateFailure() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
@@ -172,7 +179,8 @@ public class TestCommandTask {
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("Error Querying AAI with vnfID = ");
@@ -180,19 +188,21 @@ public class TestCommandTask {
}
@Test
- public void testRunPositiveAaiServiceException() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveAaiServiceException() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class)))
.thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
Mockito.when(mockAai.getRequestFromResource("generic-vnf")).thenReturn(Mockito.mock(AAIRequest.class));
- Mockito.when(mockAai.delete(Mockito.any(AAIRequest.class), Mockito.anyString())).thenThrow(new AAIServiceException("ERROR IN DELETE"));
+ Mockito.when(mockAai.delete(Mockito.any(AAIRequest.class), Mockito.anyString()))
+ .thenThrow(new AAIServiceException("ERROR IN DELETE"));
Whitebox.setInternalState(task, "aaiService", mockAai);
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectCause(allOf(isA(AAIServiceException.class),
@@ -213,14 +223,15 @@ public class TestCommandTask {
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectCause(isA(SvcLogicException.class));
task.run();
}
- private WorkflowResponse getWorkflowResponse (){
+ private WorkflowResponse getWorkflowResponse () {
WorkflowResponse wfResponse = new WorkflowResponse();
ResponseContext responseContext = createResponseContextWithObjects();
wfResponse.setResponseContext(responseContext);
@@ -229,7 +240,7 @@ public class TestCommandTask {
return wfResponse;
}
- private ResponseContext createResponseContextWithObjects(){
+ private ResponseContext createResponseContextWithObjects() {
ResponseContext responseContext = new ResponseContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
@@ -240,41 +251,44 @@ public class TestCommandTask {
return responseContext;
}
- private void setResponseContext(int statusCode ,RuntimeContext runtimeContext ){
+ private void setResponseContext(int statusCode, RuntimeContext runtimeContext) {
ResponseContext responseContext = createResponseContextWithObjects();
responseContext.getStatus().setCode(statusCode);
runtimeContext.setResponseContext(responseContext);
}
private CommandRequest getCommandRequest(String vnfType, Integer ttl, Date timeStamp, String requestId,
- Map<String, Object> flags, VNFOperation command, String vnfId, String vnfVersion ){
+ Map<String, Object> flags, VNFOperation command, String vnfId, String vnfVersion) {
- CommandExecutorInput commandExecutorInput =
- pouplateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, "");
+ CommandExecutorInput commandExecutorInput = populateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp,
+ API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, "");
CommandRequest request = new CommandRequest(commandExecutorInput);
request.setCommandExecutorInput(commandExecutorInput);
request.setCommandInTimeStamp(new Date());
return request;
}
- private CommandExecutorInput pouplateCommandExecutorInput(String vnfType, int ttl, String vnfVersion, Date timeStamp, String apiVersion,
- String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload){
+ private CommandExecutorInput populateCommandExecutorInput(String vnfType, int ttl, String vnfVersion,
+ Date timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID,
+ VNFOperation action, String vnfId, String payload) {
CommandExecutorInput commandExecutorInput = createCommandExecutorInputWithSubObjects();
RuntimeContext runtimeContext = commandExecutorInput.getRuntimeContext();
RequestContext requestContext = runtimeContext.getRequestContext();
+ CommonHeader commonHeader = requestContext.getCommonHeader();
ResponseContext responseContext = createResponseContextWithSuObjects();
runtimeContext.setResponseContext(responseContext);
- requestContext.getCommonHeader().getFlags().setTtl(ttl);
- requestContext.getCommonHeader().setApiVer(apiVersion);
- requestContext.getCommonHeader().setTimestamp(timeStamp);
- requestContext.getCommonHeader().setRequestId(requestId);
- requestContext.getCommonHeader().setSubRequestId(subRequestID);
- requestContext.getCommonHeader().setOriginatorId(originatorID);
+ commonHeader.getFlags().setTtl(ttl);
+ commonHeader.setApiVer(apiVersion);
+ commonHeader.setTimestamp(timeStamp);
+ commonHeader.setRequestId(requestId);
+ commonHeader.setSubRequestId(subRequestID);
+ commonHeader.setOriginatorId(originatorID);
requestContext.setAction(action);
requestContext.setPayload(payload);
- requestContext.getActionIdentifiers().setVnfId(vnfId);
- requestContext.getActionIdentifiers().setServiceInstanceId("test");
+ ActionIdentifiers actionIdentifiers = requestContext.getActionIdentifiers();
+ actionIdentifiers.setVnfId(vnfId);
+ actionIdentifiers.setServiceInstanceId("test");
VNFContext vnfContext = runtimeContext.getVnfContext();
vnfContext.setType(vnfType);
vnfContext.setId(vnfId);
@@ -289,7 +303,7 @@ public class TestCommandTask {
return commandExecutorInput;
}
- private ResponseContext createResponseContextWithSuObjects(){
+ private ResponseContext createResponseContextWithSuObjects() {
ResponseContext responseContext = new ResponseContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
@@ -315,9 +329,9 @@ public class TestCommandTask {
return runtimeContext;
}
- private Map<String,Object> setTTLInFlags( String value){
- Map<String,Object> flags = new HashMap<String,Object>();
- if( value != null || !("".equalsIgnoreCase(value))){
+ private Map<String, Object> setTTLInFlags(String value) {
+ Map<String, Object> flags = new HashMap<String, Object>();
+ if (value != null || !("".equalsIgnoreCase(value))) {
flags.put(TTL_FLAG, value);
}
return flags;
diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcDatabaseConnectionPool.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcDatabaseConnectionPool.java
index 1f4a75911..2a1484c2d 100644
--- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcDatabaseConnectionPool.java
+++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/AppcDatabaseConnectionPool.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -19,7 +19,6 @@
* 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=========================================================
*/
@@ -41,8 +40,8 @@ import java.util.Map;
* This class implements
*
* @see org.onap.appc.dao.util.dbcp.DBConnectionPool
- * that provides concrete implemenation of accessing appc database which basic setup
- * data would be got from global configuration.
+ * that provides a concrete implementation of appc database access
+ * with basic setup data extracted from the global configuration.
* @see org.onap.appc.configuration.Configuration
* <p>
* The singleton instance of this class has been instantiated by blueprint.
@@ -88,8 +87,8 @@ public class AppcDatabaseConnectionPool implements DBConnectionPoolService {
try {
connection = dbConnectionPool.getConnection();
} catch (DBConnectionPoolException e) {
- logger.error("DB connection pool is created failed." +
- "Please make sure the provided information is correct.");
+ logger.error("DB connection pool creation failed."
+ + " Please make sure the provided information is correct.");
}
if (connection != null) {
diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/api/DBConnectionPoolService.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/api/DBConnectionPoolService.java
index 6f51fec3c..0a163544d 100644
--- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/api/DBConnectionPoolService.java
+++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/api/DBConnectionPoolService.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,14 @@
* 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=========================================================
*/
@@ -45,10 +44,10 @@ import java.util.Map;
* <blockquote><pre>
* {@code
* private AppcDatabaseConnectionPool pool;
- * public void setAppcDatabaseConnectionPool(AppcDatabaseConnectionPool pool){
+ * public void setAppcDatabaseConnectionPool(AppcDatabaseConnectionPool pool) {
* this.pool = pool;
* }
- * public queryAppcDatabase(AppcDatabaseConnectionPool pool){
+ * public queryAppcDatabase(AppcDatabaseConnectionPool pool) {
* Connection connection = null;
* try {
* connection = pool.getConnection();
@@ -64,11 +63,11 @@ import java.util.Map;
* System.out.println("# of entries in db:");
* int numcols = rs.getMetaData().getColumnCount();
* System.out.println(pool.getDataSourceStatus());
- * }catch (SQLException e) {
+ * } catch (SQLException e) {
* e.printStackTrace();
* } finally {
* try {
- * pool.close(rs, stmt, conn);
+ * pool.close(rs, stmt, conn);
* } catch (DataAccessException e) {
* e.printStackTrace();
* }
diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/dbcp/DBConnectionPool.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/dbcp/DBConnectionPool.java
index d201f399c..5381721ea 100644
--- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/dbcp/DBConnectionPool.java
+++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/main/java/org/onap/appc/dao/util/dbcp/DBConnectionPool.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,14 @@
* 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=========================================================
*/
@@ -63,11 +62,10 @@ public class DBConnectionPool implements DBConnectionPoolService {
this(connectURI, username, password, driverClass, null, null, null, null, null);
}
- public DBConnectionPool(String connectURI, String username, String password,
- String driverClass, Integer initialSize, Integer maxActive,
- Integer maxIdle, Integer maxWait, Integer minIdle) {
+ public DBConnectionPool(String connectURI, String username, String password, String driverClass,
+ Integer initialSize, Integer maxActive, Integer maxIdle, Integer maxWait, Integer minIdle) {
this.dataSource = getBasicDataSource(connectURI, username, password, driverClass,
- initialSize, maxActive, maxIdle, maxWait, minIdle);
+ initialSize, maxActive, maxIdle, maxWait, minIdle);
}
/**
@@ -87,8 +85,8 @@ public class DBConnectionPool implements DBConnectionPoolService {
throw new DBConnectionPoolException(e);
}
- if(connection == null){
- //
+ if (connection == null) {
+ // Don't necessarily know why, but can report. . . .
throw new DBConnectionPoolException("Connection was not created");
}
@@ -125,8 +123,8 @@ public class DBConnectionPool implements DBConnectionPoolService {
}
protected BasicDataSource getBasicDataSource(String connectURI, String username, String password,
- String driverClass, Integer initialSize, Integer maxtotal,
- Integer maxIdle, Integer maxWaitMillis, Integer minIdle) {
+ String driverClass, Integer initialSize, Integer maxTotal, Integer maxIdle, Integer maxWaitMillis,
+ Integer minIdle) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(username);
@@ -136,8 +134,8 @@ public class DBConnectionPool implements DBConnectionPoolService {
if (initialSize != null) {
dataSource.setInitialSize(initialSize);
}
- if (maxtotal != null) {
- dataSource.setMaxTotal(maxtotal);
+ if (maxTotal != null) {
+ dataSource.setMaxTotal(maxTotal);
}
if (maxIdle != null) {
dataSource.setMaxIdle(maxIdle);
diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/AppcDatabaseConnectionPoolTest.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/AppcDatabaseConnectionPoolTest.java
index ad1b4ea0f..98ef98ab8 100644
--- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/AppcDatabaseConnectionPoolTest.java
+++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/AppcDatabaseConnectionPoolTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -19,7 +19,6 @@
* 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=========================================================
*/
@@ -106,8 +105,8 @@ public class AppcDatabaseConnectionPoolTest {
@Test
public void testArgumentConstructor() {
- AppcDatabaseConnectionPool appcDatabaseConnectionPool = new AppcDatabaseConnectionPool(dbUrl, username,
- password, driver);
+ AppcDatabaseConnectionPool appcDatabaseConnectionPool =
+ new AppcDatabaseConnectionPool(dbUrl, username, password, driver);
Object dbConnectionPool = Whitebox.getInternalState(appcDatabaseConnectionPool, "dbConnectionPool");
Assert.assertNotNull(dbConnectionPool);
}
diff --git a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/dbcp/DBConnectionPoolTest.java b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/dbcp/DBConnectionPoolTest.java
index d2ac778a4..a26f8c037 100644
--- a/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/dbcp/DBConnectionPoolTest.java
+++ b/appc-dispatcher/appc-dispatcher-common/appc-data-access-lib/src/test/java/org/onap/appc/dao/util/dbcp/DBConnectionPoolTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,14 @@
* 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=========================================================
*/
@@ -39,7 +38,6 @@ import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
-
public class DBConnectionPoolTest {
private final String connectURI = "jdbc:h2:mem:~/test;MODE=MYSQL;DB_CLOSE_DELAY=-1";
private final String username = "sa";
@@ -104,8 +102,8 @@ public class DBConnectionPoolTest {
@Test
public void testShutdownException() throws SQLException {
- DBConnectionPool dbcpSpy = Mockito.spy(new DBConnectionPool(connectURI, username, password, driverClass,
- 0, 0, 0, 0, 0));
+ DBConnectionPool dbcpSpy =
+ Mockito.spy(new DBConnectionPool(connectURI, username, password, driverClass, 0, 0, 0, 0, 0));
BasicDataSource mockDataSource = Mockito.mock(BasicDataSource.class);
Mockito.doThrow(new SQLException()).when(mockDataSource).close();
Whitebox.setInternalState(dbcpSpy, "dataSource", mockDataSource);
diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/test/java/org/onap/appc/domainmodel/lcm/TestRequestContext.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/test/java/org/onap/appc/domainmodel/lcm/TestRequestContext.java
index 4df409995..7d56ab732 100644
--- a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/test/java/org/onap/appc/domainmodel/lcm/TestRequestContext.java
+++ b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/test/java/org/onap/appc/domainmodel/lcm/TestRequestContext.java
@@ -6,6 +6,8 @@
*=================================================================================
* Modifications Copyright 2018 IBM.
*=================================================================================
+* Modifications Copyright 2019 AT&T Intellectual Property
+*=================================================================================
* 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
@@ -42,26 +44,26 @@ public class TestRequestContext {
@Test
public void testGetActionLevel_ValidEnumConstant() {
requestContext.setActionLevel(ActionLevel.VM);
- Assert.assertNotNull(requestContext. getActionLevel());
- Assert.assertEquals(requestContext. getActionLevel(),ActionLevel.VM);
+ Assert.assertNotNull(requestContext.getActionLevel());
+ Assert.assertEquals(requestContext.getActionLevel(), ActionLevel.VM);
}
@Test
public void testgetAdditionalContext() {
- testadditionalContext=new HashMap<String, String>();
+ testadditionalContext = new HashMap<String, String>();
testadditionalContext.put("A", "a");
requestContext.setAdditionalContext(testadditionalContext);
Assert.assertNotNull(requestContext.getAdditionalContext());
Assert.assertTrue(requestContext.getAdditionalContext().containsKey("A"));
Assert.assertTrue(requestContext.getAdditionalContext().containsValue("a"));
}
-
+
@Test
public void testAddKeyValueToAdditionalContext() {
- String key="key1";
- String value="value1";
+ String key = "key1";
+ String value = "value1";
requestContext.addKeyValueToAdditionalContext(key, value);
- Map<String, String> additionalContext= requestContext.getAdditionalContext();
+ Map<String, String> additionalContext = requestContext.getAdditionalContext();
Assert.assertEquals("value1", additionalContext.get("key1"));
}
@@ -82,27 +84,24 @@ public class TestRequestContext {
public void testToString_ContainsString() {
assertTrue(requestContext.toString().contains("RequestContext{commonHeader"));
}
-
+
@Test
- public void testGetSetCommonHeader()
- {
+ public void testGetSetCommonHeader() {
CommonHeader commonHeader = new CommonHeader();
requestContext.setCommonHeader(commonHeader);
assertEquals(commonHeader, requestContext.getCommonHeader());
}
-
+
@Test
- public void testGetSetActionIdentifiers()
- {
- ActionIdentifiers actionIdentifiers= new ActionIdentifiers();
+ public void testGetSetActionIdentifiers() {
+ ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
requestContext.setActionIdentifiers(actionIdentifiers);
assertEquals(actionIdentifiers, requestContext.getActionIdentifiers());
}
-
+
@Test
- public void testGetSetAction()
- {
- VNFOperation action= VNFOperation.ActionStatus;
+ public void testGetSetAction() {
+ VNFOperation action = VNFOperation.ActionStatus;
requestContext.setAction(action);
assertEquals(action, requestContext.getAction());
}
diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java
index 15ed9ad4b..0acb2b5a0 100644
--- a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java
+++ b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java
@@ -19,7 +19,6 @@
* 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=========================================================
*/
@@ -37,17 +36,17 @@ import org.onap.ccsdk.sli.core.dblib.DbLibService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.sql.rowset.CachedRowSet;
import java.sql.SQLException;
+import javax.sql.rowset.CachedRowSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.time.temporal.ChronoUnit;
import static org.onap.appc.transactionrecorder.objects.TransactionConstants.TRANSACTION_ATTRIBUTES.*;
import static org.onap.appc.transactionrecorder.objects.TransactionConstants.*;
@@ -74,44 +73,41 @@ public class TransactionRecorderImpl implements TransactionRecorder {
*/
@Override
public void store(TransactionRecord record) throws APPCException {
- if (logger.isTraceEnabled()) {
- logger.trace("Transaction data insertion into DB");
- }
- final String STORE_DATE_QUERY = TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS +
- "(" + TRANSACTION_ID.getColumnName() + TransactionConstants.COMMA +
- ORIGIN_TIMESTAMP.getColumnName() + TransactionConstants.COMMA +
- REQUEST_ID.getColumnName() + TransactionConstants.COMMA +
- SUBREQUEST_ID.getColumnName() + TransactionConstants.COMMA +
- ORIGINATOR_ID.getColumnName() + TransactionConstants.COMMA +
- START_TIME.getColumnName() + TransactionConstants.COMMA +
- END_TIME.getColumnName() + TransactionConstants.COMMA +
- TARGET_ID.getColumnName() + TransactionConstants.COMMA +
- TARGET_TYPE.getColumnName() + TransactionConstants.COMMA +
- OPERATION.getColumnName() + TransactionConstants.COMMA +
- RESULT_CODE.getColumnName() + TransactionConstants.COMMA +
- DESCRIPTION.getColumnName() + TransactionConstants.COMMA +
- STATE.getColumnName() + TransactionConstants.COMMA +
- SERVICE_INSTANCE_ID + TransactionConstants.COMMA +
- VNFC_NAME + TransactionConstants.COMMA +
- VSERVER_ID + TransactionConstants.COMMA +
- VF_MODULE_ID + TransactionConstants.COMMA +
- MODE + ") " +
- "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ logger.trace("Transaction data insertion into DB");
+ final String STORE_DATE_QUERY =
+ TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS
+ + "(" + TRANSACTION_ID.getColumnName() + TransactionConstants.COMMA
+ + ORIGIN_TIMESTAMP.getColumnName() + TransactionConstants.COMMA
+ + REQUEST_ID.getColumnName() + TransactionConstants.COMMA
+ + SUBREQUEST_ID.getColumnName() + TransactionConstants.COMMA
+ + ORIGINATOR_ID.getColumnName() + TransactionConstants.COMMA
+ + START_TIME.getColumnName() + TransactionConstants.COMMA
+ + END_TIME.getColumnName() + TransactionConstants.COMMA
+ + TARGET_ID.getColumnName() + TransactionConstants.COMMA
+ + TARGET_TYPE.getColumnName() + TransactionConstants.COMMA
+ + OPERATION.getColumnName() + TransactionConstants.COMMA
+ + RESULT_CODE.getColumnName() + TransactionConstants.COMMA
+ + DESCRIPTION.getColumnName() + TransactionConstants.COMMA
+ + STATE.getColumnName() + TransactionConstants.COMMA
+ + SERVICE_INSTANCE_ID + TransactionConstants.COMMA
+ + VNFC_NAME + TransactionConstants.COMMA
+ + VSERVER_ID + TransactionConstants.COMMA
+ + VF_MODULE_ID + TransactionConstants.COMMA
+ + MODE + ") "
+ + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
dbLibService.writeData(STORE_DATE_QUERY, prepareArguments(record), SCHEMA);
} catch (SQLException e) {
logger.error("Error on storing record " + record.toString(), e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
- if (logger.isTraceEnabled()) {
- logger.trace("Transaction Data Inserted Successfully into DB");
- }
+ logger.trace("Transaction Data Inserted Successfully into DB");
}
@Override
public void update(String key,
- String requestId,
- Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
+ String requestId,
+ Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
logger.debug("Inside update in TransactionRecorderImpl");
if (appcInstanceId != null && checkIfNullInstanceEntryExist(key, requestId)) {
@@ -151,15 +147,12 @@ public class TransactionRecorderImpl implements TransactionRecorder {
logger.error("Error in updating records in updateTransactionEntry " + e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
- if (logger.isTraceEnabled()) {
- logger.trace("Transaction data updated successfully");
- }
-
+ logger.trace("Transaction data updated successfully");
}
private void updateNullInstanceEntry(String key,
- String requestId,
- Map<TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
+ String requestId,
+ Map<TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
logger.debug("Inside updateNullInstanceEntry");
ArrayList<String> values = new ArrayList<>();
@@ -180,7 +173,7 @@ public class TransactionRecorderImpl implements TransactionRecorder {
if (logger.isDebugEnabled()) {
logger.debug("Before updating Transaction table the Query is: " + query);
for (String value : values) {
- logger.debug("Value for Transaction table: " + value);
+ logger.debug("Value for Transaction table: " + value);
}
}
Boolean result = dbLibService.writeData(query, values, SCHEMA);
@@ -195,24 +188,24 @@ public class TransactionRecorderImpl implements TransactionRecorder {
private boolean checkIfNullInstanceEntryExist(String key, String requestId) throws APPCException {
logger.debug("Entered checkIfNullInstanceEntryExist");
- String nullInstanceCheckQuery = new String("SELECT COUNT(*) as ROWCOUNT FROM " +
- TransactionConstants.TRANSACTIONS + WHERE +
- TRANSACTION_ID.getColumnName() + " = ? AND " +
- REQUEST_ID.getColumnName() + " = ? ");
+ String nullInstanceCheckQuery = new String(
+ "SELECT COUNT(*) as ROWCOUNT FROM "
+ + TransactionConstants.TRANSACTIONS + WHERE
+ + TRANSACTION_ID.getColumnName() + " = ? AND "
+ + REQUEST_ID.getColumnName() + " = ? ");
ArrayList<String> nullInstanceCheckParams = new ArrayList<>();
nullInstanceCheckParams.add(null + "~" + key);
nullInstanceCheckParams.add(requestId);
- try{
- CachedRowSet rowSet = dbLibService.getData(nullInstanceCheckQuery, nullInstanceCheckParams, SCHEMA);
+ try (CachedRowSet rowSet = dbLibService.getData(nullInstanceCheckQuery, nullInstanceCheckParams, SCHEMA)) {
int noRows = 0;
if (rowSet != null && rowSet.first()) {
noRows = rowSet.getInt("ROWCOUNT");
- logger.info("No of Rows in Transactions Table with TRANSACTION_ID: " +
- null + "~" + key + " and REQUEST_ID " + requestId + " is: " + noRows);
+ logger.info("No of Rows in Transactions Table with TRANSACTION_ID: "
+ + null + "~" + key + " and REQUEST_ID " + requestId + " is: " + noRows);
}
- if(noRows > 0)
+ if (noRows > 0)
return true;
} catch (SQLException e) {
logger.error("Error in checkIfNullInstanceEntryExist in the transaction table", e);
@@ -223,14 +216,12 @@ public class TransactionRecorderImpl implements TransactionRecorder {
@Override
public void markTransactionsAborted(String appcInstanceId) {
- if (logger.isTraceEnabled()) {
- logger.trace("marking in progress transactions to aborted");
- }
+ logger.trace("marking in progress transactions to aborted");
final String updateQuery =
- "UPDATE " + TransactionConstants.TRANSACTIONS +
- " SET " + STATE.getColumnName() + " = '" + RequestStatus.ABORTED.name() + "',"
- + END_TIME.getColumnName() + " = ? " +
- WHERE + TRANSACTION_ID.getColumnName() + " LIKE '" + appcInstanceId + "%' AND "
+ "UPDATE " + TransactionConstants.TRANSACTIONS
+ + " SET " + STATE.getColumnName() + " = '" + RequestStatus.ABORTED.name() + "',"
+ + END_TIME.getColumnName() + " = ? "
+ + WHERE + TRANSACTION_ID.getColumnName() + " LIKE '" + appcInstanceId + "%' AND "
+ STATE.getColumnName() + " in (?,?)";
if (logger.isDebugEnabled()) {
@@ -248,19 +239,18 @@ public class TransactionRecorderImpl implements TransactionRecorder {
logger.error(message);
throw new RuntimeException(message, e);
}
- if (logger.isTraceEnabled()) {
- logger.trace("In progress transactions marked aborted");
- }
+ logger.trace("In progress transactions marked aborted");
}
@Override
public List<TransactionRecord> getInProgressRequests(TransactionRecord record, int interval) throws APPCException {
- String IN_PROGRESS_REQUESTS_QUERY = "SELECT * FROM " +
- TransactionConstants.TRANSACTIONS + WHERE +
- TARGET_ID + " = ? AND " +
- STATE.getColumnName() + " IN (?,?) AND " +
- START_TIME.getColumnName() + " < ?";
+ String IN_PROGRESS_REQUESTS_QUERY =
+ "SELECT * FROM "
+ + TransactionConstants.TRANSACTIONS + WHERE
+ + TARGET_ID + " = ? AND "
+ + STATE.getColumnName() + " IN (?,?) AND "
+ + START_TIME.getColumnName() + " < ?";
ArrayList<String> inProgressQueryParams = new ArrayList<>();
Instant window = record.getStartTime().minus(interval, ChronoUnit.HOURS);
@@ -273,37 +263,40 @@ public class TransactionRecorderImpl implements TransactionRecorder {
inProgressQueryParams.add(dateToStringConverterMillis(window));
}
- try (CachedRowSet rowSet = dbLibService.getData(IN_PROGRESS_REQUESTS_QUERY, inProgressQueryParams, SCHEMA)) {
+ try (CachedRowSet rowSet =
+ dbLibService.getData(IN_PROGRESS_REQUESTS_QUERY, inProgressQueryParams, SCHEMA)) {
List<TransactionRecord> inProgressRecords = new ArrayList<>();
TransactionRecord transaction;
- while (rowSet.next()) {
- transaction = new TransactionRecord();
- transaction.setTransactionId(rowSet.getString(TRANSACTION_ID.getColumnName()));
- transaction.setRequestId(rowSet.getString(REQUEST_ID.getColumnName()));
- transaction.setSubRequestId(rowSet.getString(SUBREQUEST_ID.getColumnName()));
- transaction.setOriginatorId(rowSet.getString(ORIGINATOR_ID.getColumnName()));
- transaction.setStartTime(stringToDateConverterMillis(rowSet.getString(START_TIME.getColumnName())));
- transaction.setTargetId(rowSet.getString(TARGET_ID.getColumnName()));
- transaction.setTargetType(rowSet.getString(TARGET_TYPE.getColumnName()));
- transaction.setOperation(VNFOperation.valueOf(rowSet.getString(OPERATION.getColumnName())));
- transaction.setRequestState(RequestStatus.valueOf(rowSet.getString(STATE.getColumnName())));
- transaction.setVnfcName(rowSet.getString(VNFC_NAME.getColumnName()));
- transaction.setVserverId(rowSet.getString(VSERVER_ID.getColumnName()));
- transaction.setVfModuleId(rowSet.getString(VF_MODULE_ID.getColumnName()));
- transaction.setServiceInstanceId(rowSet.getString(SERVICE_INSTANCE_ID.getColumnName()));
- transaction.setMode(Flags.Mode.valueOf(rowSet.getString(MODE.getColumnName())));
- inProgressRecords.add(transaction);
- }
- if (logger.isTraceEnabled()) {
- logger.trace("In progress transaction records fetched from database successfully.");
+ int count = 0;
+ if (rowSet != null) {
+ for (; rowSet.next(); ++count) {
+ transaction = new TransactionRecord();
+ transaction.setTransactionId(rowSet.getString(TRANSACTION_ID.getColumnName()));
+ transaction.setRequestId(rowSet.getString(REQUEST_ID.getColumnName()));
+ transaction.setSubRequestId(rowSet.getString(SUBREQUEST_ID.getColumnName()));
+ transaction.setOriginatorId(rowSet.getString(ORIGINATOR_ID.getColumnName()));
+ transaction.setStartTime(stringToDateConverterMillis(rowSet.getString(START_TIME.getColumnName())));
+ transaction.setTargetId(rowSet.getString(TARGET_ID.getColumnName()));
+ transaction.setTargetType(rowSet.getString(TARGET_TYPE.getColumnName()));
+ transaction.setOperation(VNFOperation.valueOf(rowSet.getString(OPERATION.getColumnName())));
+ transaction.setRequestState(RequestStatus.valueOf(rowSet.getString(STATE.getColumnName())));
+ transaction.setVnfcName(rowSet.getString(VNFC_NAME.getColumnName()));
+ transaction.setVserverId(rowSet.getString(VSERVER_ID.getColumnName()));
+ transaction.setVfModuleId(rowSet.getString(VF_MODULE_ID.getColumnName()));
+ transaction.setServiceInstanceId(rowSet.getString(SERVICE_INSTANCE_ID.getColumnName()));
+ transaction.setMode(Flags.Mode.valueOf(rowSet.getString(MODE.getColumnName())));
+ inProgressRecords.add(transaction);
+ }
}
+ logger.trace(String.valueOf(count)
+ + " in progress transaction records fetched from database successfully.");
return inProgressRecords;
} catch (ParseException e) {
logger.error("Error parsing start date during fetching in progress records ", e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
} catch (SQLException e) {
- logger.error("Error fetching in progress records for Transaction ID = " + appcInstanceId + "~" + record
- .getTransactionId(), e);
+ logger.error("Error fetching in progress records for Transaction ID = " + appcInstanceId + "~"
+ + record.getTransactionId(), e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
}
@@ -311,12 +304,12 @@ public class TransactionRecorderImpl implements TransactionRecorder {
@Override
public Boolean isTransactionDuplicate(TransactionRecord record) throws APPCException {
- StringBuilder duplicateRequestCheckQuery = new StringBuilder("SELECT " +
- TRANSACTION_ID.getColumnName() + " FROM " +
- TransactionConstants.TRANSACTIONS + WHERE +
- TRANSACTION_ID.getColumnName() + " <> ? AND " +
- REQUEST_ID.getColumnName() + " = ? AND " +
- STATE.getColumnName() + " IN(?,?) ");
+ StringBuilder duplicateRequestCheckQuery = new StringBuilder()
+ .append("SELECT ").append(TRANSACTION_ID.getColumnName()).append(" FROM ")
+ .append(TransactionConstants.TRANSACTIONS).append(WHERE)
+ .append(TRANSACTION_ID.getColumnName()).append(" <> ? AND ")
+ .append(REQUEST_ID.getColumnName()).append(" = ? AND ")
+ .append(STATE.getColumnName()).append(" IN(?,?) ");
ArrayList<String> duplicateCheckParams = new ArrayList<>();
duplicateCheckParams.add(appcInstanceId + "~" + record.getTransactionId());
@@ -339,35 +332,37 @@ public class TransactionRecorderImpl implements TransactionRecorder {
if (logger.isDebugEnabled()) {
logger.debug(duplicateRequestCheckQuery.toString());
}
- try (CachedRowSet rowSet = dbLibService.getData(duplicateRequestCheckQuery.toString(), duplicateCheckParams,
- SCHEMA)) {
- if (rowSet.first()) {
+ try (CachedRowSet rowSet =
+ dbLibService.getData(duplicateRequestCheckQuery.toString(), duplicateCheckParams, SCHEMA)) {
+ if (rowSet != null && rowSet.first()) {
String transactionId = rowSet.getString(TRANSACTION_ID.getColumnName());
if (logger.isErrorEnabled()) {
- logger.error("Duplicate request found. Transaction ID " + transactionId + " is currently in " +
- "progress.");
+ logger.error("Duplicate request found. Transaction ID " + transactionId
+ + " is currently in progress.");
}
return true;
}
return false;
} catch (SQLException e) {
- logger.error("Error checking duplicate records for Transaction ID = " + appcInstanceId + "~" + record
- .getTransactionId(), e);
+ logger.error("Error checking duplicate records for Transaction ID = " + appcInstanceId + "~"
+ + record.getTransactionId(), e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
}
@Override
public Integer getInProgressRequestsCount() throws APPCException {
- final String inProgressRequestCountQuery = "SELECT COUNT(*) as VALUE FROM "
- + TransactionConstants.TRANSACTIONS
- + WHERE + STATE.getColumnName() + " IN (?,?) ";
+ final String inProgressRequestCountQuery =
+ "SELECT COUNT(*) as VALUE FROM "
+ + TransactionConstants.TRANSACTIONS
+ + WHERE + STATE.getColumnName() + " IN (?,?) ";
ArrayList<String> checkInProgressParams = new ArrayList<>();
checkInProgressParams.add(RequestStatus.RECEIVED.name());
checkInProgressParams.add(RequestStatus.ACCEPTED.name());
- try(CachedRowSet rowSet=dbLibService.getData(inProgressRequestCountQuery,checkInProgressParams,SCHEMA)){
- if (rowSet.first()) {
+ try (CachedRowSet rowSet =
+ dbLibService.getData(inProgressRequestCountQuery, checkInProgressParams, SCHEMA)) {
+ if (rowSet != null && rowSet.first()) {
int count = rowSet.getInt("VALUE");
logger.info("In progress request count fetched from database successfully.");
return count;
@@ -391,44 +386,51 @@ public class TransactionRecorderImpl implements TransactionRecorder {
public List<RequestStatus> getRecords(String requestId, String subrequestId, String originatorId, String vnfId)
throws APPCException {
StringBuilder queryString = (new StringBuilder(1024))
- .append("SELECT " + TRANSACTION_ATTRIBUTES.STATE.getColumnName())
- .append(" FROM " + TRANSACTIONS)
- .append(" WHERE " + TRANSACTION_ATTRIBUTES.REQUEST_ID.getColumnName() + " = ? AND " +
- TRANSACTION_ATTRIBUTES.TARGET_ID.getColumnName() + " = ?");
-
+ .append("SELECT ").append(TRANSACTION_ID.getColumnName())
+ .append(",")
+ .append(STATE.getColumnName())
+ .append(" FROM ").append(TRANSACTIONS)
+ .append(" WHERE ").append(TRANSACTION_ATTRIBUTES.REQUEST_ID.getColumnName()).append(" = ? AND ")
+ .append(TRANSACTION_ATTRIBUTES.TARGET_ID.getColumnName()).append(" = ?");
ArrayList<String> argList = new ArrayList<>();
argList.add(requestId);
argList.add(vnfId);
if (subrequestId != null) {
- queryString.append(" AND " + TRANSACTION_ATTRIBUTES.SUBREQUEST_ID.getColumnName() + " = ?");
+ queryString.append(" AND ").append(TRANSACTION_ATTRIBUTES.SUBREQUEST_ID.getColumnName()).append(" = ?");
argList.add(subrequestId);
}
if (originatorId != null) {
- queryString.append(" AND " + TRANSACTION_ATTRIBUTES.ORIGINATOR_ID.getColumnName() + " = ?");
+ queryString.append(" AND ").append(TRANSACTION_ATTRIBUTES.ORIGINATOR_ID.getColumnName()).append(" = ?");
argList.add(originatorId);
}
List<RequestStatus> requestStatusList = new ArrayList<>();
- try {
- CachedRowSet resultSet = dbLibService.getData(queryString.toString(), argList, SCHEMA);
- while (resultSet.next()) {
- String name = resultSet.getString(TRANSACTION_ATTRIBUTES.STATE.getColumnName());
- RequestStatus requestStatus = null;
- try {
- requestStatus = RequestStatus.valueOf(name);
- } catch (IllegalArgumentException e) {
- logger.error(String.format("Invalid request status (%s) using (%s) :", name, RequestStatus
- .UNKNOWN), e);
- requestStatus = RequestStatus.UNKNOWN;
+ try (CachedRowSet resultSet = dbLibService.getData(queryString.toString(), argList, SCHEMA)) {
+ if (resultSet == null) {
+ logger.error(String.format(
+ "No results returned when retrieving record for requestID %s and vnfId %s %s",
+ requestId, vnfId, "from the transactions table"));
+ } else {
+ while (resultSet.next()) {
+ String name = resultSet.getString(TRANSACTION_ATTRIBUTES.STATE.getColumnName());
+ RequestStatus requestStatus = null;
+ try {
+ requestStatus = RequestStatus.valueOf(name);
+ } catch (IllegalArgumentException e) {
+ logger.error(String.format(
+ "Invalid request status (%s) using (%s):", name, RequestStatus.UNKNOWN), e);
+ requestStatus = RequestStatus.UNKNOWN;
+ }
+ requestStatusList.add(requestStatus);
+ logger.debug(String.format("Request Status obtained (%s).", requestStatus));
}
- requestStatusList.add(requestStatus);
- logger.debug(String.format("Request Status obtained (%s).", requestStatus));
}
} catch (SQLException e) {
logger.error("Error Accessing Database ", e);
- throw new APPCException(String.format("Error retrieving record for requestID %s and vnfId %s " +
- "from the transactions table", requestId, vnfId), e);
+ throw new APPCException(String.format(
+ "Error retrieving record for requestID %s and vnfId %s from the transactions table",
+ requestId, vnfId), e);
}
return requestStatusList;
diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java
index 36cf26bb7..394aa97a1 100644
--- a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java
+++ b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java
@@ -19,31 +19,12 @@
* 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.onap.appc.transactionrecorder.impl;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
-import static org.hamcrest.CoreMatchers.isA;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.text.ParseException;
-import java.time.Instant;
-import java.time.ZoneOffset;
-import java.time.format.DateTimeFormatter;
-import java.time.temporal.ChronoUnit;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import javax.sql.rowset.CachedRowSet;
+import com.sun.rowset.CachedRowSetImpl;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -51,6 +32,11 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
+
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.hamcrest.CoreMatchers.isA;
+
import org.onap.appc.dao.util.dbcp.DBConnectionPool;
import org.onap.appc.dao.util.helper.DBHelper;
import org.onap.appc.domainmodel.lcm.Flags;
@@ -61,7 +47,22 @@ import org.onap.appc.exceptions.APPCException;
import org.onap.appc.transactionrecorder.objects.TransactionConstants;
import org.onap.appc.transactionrecorder.objects.TransactionConstants.TRANSACTION_ATTRIBUTES;
import org.onap.ccsdk.sli.core.dblib.DbLibService;
-import com.sun.rowset.CachedRowSetImpl;
+
+import javax.sql.rowset.CachedRowSet;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
/**
* Test class for TransactionRecorder
@@ -86,26 +87,27 @@ public class TransactionRecorderImplTest {
* <p>
* Please ensure this table create script is identical to the source script used in a deployment.
*/
- private String TRANSACTION_CREATE_TABLE = "CREATE TABLE TRANSACTIONS (" +
- " TRANSACTION_ID VARCHAR(75) NOT NULL PRIMARY KEY," +
- " ORIGIN_TIMESTAMP DATETIME(3) NOT NULL," +
- " REQUEST_ID VARCHAR(256) NOT NULL," +
- " SUBREQUEST_ID VARCHAR(256) DEFAULT NULL," +
- " ORIGINATOR_ID VARCHAR(256) DEFAULT NULL," +
- " START_TIME DATETIME(3) NOT NULL," +
- " END_TIME DATETIME(3) DEFAULT NULL," +
- " TARGET_ID VARCHAR(256) NOT NULL," +
- " TARGET_TYPE VARCHAR(256) DEFAULT NULL," +
- " OPERATION VARCHAR(256) NOT NULL," +
- " RESULT_CODE INT(11) DEFAULT NULL," +
- " DESCRIPTION TEXT," +
- " STATE VARCHAR(50) NOT NULL," +
- " SERVICE_INSTANCE_ID VARCHAR(256) DEFAULT NULL," +
- " VNFC_NAME VARCHAR(256) DEFAULT NULL," +
- " VSERVER_ID VARCHAR(256) DEFAULT NULL," +
- " VF_MODULE_ID VARCHAR(256) DEFAULT NULL," +
- " MODE VARCHAR(50) NOT NULL," +
- ")";
+ private String TRANSACTION_CREATE_TABLE =
+ "CREATE TABLE TRANSACTIONS ("
+ + " TRANSACTION_ID VARCHAR(75) NOT NULL PRIMARY KEY,"
+ + " ORIGIN_TIMESTAMP DATETIME(3) NOT NULL,"
+ + " REQUEST_ID VARCHAR(256) NOT NULL,"
+ + " SUBREQUEST_ID VARCHAR(256) DEFAULT NULL,"
+ + " ORIGINATOR_ID VARCHAR(256) DEFAULT NULL,"
+ + " START_TIME DATETIME(3) NOT NULL,"
+ + " END_TIME DATETIME(3) DEFAULT NULL,"
+ + " TARGET_ID VARCHAR(256) NOT NULL,"
+ + " TARGET_TYPE VARCHAR(256) DEFAULT NULL,"
+ + " OPERATION VARCHAR(256) NOT NULL,"
+ + " RESULT_CODE INT(11) DEFAULT NULL,"
+ + " DESCRIPTION TEXT,"
+ + " STATE VARCHAR(50) NOT NULL,"
+ + " SERVICE_INSTANCE_ID VARCHAR(256) DEFAULT NULL,"
+ + " VNFC_NAME VARCHAR(256) DEFAULT NULL,"
+ + " VSERVER_ID VARCHAR(256) DEFAULT NULL,"
+ + " VF_MODULE_ID VARCHAR(256) DEFAULT NULL,"
+ + " MODE VARCHAR(50) NOT NULL,"
+ + ")";
private String TRANSACTION_DROP_TABLE = "DROP TABLE IF EXISTS TRANSACTIONS";
@Rule
@@ -151,8 +153,8 @@ public class TransactionRecorderImplTest {
public void testStore() throws Exception {
TransactionRecord input = prepareTransactionsInput();
- Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- testStoreInMemory(invocation.getArguments()));
+ Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> testStoreInMemory(invocation.getArguments()));
transactionRecorderImpl.store(input);
}
@@ -175,8 +177,8 @@ public class TransactionRecorderImplTest {
insertRecord(record1);
TransactionRecord input = prepareTransactionsInput();
input.setStartTime(Instant.now());
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- inMemoryExecutionWithResultSet(invocation.getArguments()));
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments()));
Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input, 0).size());
}
@@ -197,22 +199,22 @@ public class TransactionRecorderImplTest {
@Test
public void testGetInProgressRequestsWithinTimeInterval() throws SQLException, APPCException {
TransactionRecord record1 = prepareTransactionsInput();
- record1.setStartTime(Instant.now().minus(4,ChronoUnit.HOURS));
+ record1.setStartTime(Instant.now().minus(4, ChronoUnit.HOURS));
insertRecord(record1);
TransactionRecord input = prepareTransactionsInput();
input.setStartTime(Instant.now());
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- inMemoryExecutionWithResultSet(invocation.getArguments()));
- List<TransactionRecord> aList= transactionRecorderImpl.getInProgressRequests(input,12);
- Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input,12).size());
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments()));
+ List<TransactionRecord> aList = transactionRecorderImpl.getInProgressRequests(input, 12);
+ Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input, 12).size());
}
@Test
public void testIsTransactionDuplicate() throws SQLException, APPCException {
TransactionRecord input = prepareTransactionsInput();
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- inMemoryExecutionWithResultSet(invocation.getArguments()));
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments()));
Assert.assertFalse(transactionRecorderImpl.isTransactionDuplicate(input));
}
@@ -274,10 +276,10 @@ public class TransactionRecorderImplTest {
insertRecord(input);
Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns = new HashMap<>();
updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.TARGET_TYPE, "Firewall");
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- returnResult(invocation.getArguments()));
- Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- testUpdateInMemory(invocation.getArguments()));
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> returnResult(invocation.getArguments()));
+ Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> testUpdateInMemory(invocation.getArguments()));
transactionRecorderImpl.update(input.getTransactionId(), input.getRequestId(), updateColumns);
Mockito.verify(dbLibService).getData(anyString(), anyObject(), anyString());
Mockito.verify(dbLibService).writeData(anyString(), anyObject(), anyString());
@@ -301,11 +303,10 @@ public class TransactionRecorderImplTest {
TransactionRecord input = prepareTransactionsInput();
Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns = new HashMap<>();
updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.TARGET_TYPE, "Firewall");
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- returnPositiveResult(invocation.getArguments()));
- Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- testUpdateInMemory(invocation.getArguments()));
-
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> returnPositiveResult(invocation.getArguments()));
+ Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> testUpdateInMemory(invocation.getArguments()));
transactionRecorderImpl.update(input.getTransactionId(), input.getRequestId(), updateColumns);
Mockito.verify(dbLibService).getData(anyString(), anyObject(), anyString());
Mockito.verify(dbLibService).writeData(anyString(), anyObject(), anyString());
@@ -319,9 +320,9 @@ public class TransactionRecorderImplTest {
insertNullInstanceData(args.get(0));
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps_second = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps_second = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps_second.setString(i, args.get(i - 1));
}
@@ -332,12 +333,13 @@ public class TransactionRecorderImplTest {
}
private void insertNullInstanceData(String transactionId) throws Exception {
- final String nullInstanceQuery = (TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS +
- " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
+ final String nullInstanceQuery =
+ TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS
+ + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(nullInstanceQuery)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(nullInstanceQuery)
+ ) {
ArrayList<String> input = new ArrayList<String>();
input.add(transactionId);
input.add(dateToStringConverterMillis(Instant.parse("2017-09-12T00:00:01.00Z")));
@@ -374,9 +376,9 @@ public class TransactionRecorderImplTest {
ArrayList<String> args = (ArrayList<String>) obj[1];
System.out.println("Query: " + query + "\nArgs: " + args);
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
@@ -430,9 +432,9 @@ public class TransactionRecorderImplTest {
ArrayList<String> args = (ArrayList<String>) obj[1];
// System.out.println("Query: " + query + "\nArgs: " + args);
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
@@ -446,9 +448,9 @@ public class TransactionRecorderImplTest {
String query = (String) obj[0];
ArrayList<String> args = (ArrayList<String>) obj[1];
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
@@ -460,13 +462,13 @@ public class TransactionRecorderImplTest {
private boolean isTransactionAborted() throws Exception {
String query = "SELECT COUNT(*) FROM TRANSACTIONS WHERE STATE = ?";
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
ps.setString(1, RequestStatus.ABORTED.toString());
try (
- ResultSet rs = ps.executeQuery()
- ) {
+ ResultSet rs = ps.executeQuery()
+ ) {
while (rs.next()) {
int value = rs.getInt(1);
if (value == 1) {
@@ -483,9 +485,9 @@ public class TransactionRecorderImplTest {
String query = (String) obj[0];
ArrayList<String> args = (ArrayList<String>) obj[1];
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
System.out.println("Value at " + i + ": " + args.get(i - 1));
ps.setString(i, args.get(i - 1));
@@ -504,9 +506,9 @@ public class TransactionRecorderImplTest {
String query = (String) obj[0];
ArrayList<String> args = (ArrayList<String>) obj[1];
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
@@ -538,12 +540,13 @@ public class TransactionRecorderImplTest {
}
private void insertRecord(TransactionRecord input) throws SQLException {
- final String STORE_DATE_QUERY = TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS +
- " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ final String STORE_DATE_QUERY =
+ TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS
+ + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(STORE_DATE_QUERY)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(STORE_DATE_QUERY)
+ ) {
ArrayList<String> args = prepareArguments(input);
args.remove(0);
args.add(0, "123~" + input.getTransactionId());
@@ -615,21 +618,22 @@ public class TransactionRecorderImplTest {
private String checkIfValueIsUpdated(String key) throws Exception {
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement("SELECT TARGET_TYPE,TRANSACTION_ID FROM TRANSACTIONS" +
- " WHERE TRANSACTION_ID = ?")
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(
+ "SELECT TARGET_TYPE, TRANSACTION_ID FROM TRANSACTIONS"
+ + " WHERE TRANSACTION_ID = ?")
+ ) {
ps.setString(1, key);
try (
- ResultSet rs = ps.executeQuery()
- ) {
- while (rs.next()) {
- String value = rs.getString("TARGET_TYPE");
- String transactionId = rs.getString("TRANSACTION_ID");
- System.out.println("Updated data: TRANSACTION_ID: " + transactionId + " TARGET_TYPE: " + value);
- return value;
- }
- throw new Exception("Value not found");
+ ResultSet rs = ps.executeQuery()
+ ) {
+ while (rs.next()) {
+ String value = rs.getString("TARGET_TYPE");
+ String transactionId = rs.getString("TRANSACTION_ID");
+ System.out.println("Updated data: TRANSACTION_ID: " + transactionId + " TARGET_TYPE: " + value);
+ return value;
+ }
+ throw new Exception("Value not found");
}
}
}
diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/LicenseManagerImplTest.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/LicenseManagerImplTest.java
index 9d2fb87b4..ad924ca0a 100644
--- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/LicenseManagerImplTest.java
+++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/LicenseManagerImplTest.java
@@ -4,6 +4,8 @@
* ================================================================================
* Modifications Copyright (C) 2018 Nokia
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* 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
@@ -61,15 +63,15 @@ public class LicenseManagerImplTest {
public void retrieveLicenseModel_shouldThrowException_whenRetrieveLicenseModelDataIsEmpty() {
// GIVEN
- String expectedMessage = String
- .format("License model not found for vnfType='%s' and vnfVersion='%s'", VNF_TYPE, VNF_VERSION);
+ String expectedMessage =
+ String.format("License model not found for vnfType='%s' and vnfVersion='%s'", VNF_TYPE, VNF_VERSION);
given(licenseDataAccessService.retrieveLicenseModelData(VNF_TYPE, VNF_VERSION))
- .willReturn(Collections.emptyMap());
+ .willReturn(Collections.emptyMap());
// WHEN THEN
assertThatExceptionOfType(DataAccessException.class)
- .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION))
- .withMessage(expectedMessage);
+ .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION))
+ .withMessage(expectedMessage);
}
@Test
@@ -81,11 +83,11 @@ public class LicenseManagerImplTest {
Map<String, String> licenseModelData = new HashMap<>();
licenseModelData.put(ARTIFACT_CONTENT.name(), malformedXml);
given(licenseDataAccessService.retrieveLicenseModelData(VNF_TYPE, VNF_VERSION))
- .willReturn(licenseModelData);
+ .willReturn(licenseModelData);
// WHEN THEN
assertThatExceptionOfType(DataAccessException.class)
- .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION));
+ .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION));
}
@Test
@@ -102,7 +104,7 @@ public class LicenseManagerImplTest {
Map<String, String> licenseModelData = new HashMap<>();
licenseModelData.put(ARTIFACT_CONTENT.name(), correctlyFormedXml);
given(licenseDataAccessService.retrieveLicenseModelData(VNF_TYPE, VNF_VERSION))
- .willReturn(licenseModelData);
+ .willReturn(licenseModelData);
// WHEN
LicenseModel licenseModel = licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION);
@@ -111,4 +113,4 @@ public class LicenseManagerImplTest {
assertEquals(expectedEntitlementPool, licenseModel.getEntitlementPoolUuid());
assertEquals(expectedKeyGroup, licenseModel.getLicenseKeyGroupUuid());
}
-} \ No newline at end of file
+}
diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/XmlToLicenseModelConverterTest.java b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/XmlToLicenseModelConverterTest.java
index d0c48cc93..2dd3fde51 100644
--- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/XmlToLicenseModelConverterTest.java
+++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/onap/appc/licmgr/impl/XmlToLicenseModelConverterTest.java
@@ -4,6 +4,8 @@
* ================================================================================
* Copyright (C) 2018 Nokia
* =============================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* 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
@@ -57,7 +59,7 @@ public class XmlToLicenseModelConverterTest {
// WHEN
converter.convert((a, b) -> {
- }, anyString(), null);
+ }, anyString(), null);
// THEN
then(xmlStreamReader).should().close();
@@ -72,9 +74,9 @@ public class XmlToLicenseModelConverterTest {
// WHEN THEN
assertThatExceptionOfType(XMLStreamException.class)
- .isThrownBy(() -> converter.convert((a, b) -> {
- throw new XMLStreamException();
- }, anyString(), null));
+ .isThrownBy(() -> converter.convert((a, b) -> {
+ throw new XMLStreamException();
+ }, anyString(), null));
then(xmlStreamReader).should().close();
}
-} \ No newline at end of file
+}
diff --git a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/resources/test-vf-license-model.xml b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/resources/test-vf-license-model.xml
index 6f32f50b8..9f0b2b6ed 100644
--- a/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/resources/test-vf-license-model.xml
+++ b/appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/resources/test-vf-license-model.xml
@@ -60,4 +60,4 @@
</license-key-group-list>
</feature-group>
</feature-group-list>
-</vf-license-model> \ No newline at end of file
+</vf-license-model>
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java
index 65f51552a..ba56da044 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java
@@ -11,15 +11,14 @@
* 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=========================================================
*/
@@ -38,7 +37,7 @@ import org.onap.appc.srvcomm.messaging.MessagingConnector;
public class MessageAdapterImpl implements MessageAdapter{
private MessagingConnector messageService;
- private String partition ;
+ private String partition;
private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapterImpl.class);
@@ -46,23 +45,25 @@ public class MessageAdapterImpl implements MessageAdapter{
* Initialize producer client to post messages using configuration properties
*/
@Override
- public void init(){
- logger.debug("MessageAdapterImpl - init");
+ public void init() {
+ logger.debug("MessageAdapterImpl - init");
this.messageService = new MessagingConnector();
}
-
+
public void init(MessagingConnector connector) {
logger.debug("MessageAdapterImpl - init");
this.messageService = connector;
}
/**
- * Posts message to DMaaP. As DMaaP accepts only json messages this method first convert dmaapMessage to json format and post it to DMaaP.
- * @param asyncResponse response data that based on it a message will be send to DMaaP (the format of the message that will be sent to DMaaP based on the action and its YANG domainmodel).
- * @return True if message is postes successfully else False
+ * Posts message to DMaaP. As DMaaP accepts only json messages this method first converts dmaapMessage
+ * to json format and posts it to DMaaP.
+ * @param asyncResponse response data on which to base a message that will be sent to DMaaP
+ * (the format of the message that will be sent to DMaaP is based on the action and its YANG domainmodel).
+ * @return True if message is posted successfully, else False
*/
@Override
- public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse){
+ public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse) {
boolean success;
if (logger.isTraceEnabled()) {
logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(asyncResponse));
@@ -70,18 +71,19 @@ public class MessageAdapterImpl implements MessageAdapter{
logger.debug("Entered MessageAdapterImpl.post()");
String jsonMessage;
try {
- logger.debug("Before converting Async Response");
- jsonMessage = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse);
+ logger.debug("Before converting Async Response");
+ jsonMessage =
+ Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse);
if (logger.isDebugEnabled()) {
logger.debug("DMaaP Response = " + jsonMessage);
}
- logger.debug("Before Invoking producer.post(): jsonMessage is::" + jsonMessage);
+ logger.debug("Before Invoking messageService.publishMessage(): jsonMessage is::" + jsonMessage);
success = messageService.publishMessage("appc.LCM", this.partition, jsonMessage);
- logger.debug("After Invoking producer.post()");
+ logger.debug("After Invoking messageService.publishMessage()");
} catch (JsonProcessingException e1) {
logger.error("Error generating Json from DMaaP message " + e1.getMessage());
success = false;
- }catch (Exception e){
+ } catch (Exception e) {
logger.error("Error sending message to DMaaP " + e.getMessage());
success = false;
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java
index 6d62c107b..3a02e4d85 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,14 @@
* 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=========================================================
*/
@@ -67,7 +66,8 @@ public class Converter {
isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
- public static Builder<?> convAsyncResponseToBuilder(VNFOperation vnfOperation, String rpcName, ResponseContext response) {
+ public static Builder<?> convAsyncResponseToBuilder(
+ VNFOperation vnfOperation, String rpcName, ResponseContext response) {
Builder<?> outObj = null;
if (response == null) {
throw new IllegalArgumentException("empty asyncResponse");
@@ -76,7 +76,8 @@ public class Converter {
throw new IllegalArgumentException("empty asyncResponse.action");
}
logger.debug("Entered Converter.convAsyncResponseToBuilder(): Operation Name " + vnfOperation.name());
- org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action action = org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action.valueOf(vnfOperation.name());
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action action =
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action.valueOf(vnfOperation.name());
logger.debug("After resolving action");
CommonHeader commonHeader = convAsyncResponseTorev160108CommonHeader(response);
Status status = convAsyncResponseTorev160108Status(response);
@@ -94,9 +95,9 @@ public class Converter {
((SnapshotOutputBuilder)outObj).setStatus(status);
try {
((SnapshotOutputBuilder) outObj)
- .setSnapshotId(response.getAdditionalContext().get("output.snapshot-id"));
+ .setSnapshotId(response.getAdditionalContext().get("output.snapshot-id"));
} catch (NullPointerException ignored) {
- // in case of negative response, snapshotID does not populated, so just ignore NPL
+ // in case of negative response, snapshotID is not populated, so just ignore NPL
}
return outObj;
case Audit:
@@ -282,7 +283,7 @@ public class Converter {
outObj = new AttachVolumeOutputBuilder();
((AttachVolumeOutputBuilder)outObj).setCommonHeader(commonHeader);
((AttachVolumeOutputBuilder)outObj).setStatus(status);
- return outObj;
+ return outObj;
case DetachVolume:
outObj = new DetachVolumeOutputBuilder();
((DetachVolumeOutputBuilder)outObj).setCommonHeader(commonHeader);
@@ -295,14 +296,14 @@ public class Converter {
return outObj;
case DistributeTrafficCheck:
outObj = new DistributeTrafficCheckOutputBuilder();
- ((DistributeTrafficCheckOutputBuilder) outObj).setCommonHeader(commonHeader);
+ ((DistributeTrafficCheckOutputBuilder)outObj).setCommonHeader(commonHeader);
((DistributeTrafficCheckOutputBuilder)outObj).setStatus(status);
return outObj;
case PreConfigure:
outObj = new PreConfigureOutputBuilder();
((PreConfigureOutputBuilder)outObj).setCommonHeader(commonHeader);
((PreConfigureOutputBuilder)outObj).setStatus(status);
- ((PreConfigureOutputBuilder)outObj).setPayload(payload);
+ ((PreConfigureOutputBuilder)outObj).setPayload(payload);
return outObj;
case GetConfig:
outObj = new GetConfigOutputBuilder();
@@ -371,7 +372,7 @@ public class Converter {
((StopTrafficOutputBuilder)outObj).setPayload(payload);
return outObj;
case LicenseManagement:
- outObj = new LicenseManagementOutputBuilder();
+ outObj = new LicenseManagementOutputBuilder();
((LicenseManagementOutputBuilder)outObj).setCommonHeader(commonHeader);
((LicenseManagementOutputBuilder)outObj).setStatus(status);
((LicenseManagementOutputBuilder)outObj).setPayload(payload);
@@ -381,8 +382,8 @@ public class Converter {
}
}
- public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) {
- logger.debug("Entering convAsyncResponseTorev160108Payload");
+ public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) {
+ logger.debug("Entering convAsyncResponseTorev160108Payload");
Payload payload = null;
if (inObj.getPayload() != null) {
payload = new Payload(inObj.getPayload());
@@ -395,23 +396,23 @@ public class Converter {
String payloadAsString = null;
if (inObj != null) {
- if (inObj instanceof String) {
- payloadAsString = (String)inObj;
- } else {
- try {
- ObjectMapper objectMapper = new ObjectMapper();
- payloadAsString = objectMapper.writeValueAsString(inObj);
- } catch (JsonProcessingException e) {
- String errMsg = "Error serialize payload json to string";
- throw new ParseException(errMsg + "-" + e.toString(), 0);
- }
+ if (inObj instanceof String) {
+ payloadAsString = (String)inObj;
+ } else {
+ try {
+ ObjectMapper objectMapper = new ObjectMapper();
+ payloadAsString = objectMapper.writeValueAsString(inObj);
+ } catch (JsonProcessingException e) {
+ String errMsg = "Error serialize payload json to string";
+ throw new ParseException(errMsg + "-" + e.toString(), 0);
}
+ }
}
return payloadAsString;
}
public static Status convAsyncResponseTorev160108Status(ResponseContext inObj) {
- logger.debug("Entering convAsyncResponseTorev160108Status");
+ logger.debug("Entering convAsyncResponseTorev160108Status");
StatusBuilder statusBuilder = new StatusBuilder();
statusBuilder.setCode(inObj.getStatus().getCode());
statusBuilder.setMessage(inObj.getStatus().getMessage());
@@ -420,7 +421,7 @@ public class Converter {
}
public static CommonHeader convAsyncResponseTorev160108CommonHeader(ResponseContext inObj) {
- logger.debug("Entered into convAsyncResponseTorev160108CommonHeader");
+ logger.debug("Entered into convAsyncResponseTorev160108CommonHeader");
CommonHeader outObj = null;
if (inObj == null) {
throw new IllegalArgumentException("empty asyncResponse");
@@ -452,7 +453,7 @@ public class Converter {
commonHeaderBuilder.setTimestamp(zuluTimestamp);
}
outObj = commonHeaderBuilder.build();
- logger.debug("Exiting from convAsyncResponseTorev160108CommonHeader: Returning outObj::"+ outObj.toString());
+ logger.debug("Exiting from convAsyncResponseTorev160108CommonHeader: Returning outObj: " + outObj.toString());
return outObj;
}
@@ -462,31 +463,34 @@ public class Converter {
}
public static org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags
- convFlagsMapTorev160108Flags(org.onap.appc.domainmodel.lcm.Flags flags) {
+ convFlagsMapTorev160108Flags(org.onap.appc.domainmodel.lcm.Flags flags) {
Flags rev160108flags;
boolean anyFlag = false;
FlagsBuilder flagsBuilder = new FlagsBuilder();
/*
- * TODO: The below flags are related to APP-C request and should not be sent back - uncomment when response flags are introduced.
+ * TODO: The below flags are related to APP-C request and should not be sent back -
+ * uncomment when response flags are introduced.
*/
/*
- if(flags.containsKey(FORCE_FLAG)){
+ if (flags.containsKey(FORCE_FLAG)) {
org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force force =
- org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force.valueOf(flags.get(FORCE_FLAG).toString());
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header
+ .Flags.Force.valueOf(flags.get(FORCE_FLAG).toString());
flagsBuilder.setForce(force);
anyFlag = true;
}
- if(flags.containsKey(MODE_FLAG)){
+ if (flags.containsKey(MODE_FLAG)) {
org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode mode =
- org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode.valueOf(flags.get(MODE_FLAG).toString());
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header
+ .Flags.Mode.valueOf(flags.get(MODE_FLAG).toString());
flagsBuilder.setMode(mode);
anyFlag = true;
}
- if(flags.containsKey(TTL_FLAG)){
+ if (flags.containsKey(TTL_FLAG)) {
flagsBuilder.setTtl(Integer.valueOf(flags.get(TTL_FLAG).toString()));
anyFlag = true;
}
- if(anyFlag){
+ if (anyFlag) {
rev160108flags = flagsBuilder.build();
}
*/
@@ -508,7 +512,7 @@ public class Converter {
objectMapper.addMixIn(Payload.class, MixIn.class);
objectMapper.addMixIn(ZULU.class, MixIn.class);
-// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
+// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true)
ObjectWriter writer = objectMapper
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
@@ -522,8 +526,8 @@ public class Converter {
VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse)
throws JsonProcessingException {
logger.debug("Entered Converter.convAsyncResponseToDmaapOutgoingMessageJsonString()");
- DmaapOutgoingMessage dmaapOutgoingMessage =
- convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse);
+ DmaapOutgoingMessage dmaapOutgoingMessage =
+ convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(dmaapOutgoingMessage.getBody().getOutput().getClass(), MixInFlagsMessage.class);
objectMapper.addMixIn(CommonHeader.class, MixInCommonHeader.class);
@@ -532,7 +536,7 @@ public class Converter {
objectMapper.addMixIn(Payload.class, MixIn.class);
objectMapper.addMixIn(ZULU.class, MixIn.class);
-// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
+// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true)
ObjectWriter writer = objectMapper
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
@@ -542,10 +546,10 @@ public class Converter {
}
public static DmaapOutgoingMessage convAsyncResponseToDmaapOutgoingMessage(
- VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse)
+ VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse)
throws JsonProcessingException {
- logger.debug("Entered Converter.convAsyncResponseToDmaapOutgoingMessage()");
- DmaapOutgoingMessage outObj = new DmaapOutgoingMessage();
+ logger.debug("Entered Converter.convAsyncResponseToDmaapOutgoingMessage()");
+ DmaapOutgoingMessage outObj = new DmaapOutgoingMessage();
String correlationID = getCorrelationID(asyncResponse);
outObj.setCorrelationID(correlationID);
outObj.setType("response");
@@ -556,7 +560,7 @@ public class Converter {
Object messageBody = builder.build();
DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody);
outObj.setBody(body);
- logger.debug("Exiting Converter.convAsyncResponseToDmaapOutgoingMessage(): messageBody is:" + body.toString());
+ logger.debug("Exiting Converter.convAsyncResponseToDmaapOutgoingMessage(): messageBody is: " + body.toString());
return outObj;
}
@@ -586,6 +590,6 @@ public class Converter {
}
abstract class MixInFlagsMessage extends MixIn {
@JsonProperty("common-header")
- abstract CommonHeader getCommonHeader();
+ abstract CommonHeader getCommonHeader();
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java
index aa9b42a5a..94a86e841 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java
@@ -17,7 +17,6 @@
* 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=========================================================
*/
@@ -73,8 +72,9 @@ import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-import java.util.UUID;
import java.util.TimeZone;
+import java.util.UUID;
+
import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
@@ -133,8 +133,8 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
* 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database
* If any of the validation fails, it returns appropriate response *
*
- * @param input RequestHandlerInput object which contains request header and other request parameters like
- * command , target Id , payload etc.
+ * @param input RequestHandlerInput object which contains request header and other request parameters like
+ * command, target Id, payload etc.
* @return response for request as enum with Return code and message.
*/
@Override
@@ -163,17 +163,17 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
storeErrorMessageToLog(runtimeContext, e.getTargetEntity(), e.getTargetService(), e.getLogMessage());
output = buildRequestHandlerOutput(e.getLcmCommandStatus(), e.getParams());
} catch (InvalidInputException e) {
- logger.error("InvalidInputException : " + e.getMessage(), e);
+ logger.error("InvalidInputException: " + e.getMessage(), e);
errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
- output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, new Params().addParam
- ("errorMsg", errorMessage));
+ output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER,
+ new Params().addParam("errorMsg", errorMessage));
} catch (LockException e) {
- logger.error("LockException : " + e.getMessage(), e);
+ logger.error("LockException: " + e.getMessage(), e);
Params params = new Params().addParam("errorMsg", e.getMessage());
fillStatus(runtimeContext, LCMCommandStatus.LOCKED_VNF_ID, params);
output = buildRequestHandlerOutput(LCMCommandStatus.LOCKED_VNF_ID, params);
} catch (Exception e) {
- logger.error("Exception : " + e.getMessage(), e);
+ logger.error("Exception: " + e.getMessage(), e);
storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage());
errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
Params params = new Params().addParam("errorMsg", errorMessage);
@@ -187,15 +187,17 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
if (isMetricEnabled)
((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
} else {
- requestStatus = (statusCode == LCMCommandStatus.EXPIRED_REQUEST.getResponseCode()) ? RequestStatus
- .TIMEOUT : RequestStatus.REJECTED;
+ requestStatus = (statusCode == LCMCommandStatus.EXPIRED_REQUEST.getResponseCode()) ?
+ RequestStatus.TIMEOUT : RequestStatus.REJECTED;
if (isMetricEnabled)
((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest();
}
try {
- if (errorMessage != null && logger.isDebugEnabled())
- logger.debug("error occurred in handleRequest " + errorMessage);
- logger.debug("output.getResponseContext().getStatus().getCode(): " + statusCode);
+ if (logger.isDebugEnabled()) {
+ if (errorMessage != null)
+ logger.debug("error occurred in handleRequest: " + errorMessage);
+ logger.debug("output.getResponseContext().getStatus().getCode(): " + statusCode);
+ }
runtimeContext.setResponseContext(output.getResponseContext());
} finally {
runtimeContext.getTransactionRecord().setRequestState(requestStatus);
@@ -205,8 +207,8 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
}
}
if (logger.isTraceEnabled()) {
- logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " +
- ObjectUtils.toString(output.getResponseContext()) + ")");
+ logger.trace("Exiting from handleRequest with (RequestHandlerOutput = "
+ + ObjectUtils.toString(output.getResponseContext()) + ")");
}
return output;
}
@@ -286,12 +288,12 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
String additionalMessage) {
LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ?
String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "",
- runtimeContext.getResponseContext().getStatus() != null ?
+ runtimeContext.getResponseContext().getStatus() != null ?
String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "",
- targetEntity,
- targetServiceName,
- additionalMessage,
- this.getClass().getCanonicalName());
+ targetEntity,
+ targetServiceName,
+ additionalMessage,
+ this.getClass().getCanonicalName());
}
protected abstract void handleRequest(RuntimeContext runtimeContext);
@@ -329,7 +331,7 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name());
MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId());
} catch (UnknownHostException e) {
- logger.error("Error occured while setting initial log properties", e);
+ logger.error("Error occurred while setting initial log properties", e);
}
}
@@ -345,24 +347,24 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
}
/**
- * This method perform following operations required after execution of workflow.
+ * This method performs following operations required after execution of workflow.
* It posts asynchronous response to message bus (DMaaP).
- * Unlock VNF Id
+ * Unlocks VNF Id.
* Removes request from request registry.
- * Generate audit logs.
+ * Generates audit logs.
* Adds transaction record to database id if transaction logging is enabled.
*/
@Override
public void onRequestExecutionEnd(RuntimeContext runtimeContext) {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " +
- ObjectUtils.toString(runtimeContext));
+ logger.trace("Entering to onRequestExecutionEnd with runtimeContext = "
+ + ObjectUtils.toString(runtimeContext));
}
postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(),
- runtimeContext.getResponseContext());
+ runtimeContext.getResponseContext());
final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
RequestStatus requestStatus =
- (statusCode == LCMCommandStatus.SUCCESS.getResponseCode()) ?
+ (statusCode == LCMCommandStatus.SUCCESS.getResponseCode()) ?
RequestStatus.SUCCESSFUL : RequestStatus.FAILED;
runtimeContext.getTransactionRecord().setRequestState(requestStatus);
runtimeContext.getTransactionRecord().setResultCode(runtimeContext.getResponseContext().getStatus().getCode());
@@ -372,28 +374,28 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
private void storeAuditLogRecord(RuntimeContext runtimeContext) {
LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(),
- Instant.now(),
- String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
- runtimeContext.getResponseContext().getStatus().getMessage(),
- this.getClass().getCanonicalName());
+ Instant.now(),
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+ runtimeContext.getResponseContext().getStatus().getMessage(),
+ this.getClass().getCanonicalName());
}
private void storeMetricLogRecord(RuntimeContext runtimeContext) {
LoggingUtils.logMetricsMessage(runtimeContext.getTimeStart(),
- Instant.now(),
- LoggingConstants.TargetNames.APPC,
- runtimeContext.getRequestContext().getAction().name(),
- runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()
- ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
- String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
- runtimeContext.getResponseContext().getStatus().getMessage(),
- this.getClass().getCanonicalName());
+ Instant.now(),
+ LoggingConstants.TargetNames.APPC,
+ runtimeContext.getRequestContext().getAction().name(),
+ runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()
+ ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+ runtimeContext.getResponseContext().getStatus().getMessage(),
+ this.getClass().getCanonicalName());
}
private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " +
- ObjectUtils.toString(responseContext));
+ logger.trace("Entering to postMessageToDMaaP with AsyncResponse = "
+ + ObjectUtils.toString(responseContext));
}
logger.debug("In postMessageToDMaap before invoking post()");
boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext);
@@ -402,44 +404,41 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
logger.error("DMaaP posting status: false", "dmaapMessage: " + responseContext);
}
if (logger.isTraceEnabled())
- logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " +
- ObjectUtils.toString(callbackResponse) + ")");
+ logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = "
+ + ObjectUtils.toString(callbackResponse) + ")");
}
private void initMetric() {
- if (logger.isDebugEnabled())
- logger.debug("Metric getting initialized");
+ logger.debug("Metric getting initialized");
MetricService metricService = getMetricservice();
// Check for the metric service created before trying to create registry using
// the metricService object
if (metricService == null) {
// Cannot find service reference for org.onap.appc.metricservice.MetricService
- throw new NullPointerException("org.onap.appc.metricservice.MetricService is null. " +
- "Failed to init Metric");
+ throw new NullPointerException("org.onap.appc.metricservice.MetricService is null. "
+ + "Failed to init Metric");
}
metricRegistry = metricService.createRegistry("APPC");
- DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory().
- dispatchingFunctionCounterBuilder().
- withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER).
- withAcceptRequestValue(0)
- .withRejectRequestValue(0)
- .build();
+ DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory()
+ .dispatchingFunctionCounterBuilder()
+ .withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER)
+ .withAcceptRequestValue(0)
+ .withRejectRequestValue(0)
+ .build();
if (metricRegistry.register(dispatchingFuntionMetric)) {
Metric[] metrics = new Metric[]{dispatchingFuntionMetric};
LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
LogPublisher[] logPublishers = new LogPublisher[1];
logPublishers[0] = logPublisher;
PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
- .scheduledPolicyBuilder()
- .withPublishers(logPublishers)
- .withMetrics(metrics)
- .build();
+ .scheduledPolicyBuilder()
+ .withPublishers(logPublishers)
+ .withMetrics(metrics)
+ .build();
- if (logger.isDebugEnabled())
- logger.debug("Policy getting initialized");
+ logger.debug("Policy getting initialized");
manuallyScheduledPublishingPolicy.init();
- if (logger.isDebugEnabled())
- logger.debug("Metric initialized");
+ logger.debug("Metric initialized");
}
}
@@ -458,13 +457,11 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
/**
* This method returns the count of in progress requests
- * * @return in progress requests count
+ * @return in progress requests count
*/
@Override
public int getInprogressRequestCount() throws APPCException {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to getInprogressRequestCount");
- }
+ logger.trace("Entering to getInprogressRequestCount");
return transactionRecorder.getInProgressRequestsCount();
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java
index a0b27462d..71545ab10 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -19,20 +19,16 @@
* 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.onap.appc.requesthandler.impl;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-import java.util.stream.Collectors;
+import com.att.eelf.i18n.EELFResourceManager;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
@@ -70,16 +66,22 @@ import org.onap.appc.validationpolicy.objects.RuleResult;
import org.onap.appc.workflow.WorkFlowManager;
import org.onap.appc.workflow.objects.WorkflowExistsOutput;
import org.onap.appc.workflow.objects.WorkflowRequest;
-import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
+import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
-import com.att.eelf.i18n.EELFResourceManager;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import java.util.stream.Collectors;
public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
@@ -102,7 +104,6 @@ public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
String user = null;
String pass = null;
String transactionWindow = null;
-
Properties properties = configuration.getProperties();
if (properties != null) {
endpoint = properties.getProperty(SCOPE_OVERLAP_ENDPOINT);
@@ -213,20 +214,21 @@ public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
}
List<TransactionRecord> inProgressTransactionsAll = transactionRecorder
- .getInProgressRequests(runtimeContext.getTransactionRecord(),0);
+ .getInProgressRequests(runtimeContext.getTransactionRecord(), 0);
List<TransactionRecord> inProgressTransactions = transactionRecorder
- .getInProgressRequests(runtimeContext.getTransactionRecord(),transactionWindowInterval);
-
- long inProgressTransactionsAllCount = inProgressTransactionsAll.size();
- long inProgressTransactionsRelevant = inProgressTransactions.size();
+ .getInProgressRequests(runtimeContext.getTransactionRecord(), transactionWindowInterval);
+ long inProgressTransactionsAllCount = inProgressTransactionsAll == null ? 0 : inProgressTransactionsAll.size();
+ long inProgressTransactionsRelevant = inProgressTransactions == null ? 0 : inProgressTransactions.size();
logger.debug("In progress requests " + inProgressTransactions.toString());
- if ( inProgressTransactions.isEmpty()){ //No need to check for scope overlap
+ if (inProgressTransactionsRelevant == 0) { //No need for further checks
return;
}
- logInProgressTransactions(inProgressTransactions,inProgressTransactionsAllCount,
- inProgressTransactionsRelevant );
+ if (logger.isInfoEnabled()) {
+ logger.info(logInProgressTransactions(inProgressTransactions, inProgressTransactionsAllCount,
+ inProgressTransactionsRelevant));
+ }
Long exclusiveRequestCount = inProgressTransactions.stream()
.filter(record -> record.getMode().equals(Flags.Mode.EXCLUSIVE.name())).count();
@@ -493,7 +495,7 @@ public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
this.getClass().getCanonicalName());
throw new WorkflowNotFoundException(
"Workflow mapping not found for vnfType = " + vnfContext.getType() + ", command = "
- + requestContext.getAction().name(),
+ + requestContext.getAction().name(),
vnfContext.getType(), requestContext.getAction().name());
}
if (!workflowExistsOutput.isDgExist()) {
@@ -507,7 +509,7 @@ public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
this.getClass().getCanonicalName());
throw new DGWorkflowNotFoundException(
"Workflow not found for vnfType = " + vnfContext.getType() + ", command = "
- + requestContext.getAction().name(),
+ + requestContext.getAction().name(),
workflowExistsOutput.getWorkflowModule(), workflowExistsOutput.getWorkflowName(),
workflowExistsOutput.getWorkflowVersion(), vnfContext.getType(), requestContext.getAction().name());
}
@@ -526,25 +528,24 @@ public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
public String logInProgressTransactions(List<TransactionRecord> inProgressTransactions,
long inProgressTransactionsAllCount, long inProgressTransactionsRelevant) {
- if (inProgressTransactionsAllCount > inProgressTransactionsRelevant) {
- logger.info("Found Stale Transactions! Ignoring Stale Transactions for target, only considering "
+ if (inProgressTransactionsAllCount > inProgressTransactionsRelevant) {
+ logger.info("Found Stale Transactions! Ignoring Stale Transactions for target, only considering "
+ "transactions within the last " + transactionWindowInterval + " hours as transactions in-progress");
- }
- String logMsg="";
- for (TransactionRecord tr: inProgressTransactions) {
- logMsg = ("In Progress transaction for Target ID - "+ tr.getTargetId()
- + " in state " + tr.getRequestState()
- + " with Start time " + tr.getStartTime().toString()
- + " for more than configurable time period " + transactionWindowInterval
- + " hours [transaction details - Request ID - " + tr.getTransactionId()
- + ", Service Instance Id -" + tr.getServiceInstanceId()
- + ", Vserver_id - " + tr.getVserverId()
- + ", VNFC_name - "+ tr.getVnfcName()
- + ", VF module Id - " + tr.getVfModuleId()
- + " Start time " + tr.getStartTime().toString()
- + "]" );
- }
- return logMsg;
-
+ }
+ String logMsg = "";
+ for (TransactionRecord tr: inProgressTransactions) {
+ logMsg = ("In Progress transaction for Target ID - " + tr.getTargetId()
+ + " in state " + tr.getRequestState()
+ + " with Start time " + tr.getStartTime().toString()
+ + " for more than configurable time period " + transactionWindowInterval
+ + " hours [transaction details - Request ID - " + tr.getTransactionId()
+ + ", Service Instance Id - " + tr.getServiceInstanceId()
+ + ", Vserver_id - " + tr.getVserverId()
+ + ", VNFC_name - " + tr.getVnfcName()
+ + ", VF module Id - " + tr.getVfModuleId()
+ + " Start time " + tr.getStartTime().toString()
+ + "]");
+ }
+ return logMsg;
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java
index af6dc314b..41f9d2a8e 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,14 @@
* 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=========================================================
*/
@@ -41,7 +40,6 @@ import org.onap.appc.validationpolicy.rules.RuleFactory;
import org.onap.ccsdk.sli.core.dblib.DbLibService;
import javax.sql.rowset.CachedRowSet;
-import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -66,7 +64,7 @@ public class RequestValidationPolicy {
this.dbLibService = dbLibService;
}
- public void initialize(){
+ public void initialize() {
try {
String jsonContent = getPolicyJson();
if (jsonContent == null) return;
@@ -78,29 +76,30 @@ public class RequestValidationPolicy {
policyList.stream()
.filter(policy -> PolicyNames.ActionInProgress.name().equals(policy.getPolicyName()))
.forEach(policy -> {
- Rule[] ruleDTOs = policy.getRules();
- Map<String, org.onap.appc.validationpolicy.rules.Rule> rules = new HashMap<>();
- for(Rule ruleDTO : ruleDTOs) {
- String action = ruleDTO.getActionReceived();
- String validationRule = ruleDTO.getValidationRule();
- Set<VNFOperation> inclusionSet = null;
- Set<VNFOperation> exclusionSet = null;
- if (ruleDTO.getInclusionList() != null && !ruleDTO.getInclusionList().isEmpty()) {
- inclusionSet = ruleDTO.getInclusionList().stream()
- .map(VNFOperation::findByString).filter(operation -> operation != null)
- .collect(Collectors.toSet());
- }
- if (ruleDTO.getExclusionList() != null && !ruleDTO.getExclusionList().isEmpty()) {
- exclusionSet = ruleDTO.getExclusionList().stream()
- .map(VNFOperation::findByString).filter(operation -> operation != null)
- .collect(Collectors.toSet());
- }
- org.onap.appc.validationpolicy.rules.Rule rule = RuleFactory
- .createRule(validationRule, inclusionSet, exclusionSet);
- rules.put(action, rule);
- }
- actionInProgressRuleExecutor = new ActionInProgressRuleExecutor(Collections.unmodifiableMap(rules));
- });
+ Rule[] ruleDTOs = policy.getRules();
+ Map<String, org.onap.appc.validationpolicy.rules.Rule> rules = new HashMap<>();
+ for (Rule ruleDTO : ruleDTOs) {
+ String action = ruleDTO.getActionReceived();
+ String validationRule = ruleDTO.getValidationRule();
+ Set<VNFOperation> inclusionSet = null;
+ Set<VNFOperation> exclusionSet = null;
+ if (ruleDTO.getInclusionList() != null && !ruleDTO.getInclusionList().isEmpty()) {
+ inclusionSet = ruleDTO.getInclusionList().stream()
+ .map(VNFOperation::findByString).filter(operation -> operation != null)
+ .collect(Collectors.toSet());
+ }
+ if (ruleDTO.getExclusionList() != null && !ruleDTO.getExclusionList().isEmpty()) {
+ exclusionSet = ruleDTO.getExclusionList().stream()
+ .map(VNFOperation::findByString).filter(operation -> operation != null)
+ .collect(Collectors.toSet());
+ }
+ org.onap.appc.validationpolicy.rules.Rule rule = RuleFactory
+ .createRule(validationRule, inclusionSet, exclusionSet);
+ rules.put(action, rule);
+ }
+ actionInProgressRuleExecutor =
+ new ActionInProgressRuleExecutor(Collections.unmodifiableMap(rules));
+ });
} catch (Exception e) {
logger.error("Error reading request validation policies", e);
}
@@ -108,34 +107,37 @@ public class RequestValidationPolicy {
protected String getPolicyJson() {
String schema = "sdnctl";
- String query = "SELECT MAX(INTERNAL_VERSION),ARTIFACT_CONTENT " +
- "FROM ASDC_ARTIFACTS " +
- "WHERE ARTIFACT_NAME = ? " +
- "GROUP BY ARTIFACT_NAME";
+ String query =
+ "SELECT MAX(INTERNAL_VERSION),ARTIFACT_CONTENT "
+ + "FROM ASDC_ARTIFACTS "
+ + "WHERE ARTIFACT_NAME = ? "
+ + "GROUP BY ARTIFACT_NAME";
ArrayList<String> arguments = new ArrayList<>();
arguments.add("request_validation_policy");
String jsonContent = null;
- try{
+ try {
CachedRowSet rowSet = dbLibService.getData(query, arguments, schema);
- if(rowSet.next()){
+ if (rowSet != null && rowSet.next()) {
jsonContent = rowSet.getString("ARTIFACT_CONTENT");
}
- if(logger.isDebugEnabled()){
+ if (logger.isDebugEnabled()) {
logger.debug("request validation policy = " + jsonContent);
}
- if(StringUtils.isBlank(jsonContent)){
+ if (StringUtils.isBlank(jsonContent)) {
logger.warn("request validation policy not found in app-c database");
}
- }
- catch(SQLException e){
+ } catch(Exception e) {
+ logger.debug("Error while accessing database: " + e.getMessage());
+ logger.info("Error connecting to database: " + e.getMessage());
logger.error("Error accessing database", e);
throw new RuntimeException(e);
}
+ logger.info("Got Policy Json");
return jsonContent;
}
- public RuleExecutor getInProgressRuleExecutor(){
- if(actionInProgressRuleExecutor == null){
+ public RuleExecutor getInProgressRuleExecutor() {
+ if (actionInProgressRuleExecutor == null) {
throw new RuntimeException("Rule executor not available, initialization of RequestValidationPolicy failed");
}
return actionInProgressRuleExecutor;
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java
index a2c3ec360..89d34111a 100755
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java
@@ -2,6 +2,8 @@
* ============LICENSE_START=======================================================
* Copyright (C) 2018-2019 Ericsson. All rights reserved.
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* 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
*
@@ -97,7 +99,8 @@ public class AbstractRequestHandlerImplTest implements LocalRequestHanlderTestHe
recorder = mock(TransactionRecorder.class);
requestHandler.setTransactionRecorder(recorder);
List<RequestStatus> result = Arrays.asList(RequestStatus.ACCEPTED);
- PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result);
+ PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(result);
final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class);
logger.setLevel(Level.TRACE);
Whitebox.setInternalState(requestHandler, "logger", logger);
@@ -210,14 +213,21 @@ public class AbstractRequestHandlerImplTest implements LocalRequestHanlderTestHe
PowerMockito.when(bundleContext.getService(sref)).thenReturn(metricService);
MetricRegistry metricRegistry = Mockito.mock(MetricRegistry.class);
DispatchingFuntionMetric dispatchingFunctionMetric = Mockito.mock(DispatchingFuntionMetric.class);
- DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder = Mockito.mock(DispatchingFunctionCounterBuilder.class);
+ DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder =
+ Mockito.mock(DispatchingFunctionCounterBuilder.class);
MetricBuilderFactory metricBuilderFactory = Mockito.mock(MetricBuilderFactory.class);
- Mockito.when(dispatchingFunctionCounterBuilder.withName("DISPATCH_FUNCTION")).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.withType(MetricType.COUNTER)).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.withAcceptRequestValue(0)).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.withRejectRequestValue(0)).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.build()).thenReturn(dispatchingFunctionMetric);
- Mockito.when(metricBuilderFactory.dispatchingFunctionCounterBuilder()).thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withName("DISPATCH_FUNCTION"))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withType(MetricType.COUNTER))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withAcceptRequestValue(0))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withRejectRequestValue(0))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.build()).
+ thenReturn(dispatchingFunctionMetric);
+ Mockito.when(metricBuilderFactory.dispatchingFunctionCounterBuilder())
+ .thenReturn(dispatchingFunctionCounterBuilder);
Mockito.when(metricRegistry.metricBuilderFactory()).thenReturn(metricBuilderFactory);
Mockito.when(metricService.createRegistry("APPC")).thenReturn(metricRegistry);
Mockito.when(metricRegistry.register(dispatchingFunctionMetric)).thenReturn(true);
@@ -237,8 +247,8 @@ public class AbstractRequestHandlerImplTest implements LocalRequestHanlderTestHe
@Test
public void testMetricNullMetricService() throws Exception {
expectedEx.expect(NullPointerException.class);
- expectedEx.expectMessage("org.onap.appc.metricservice.MetricService is null. " +
- "Failed to init Metric");
+ expectedEx.expectMessage("org.onap.appc.metricservice.MetricService is null. "
+ + "Failed to init Metric");
Whitebox.invokeMethod(requestHandler, "initMetric");
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java
index f163c6eab..437cd5d4b 100755
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java
@@ -2,6 +2,8 @@
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* 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
*
@@ -84,7 +86,8 @@ public class RequestHandlerImplTest implements LocalRequestHanlderTestHelper {
lockManager = mock(LockManager.class);
requestHandler.setLockManager(lockManager);
List<RequestStatus> result = Arrays.asList(RequestStatus.ACCEPTED);
- PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result);
+ PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(result);
final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class);
logger.setLevel(Level.TRACE);
Whitebox.setInternalState(requestHandler, "logger", logger);
@@ -142,7 +145,7 @@ public class RequestHandlerImplTest implements LocalRequestHanlderTestHelper {
doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class),
Mockito.any(LCMCommandStatus.class), Mockito.any());
doThrow(new APPCException("TEST_APPC_EXCEPTION")).when(commandExecutor)
- .executeCommand(Mockito.any(CommandExecutorInput.class));
+ .executeCommand(Mockito.any(CommandExecutorInput.class));
doNothing().when(requestHandler).storeErrorMessageToLog(Mockito.any(RuntimeContext.class), Mockito.anyString(),
Mockito.anyString(), Mockito.anyString());
requestHandler.handleRequest(runtimeContext);
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java
index ba2915189..bb713cdc9 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -19,7 +19,6 @@
* 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=========================================================
*/
@@ -127,24 +126,24 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
AAIService aaiService = Mockito.mock(AAIService.class);
PowerMockito.when(aaiService.query(
anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenAnswer(new Answer<SvcLogicResource.QueryStatus>() {
- @Override
- public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Exception {
- Object[] args = invocation.getArguments();
- SvcLogicContext ctx = (SvcLogicContext) args[6];
- String prefix = (String) args[4];
- String key = (String) args[3];
- if (key.contains("'28'")) {
- return SvcLogicResource.QueryStatus.FAILURE;
- } else if (key.contains("'8'")) {
- return SvcLogicResource.QueryStatus.NOT_FOUND;
- } else {
- ctx.setAttribute(prefix + ".vnf-type", "FIREWALL");
- ctx.setAttribute(prefix + ".orchestration-status", "Instantiated");
+ .thenAnswer(new Answer<SvcLogicResource.QueryStatus>() {
+ @Override
+ public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Exception {
+ Object[] args = invocation.getArguments();
+ SvcLogicContext ctx = (SvcLogicContext) args[6];
+ String prefix = (String) args[4];
+ String key = (String) args[3];
+ if (key.contains("'28'")) {
+ return SvcLogicResource.QueryStatus.FAILURE;
+ } else if (key.contains("'8'")) {
+ return SvcLogicResource.QueryStatus.NOT_FOUND;
+ } else {
+ ctx.setAttribute(prefix + ".vnf-type", "FIREWALL");
+ ctx.setAttribute(prefix + ".orchestration-status", "Instantiated");
+ }
+ return SvcLogicResource.QueryStatus.SUCCESS;
}
- return SvcLogicResource.QueryStatus.SUCCESS;
- }
- });
+ });
PowerMockito.mockStatic(FrameworkUtil.class);
PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService);
PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
@@ -209,17 +208,19 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
transactionRecord.setRequestState(RequestStatus.ACCEPTED);
runtimeContext.setTransactionRecord(transactionRecord);
transactionRecordList.add(transactionRecord);
- Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),Mockito.any(int.class)))
- .thenReturn(transactionRecordList);
+ Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),
+ Mockito.any(int.class)))
+ .thenReturn(transactionRecordList);
impl.setTransactionRecorder(transactionRecorder);
WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true);
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
- Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))).thenReturn(workflowExistsOutput);
+ Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
+ .thenReturn(workflowExistsOutput);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
@@ -227,7 +228,8 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class);
RuleResult ruleResult = RuleResult.REJECT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
- Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class))).thenReturn(ruleResult);
+ Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
impl.validateRequest(runtimeContext);
}
@@ -262,14 +264,15 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
inProgressTransaction.setStartTime(Instant.now().minus(5, ChronoUnit.HOURS));
inProgressTransaction.setRequestState(RequestStatus.ACCEPTED);
transactionRecordList.add(inProgressTransaction);
- Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),Mockito.any(int.class)))
+ Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),
+ Mockito.any(int.class)))
.thenReturn(transactionRecordList);
runtimeContext.setTransactionRecord(inProgressTransaction);
impl.setTransactionRecorder(transactionRecorder);
WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true);
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
@@ -302,20 +305,21 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
inProgressTransaction.setRequestState(RequestStatus.ACCEPTED);
inProgressTransaction.setStartTime(Instant.now().minus(48, ChronoUnit.HOURS));
transactionRecordList.add(inProgressTransaction);
- Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),Mockito.any(int.class)))
- .thenReturn(transactionRecordList);
+ Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),
+ Mockito.any(int.class)))
+ .thenReturn(transactionRecordList);
Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
impl.setTransactionRecorder(transactionRecorder);
runtimeContext.setTransactionRecord(inProgressTransaction);
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
@@ -324,7 +328,7 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
RuleResult ruleResult = RuleResult.ACCEPT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
- .thenReturn(ruleResult);
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
RequestContext requestContext = new RequestContext();
ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
@@ -351,13 +355,13 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
Mockito.when(workflowExistsOutput.isMappingExist()).thenReturn(false);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");;
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
@@ -366,7 +370,7 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
RuleResult ruleResult = RuleResult.REJECT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
- .thenReturn(ruleResult);
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
impl.validateRequest(runtimeContext);
}
@@ -384,13 +388,13 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
Mockito.when(workflowExistsOutput.isDgExist()).thenReturn(false);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
@@ -399,7 +403,7 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
RuleResult ruleResult = RuleResult.REJECT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
- .thenReturn(ruleResult);
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
impl.validateRequest(runtimeContext);
}
@@ -458,7 +462,8 @@ public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
private BasicHttpEntity getHttpEntity() {
BasicHttpEntity httpEntity = new BasicHttpEntity();
InputStream inputStream = new ByteArrayInputStream(
- "{\"output\": {\"status\": {\"message\": \"test_messge\",\"code\": \"400\",\"status\":\"test_status\"},\"response-info\": { \"block\": \"true\"}}}".getBytes());
+ "{\"output\": {\"status\": {\"message\": \"test_messge\",\"code\": \"400\",\"status\":\"test_status\"},\"response-info\": { \"block\": \"true\"}}}"
+ .getBytes());
httpEntity.setContent(inputStream);
return httpEntity;
}
diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java
index 000415c93..659c3fbbb 100644
--- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java
+++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/main/java/org/onap/appc/workflow/impl/WorkFlowManagerImpl.java
@@ -2,30 +2,28 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
- * ================================================================================
- * Modifications (C) 2019 Ericsson
* =============================================================================
* 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.onap.appc.workflow.impl;
import org.apache.commons.lang.ObjectUtils;
+import org.apache.commons.lang3.StringUtils;
import org.onap.appc.common.constant.Constants;
import org.onap.appc.configuration.Configuration;
import org.onap.appc.configuration.ConfigurationFactory;
@@ -39,8 +37,26 @@ import org.onap.appc.workflow.objects.WorkflowResponse;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import java.util.ArrayList;
+import java.util.List;
+import org.onap.ccsdk.sli.core.dblib.DbLibService;
+import org.onap.ccsdk.sli.core.sli.SvcLogicGraph;
+import javax.sql.rowset.CachedRowSet;
+import java.sql.SQLException;
+import java.sql.Blob;
+import java.io.ObjectInputStream;
+import java.io.IOException;
+import org.slf4j.MDC;
+
+
+
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Enumeration;
@@ -49,6 +65,7 @@ import java.util.Properties;
public class WorkFlowManagerImpl implements WorkFlowManager{
+ private static final String DRIVER_ERROR = "DriverLoadError";
private SvcLogicService svcLogic = null;
private final EELFLogger logger = EELFManager.getInstance().getLogger(WorkFlowManagerImpl.class);
private final Configuration configuration = ConfigurationFactory.getConfiguration();
@@ -68,57 +85,73 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
/**
* Execute workflow and return response.
* This method execute workflow with following steps.
- * Retrieve workflow(DG) details - module, version and mode from database based on command and vnf Type from incoming request.
+ * Retrieve workflow(DG) details - module, version and mode from database
+ * based on command and vnf Type from incoming request.
* Execute workflow (DG) using SVC Logic Service reference
* Return response of workflow (DG) to caller.
*
- * @param workflowRequest workflow execution request which contains vnfType, command, requestId, targetId, payload and (optional) confID;
+ * @param workflowRequest workflow execution request which contains vnfType,
+ * command, requestId, targetId, payload and (optional) confID;
* @return Workflow Response which contains execution status and payload from DG if any
*/
@Override
public WorkflowResponse executeWorkflow(WorkflowRequest workflowRequest) {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to executeWorkflow with WorkflowRequest = " + ObjectUtils.toString(workflowRequest.toString()));
- }
+ logger.trace("Entering to executeWorkflow with WorkflowRequest = "
+ + ObjectUtils.toString(workflowRequest.toString()));
WorkflowResponse workflowResponse = new WorkflowResponse();
workflowResponse.setResponseContext(workflowRequest.getResponseContext());
try {
- WorkflowKey workflowKey = workflowResolver.resolve(workflowRequest.getRequestContext().getAction().name(), workflowRequest.getVnfContext().getType(), null,workflowRequest.getRequestContext().getCommonHeader().getApiVer());
+ WorkflowKey workflowKey =
+ workflowResolver.resolve(workflowRequest.getRequestContext().getAction().name(),
+ workflowRequest.getVnfContext().getType(), null,
+ workflowRequest.getRequestContext().getCommonHeader().getApiVer());
Properties workflowParams = new Properties();
String actionProperty;
String requestIdProperty;
String vfIdProperty;
- if(!workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){
+ if (!workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")) {
/*
The following method call (populateDGContext) populates DG context with the
request parameters to maintain backward compatibility with old DGs,
we are not altering the old way of passing (org.onap.appc.vnfId and so on..)
This is still a temporary solution, the end solution should be agreed with
all stakeholders and implemented.
- */
+ */
populateDGContext(workflowParams, workflowRequest);
} else {
- actionProperty = configuration.getProperty("org.onap.appc.workflow.action", String.valueOf(Constants.ACTION));
- requestIdProperty = configuration.getProperty("org.onap.appc.workflow.request.id", String.valueOf(Constants.REQUEST_ID));
- vfIdProperty = configuration.getProperty("org.onap.appc.workflow.vfid", String.valueOf(Constants.VF_ID));
- String vfTypeProperty = configuration.getProperty("org.onap.appc.workflow.vftype", String.valueOf(Constants.VF_TYPE));
- String apiVerProperty = configuration.getProperty("org.onap.appc.workflow.apiVersion", String.valueOf(Constants.API_VERSION));
- String originatorIdProperty = configuration.getProperty("org.onap.appc.workflow.originatorId", Constants.ORIGINATOR_ID);
- String subRequestId = configuration.getProperty("org.onap.appc.workflow.subRequestId", Constants.SUB_REQUEST_ID);
+ actionProperty =
+ configuration.getProperty("org.onap.appc.workflow.action", String.valueOf(Constants.ACTION));
+ requestIdProperty =
+ configuration.getProperty("org.onap.appc.workflow.request.id",
+ String.valueOf(Constants.REQUEST_ID));
+ vfIdProperty =
+ configuration.getProperty("org.onap.appc.workflow.vfid", String.valueOf(Constants.VF_ID));
+ String vfTypeProperty =
+ configuration.getProperty("org.onap.appc.workflow.vftype", String.valueOf(Constants.VF_TYPE));
+ String apiVerProperty =
+ configuration.getProperty("org.onap.appc.workflow.apiVersion",
+ String.valueOf(Constants.API_VERSION));
+ String originatorIdProperty =
+ configuration.getProperty("org.onap.appc.workflow.originatorId", Constants.ORIGINATOR_ID);
+ String subRequestId =
+ configuration.getProperty("org.onap.appc.workflow.subRequestId", Constants.SUB_REQUEST_ID);
workflowParams.put(actionProperty, workflowRequest.getRequestContext().getAction().name());
- workflowParams.put(requestIdProperty, workflowRequest.getRequestContext().getCommonHeader().getRequestId());
+ workflowParams.put(requestIdProperty,
+ workflowRequest.getRequestContext().getCommonHeader().getRequestId());
workflowParams.put(vfIdProperty, workflowRequest.getVnfContext().getId());
workflowParams.put(vfTypeProperty, workflowRequest.getVnfContext().getType());
workflowParams.put(apiVerProperty, workflowRequest.getRequestContext().getCommonHeader().getApiVer());
- workflowParams.put(originatorIdProperty, workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
- workflowParams.put(subRequestId, workflowRequest.getRequestContext().getCommonHeader().getSubRequestId());
+ workflowParams.put(originatorIdProperty,
+ workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
+ workflowParams.put(subRequestId,
+ workflowRequest.getRequestContext().getCommonHeader().getSubRequestId());
Object payloadJson = workflowRequest.getRequestContext().getPayload();
- if(payloadJson != null) {
+ if (payloadJson != null) {
try {
Map<String, String> payloadProperties = ObjectMapper.map(payloadJson);
workflowParams.putAll(payloadProperties);
@@ -128,53 +161,71 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
logger.error("Error parsing payload json string", e);
Properties workflowPrp = new Properties();
workflowPrp.setProperty("error-message", "Error parsing payload json string");
- fillStatus(501, "Error parsing payload json string: " + e.getMessage(), workflowRequest.getResponseContext());
- logger.trace("Exiting from executeWorkflow with (workflowResponse = " + ObjectUtils.toString(workflowResponse) + ")");
+ fillStatus(501, "Error parsing payload json string: " + e.getMessage(),
+ workflowRequest.getResponseContext());
+ logger.trace("Exiting from executeWorkflow with (workflowResponse = "
+ + ObjectUtils.toString(workflowResponse) + ")");
return workflowResponse;
}
}
- logger.debug("DG parameters "+ actionProperty +":"+ workflowRequest.getRequestContext().getAction().name() + ", "+
- requestIdProperty +":"+ workflowRequest.getRequestContext().getCommonHeader().getRequestId() + ", " +
- vfIdProperty + ":" + workflowRequest.getVnfContext().getId());
-
- logger.debug("Starting DG Execution for request "+workflowRequest.getRequestContext().getCommonHeader().getRequestId());
+ logger.debug("DG parameters " + actionProperty + ":"
+ + workflowRequest.getRequestContext().getAction().name() + ", "
+ + requestIdProperty + ":"
+ + workflowRequest.getRequestContext().getCommonHeader().getRequestId() + ", "
+ + vfIdProperty + ":" + workflowRequest.getVnfContext().getId());
+
+ logger.debug("Starting DG Execution for request "
+ + workflowRequest.getRequestContext().getCommonHeader().getRequestId());
}
- if (workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){
+ if (workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")) {
workflowParams.put("isBwcMode", "true");
} else {
workflowParams.put("isBwcMode", "false");
}
- SVCLogicServiceExecute(workflowKey, workflowRequest.getRequestContext(), workflowParams , workflowResponse);
- logger.trace("Completed DG Execution for Request id: " + workflowRequest.getRequestContext().getCommonHeader().getRequestId()
- + "with response code: " + workflowResponse.getResponseContext().getStatus().getCode());
- }catch (Exception e){
+ SVCLogicServiceExecute(workflowKey, workflowRequest.getRequestContext(), workflowParams,
+ workflowResponse);
+ logger.trace("Completed DG Execution for Request id: "
+ + workflowRequest.getRequestContext().getCommonHeader().getRequestId() + " with response code: "
+ + workflowResponse.getResponseContext().getStatus().getCode());
+ } catch (Exception e) {
logger.error("Error Executing DG " + e.getMessage(), e);
- fillStatus(501, "Error Executing DG "+ e.getMessage(), workflowRequest.getResponseContext());
+ fillStatus(501, "Error Executing DG " + e.getMessage(), workflowRequest.getResponseContext());
}
- logger.trace("Exiting from executeWorkflow with (workflowResponse = " +
- ObjectUtils.toString(workflowResponse.getResponseContext().getStatus().getMessage()) + ")");
+ logger.trace("Exiting from executeWorkflow with (workflowResponse = "
+ + ObjectUtils.toString(workflowResponse.getResponseContext().getStatus().getMessage()) + ")");
return workflowResponse;
}
private void populateDGContext(Properties workflowParams, WorkflowRequest workflowRequest) {
- workflowParams.put("input.common-header.timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(workflowRequest.getRequestContext().getCommonHeader().getTimeStamp()));
- workflowParams.put("input.common-header.api-ver", workflowRequest.getRequestContext().getCommonHeader().getApiVer());
- workflowParams.put("input.common-header.request-id", workflowRequest.getRequestContext().getCommonHeader().getRequestId());
- workflowParams.put("input.common-header.originator-id", workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
- workflowParams.put("input.common-header.sub-request-id", workflowRequest.getRequestContext().getCommonHeader().getSubRequestId() != null ?
+ workflowParams.put("input.common-header.timestamp",
+ new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
+ .format(workflowRequest.getRequestContext().getCommonHeader().getTimeStamp()));
+ workflowParams.put("input.common-header.api-ver",
+ workflowRequest.getRequestContext().getCommonHeader().getApiVer());
+ workflowParams.put("input.common-header.request-id",
+ workflowRequest.getRequestContext().getCommonHeader().getRequestId());
+ workflowParams.put("input.common-header.originator-id",
+ workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
+ workflowParams.put("input.common-header.sub-request-id",
+ workflowRequest.getRequestContext().getCommonHeader().getSubRequestId() != null ?
workflowRequest.getRequestContext().getCommonHeader().getSubRequestId() : "");
workflowParams.put("input.action", workflowRequest.getRequestContext().getAction().toString());
- workflowParams.put("input.payload", null != workflowRequest.getRequestContext().getPayload() ?
+ workflowParams.put("input.payload",
+ null != workflowRequest.getRequestContext().getPayload() ?
workflowRequest.getRequestContext().getPayload() : "");
workflowParams.put("input.action-identifiers.vnf-id", workflowRequest.getVnfContext().getId());
- workflowParams.put("input.action-identifiers.vnfc-name", workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName() != null ?
+ workflowParams.put("input.action-identifiers.vnfc-name",
+ workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName() : "");
- workflowParams.put("input.action-identifiers.service-instance-id", workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId() !=null ?
+ workflowParams.put("input.action-identifiers.service-instance-id",
+ workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId() : "");
- workflowParams.put("input.action-identifiers.vserver-id", workflowRequest.getRequestContext().getActionIdentifiers().getVserverId() !=null ?
+ workflowParams.put("input.action-identifiers.vserver-id",
+ workflowRequest.getRequestContext().getActionIdentifiers().getVserverId() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getVserverId() : "");
- workflowParams.put("input.action-identifiers.vf-module-id",workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId() !=null ?
+ workflowParams.put("input.action-identifiers.vf-module-id",
+ workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId() : "");
final Map<String, String> additionalContext;
if ((additionalContext = workflowRequest.getRequestContext().getAdditionalContext()) != null) {
@@ -192,8 +243,9 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
*/
@Override
public WorkflowExistsOutput workflowExists(WorkflowRequest workflowQueryParams) {
- WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(false,false);
- logger.trace("Entering to workflowExists with WorkflowRequest = " + ObjectUtils.toString(workflowQueryParams.toString()));
+ WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(false, false);
+ logger.trace("Entering to workflowExists with WorkflowRequest = "
+ + ObjectUtils.toString(workflowQueryParams.toString()));
try {
WorkflowKey workflowKey = workflowResolver.resolve(
@@ -208,21 +260,24 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
workflowExistsOutput.setWorkflowVersion(workflowKey.version());
if (isDGExists(workflowKey)) {
workflowExistsOutput.setDgExist(true);
- }else{
+ } else {
logger.warn(
- String.format("SLI doesn't have DG for resolved mapping entry: DG module - '%s', DG name - '%s', DG version - '%s'",
- workflowKey.module(), workflowKey.name(), workflowKey.version()));
+ String.format("SLI doesn't have DG for resolved mapping entry: "
+ + "DG module - '%s', DG name - '%s', DG version - '%s'",
+ workflowKey.module(), workflowKey.name(), workflowKey.version()));
}
- }else{
+ } else {
logger.warn(
- String.format("Unable to resolve recipe matching action '%s', VNF type '%s' and VNF version '%s'",
- workflowQueryParams.getRequestContext().getAction().name(), workflowQueryParams.getVnfContext().getType(), null));
+ String.format("Unable to resolve recipe matching action '%s', VNF type '%s'"
+ + " and VNF version '%s'",
+ workflowQueryParams.getRequestContext().getAction().name(),
+ workflowQueryParams.getVnfContext().getType(), null));
}
} catch (RuntimeException e) {
- logger.error("Error querying workflow from database"+e.getMessage());
+ logger.error("Error querying workflow from database" + e.getMessage());
throw e;
- }catch (SvcLogicException e) {
- logger.error("Error querying workflow from database"+e.getMessage());
+ } catch (SvcLogicException e) {
+ logger.error("Error querying workflow from database" + e.getMessage());
throw new RuntimeException(e);
}
logger.trace("Exiting workflowExists");
@@ -234,19 +289,162 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
return svcLogic.hasGraph(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync");
}
- private void SVCLogicServiceExecute(WorkflowKey workflowKey, RequestContext requestContext, Properties workflowParams, WorkflowResponse workflowResponse) {
+
+ private void restartDbLibProvider() {
+
+ Bundle bundle = FrameworkUtil.getBundle(org.onap.ccsdk.sli.core.dblib.DbLibService.class);
+ try {
+ bundle.stop();
+ bundle.start();
+ //Thread.sleep(5000);
+ } catch (org.osgi.framework.BundleException be) {
+ logger.error("Error restarting db lib" + be.toString());
+ } /*catch (InterruptedException e) {
+ }*/
+ }
+
+ private SvcLogicGraph fetchGraph(String module, String rpc, String version, String mode, StringBuilder sbError)
+ {
+ DbLibService dbLibSvc = null;
+
+ ServiceReference sref = null;
+ BundleContext bctx = null;
+
+ Bundle bundle = FrameworkUtil.getBundle(WorkFlowManagerImpl.class);
+
+ if (bundle != null) {
+ bctx = bundle.getBundleContext();
+
+ if (bctx != null) {
+ sref = bctx.getServiceReference("org.onap.ccsdk.sli.core.dblib.DbLibService");
+ }
+
+ if (sref == null) {
+ logger.warn("Could not find service reference for DBLIB service");
+ } else {
+ dbLibSvc = (DbLibService) bctx.getService(sref);
+ if (dbLibSvc == null) {
+ logger.warn("Could not find service reference for DBLIB service");
+ }
+ }
+ }
+ if (dbLibSvc == null)
+ return null;
+ else
+ logger.info("Retrieving graph(new)");
+
+ SvcLogicGraph retval = null;
+ CachedRowSet results = null;
+
+ String fetchVersionGraphSql = "SELECT graph FROM SVC_LOGIC"
+ + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
+
+ String fetchActiveGraphSql = "SELECT graph FROM SVC_LOGIC"
+ + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
+
+
+ String fetchGraphStmt;
+
+ ArrayList<String> params = new ArrayList<>();
+ params.add(module);
+ params.add(rpc);
+ params.add(mode);
+
+ if (version == null) {
+ fetchGraphStmt = fetchActiveGraphSql;
+ } else {
+ params.add(version);
+ fetchGraphStmt = fetchVersionGraphSql;
+ }
+
+ StringBuilder sqlBuilder = new StringBuilder(fetchGraphStmt);
+ try {
+ results = dbLibSvc.getData(sqlBuilder.toString(), new ArrayList(params), "sdnctl");
+
+ if (results.next()) {
+
+ ObjectInputStream gStream = new ObjectInputStream(results.getBinaryStream("graph"));
+
+ Object graphObj = gStream.readObject();
+ gStream.close();
+
+ if (graphObj instanceof SvcLogicGraph) {
+ retval = (SvcLogicGraph) graphObj;
+ } else {
+ logger.error("invalid type for graph " + graphObj.getClass().getName());
+ return null;
+ }
+
+ } else {
+ return null;
+ }
+ } catch (SQLException e) {
+ logger.error("query " + sqlBuilder + " :: " + e.getMessage() + " Will retry");
+ //sbError.append(DRIVER_ERROR);
+ return null;
+ } catch (IOException e) {
+ logger.error("IOException " + " :: " + e.getMessage() + " Will retry");
+ //sbError.append(DRIVER_ERROR);
+ return null;
+ } catch (Exception e) {
+ logger.error("Exception " + " :: " + e.getMessage() + " Will retry");
+ sbError.append(DRIVER_ERROR);
+ return null;
+ }
+
+
+ return retval;
+ }
+
+ protected Properties workflowExecute(String module, String rpc, String version, String mode, Properties props)
+ throws SvcLogicException {
+ logger.info("Fetching service logic from data store");
+ //logger.info("Trial Restart ");
+ //restartDbLibProvider();
+ //logger.info("Trial Restart End");
+
+ StringBuilder sbError = new StringBuilder();
+ SvcLogicGraph graph = fetchGraph(module, rpc, version, mode, sbError);
+ if (sbError.toString().equals(DRIVER_ERROR))
+ {
+ restartDbLibProvider();
+ sbError = new StringBuilder();
+ graph = fetchGraph(module, rpc, version, mode, sbError);
+ }
+ if (graph == null) {
+ Properties retProps = new Properties();
+ retProps.setProperty("error-code", "401");
+ retProps.setProperty("error-message",
+ "No service logic found for [" + module + "," + rpc + "," + version + "," + mode + "]");
+ return (retProps);
+ }
+
+ SvcLogicContext ctx = new SvcLogicContext(props);
+ ctx.setAttribute("currentGraph", graph.toString());
+ ctx.setAttribute("X-ONAP-RequestID", MDC.get("X-ONAP-RequestID"));
+ svcLogic.execute(graph, ctx);
+ return (ctx.toProperties());
+ }
+
+ private void SVCLogicServiceExecute(WorkflowKey workflowKey, RequestContext requestContext,
+ Properties workflowParams, WorkflowResponse workflowResponse) {
logger.trace("Entering SVCLogicServiceExecute");
Properties respProps = null;
try {
- respProps = svcLogic.execute(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync", workflowParams);
+ respProps = workflowExecute(workflowKey.module(), workflowKey.name(), workflowKey.version(),
+ "sync", workflowParams);
} catch (Exception e) {
- setWorkFlowResponseStatus(workflowResponse.getResponseContext(), "failure", "Unexpected SLI Adapter failure", 200);
+ setWorkFlowResponseStatus(workflowResponse.getResponseContext(), "failure",
+ "Unexpected SLI Adapter failure", 200);
+
+ String stk = "";
if (logger.isDebugEnabled()) {
- logger.debug("Error while executing DG " + e.getMessage() + e.getStackTrace());
- logger.error("Error in DG", e.getMessage() + Arrays.toString(e.getStackTrace()), e);
+ stk = Arrays.toString(e.getStackTrace());
+ logger.debug("Error while executing DG " + e.getMessage() + stk);
}
+ logger.error("Error in DG", e.getMessage() + stk, e);
}
if (respProps != null) {
@@ -262,7 +460,8 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
specificStatusCode = Integer.parseInt(dgOutputStatusCode);
}
- setWorkFlowResponseStatus(workflowResponse.getResponseContext(), commonStatus, specificStatusMessage, specificStatusCode);
+ setWorkFlowResponseStatus(workflowResponse.getResponseContext(), commonStatus, specificStatusMessage,
+ specificStatusCode);
logger.debug("DG Execution Status: " + commonStatus);
}
@@ -276,42 +475,44 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
* @param responseContext response context which you need to fill
* @param respProps DG context in a properties format
*/
- private void fillResponseContextByOutputFieldsFromDgContext(ResponseContext responseContext, Properties respProps) {
+ private void fillResponseContextByOutputFieldsFromDgContext(ResponseContext responseContext,
+ Properties respProps) {
Enumeration<?> e = respProps.propertyNames();
- while (e.hasMoreElements()){
+ while (e.hasMoreElements()) {
String key = (String) e.nextElement();
- if (key.startsWith("output.")){
- if (!key.startsWith("output.common-header.") && !key.startsWith("output.status.")){
+ if (key.startsWith("output.")) {
+ if (!key.startsWith("output.common-header.") && !key.startsWith("output.status.")) {
- if (key.equalsIgnoreCase("output.payload")){
+ if (key.equalsIgnoreCase("output.payload")) {
responseContext.setPayload(respProps.getProperty(key));
} else {
responseContext.addKeyValueToAdditionalContext(key, respProps.getProperty(key));
- }
+ }
}
}
}
}
/**
- * Filling responceContext status code amd message according to responce messages and codes from DG.
+ * Filling responseContext status code and message according to response messages and codes from DG.
*
* @param responseContext response cotext
* @param commonStatus common status message from DG ("success" or "failure")
* @param specificStatusMessage specific status message from specific DG node
* @param specificStatusCode specific status code from specific DG node
*/
- private void setWorkFlowResponseStatus(ResponseContext responseContext, String commonStatus, String specificStatusMessage, int specificStatusCode) {
+ private void setWorkFlowResponseStatus(ResponseContext responseContext, String commonStatus,
+ String specificStatusMessage, int specificStatusCode) {
if (null == specificStatusMessage) { specificStatusMessage = ""; }
- if (commonStatus.equalsIgnoreCase(Constants.DG_STATUS_SUCCESS)){
- if (specificStatusCode != 0 ){
+ if (commonStatus.equalsIgnoreCase(Constants.DG_STATUS_SUCCESS)) {
+ if (specificStatusCode != 0) {
fillStatus(specificStatusCode, specificStatusMessage, responseContext);
} else {
fillStatus(400, commonStatus, responseContext);
}
} else {
- if (specificStatusCode != 0){
+ if (specificStatusCode != 0) {
fillStatus(specificStatusCode, specificStatusMessage, responseContext);
} else {
fillStatus(401, specificStatusMessage, responseContext);
@@ -324,10 +525,12 @@ public class WorkFlowManagerImpl implements WorkFlowManager{
*
* @param code 3-digit status code
* @param message explanation of a status code
- * @param responceContext response context which will be store status code and status message
+ * @param responseContext response context which will be store status code and status message
*/
- private void fillStatus(int code, String message, ResponseContext responceContext) {
- responceContext.getStatus().setCode(code);
- responceContext.getStatus().setMessage(message);
+ private void fillStatus(int code, String message, ResponseContext responseContext) {
+ responseContext.getStatus().setCode(code);
+ responseContext.getStatus().setMessage(message);
}
+
+
}
diff --git a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/impl/TestWorkFlowManager.java b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/impl/TestWorkFlowManager.java
index 8689fa70d..ecac32714 100644
--- a/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/impl/TestWorkFlowManager.java
+++ b/appc-dispatcher/appc-workflow-management/appc-workflow-management-core/src/test/java/org/onap/appc/workflow/impl/TestWorkFlowManager.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
@@ -11,15 +11,15 @@
* 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=========================================================
*/
@@ -65,16 +65,17 @@ import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({ConfigurationFactory.class, DBUtils.class, ObjectMapper.class})
+@PrepareForTest({ConfigurationFactory.class, DBUtils.class, ObjectMapper.class, WorkFlowManagerImpl.class})
public class TestWorkFlowManager {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
-
+
public TestWorkFlowManager() {
}
@@ -85,7 +86,7 @@ public class TestWorkFlowManager {
public SvcLogicService svcLogicService;
@Before
- public void init(){
+ public void init() {
PowerMockito.mockStatic(ConfigurationFactory.class);
Configuration mockConfiguration = Mockito.mock(Configuration.class);
PowerMockito.when(ConfigurationFactory.getConfiguration()).thenReturn(mockConfiguration);
@@ -93,87 +94,120 @@ public class TestWorkFlowManager {
this.svcLogicService = Mockito.mock(SvcLogicService.class);
workflowManger.setWorkflowResolver(workflowResolver);
workflowManger.setSvcLogicServiceRef(svcLogicService);
-
}
+
@Test
- public void testExecuteWorkFlow() throws SvcLogicException{
+ public void testExecuteWorkFlow() throws SvcLogicException, Exception {
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
- WorkflowResponse response = workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertTrue(response.getResponseContext().getStatus().getMessage().equals("success"));
}
@Test
- public void testExecuteWorkFlowFalse() throws SvcLogicException{
+ public void testExecuteWorkFlowFalse() throws SvcLogicException, Exception {
+
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteFailureResponse());
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteFailureResponse());
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteFailureResponse());
- WorkflowResponse response=workflowManger.executeWorkflow(workflowRequest);
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertTrue(response.getResponseContext().getStatus().getMessage().equals("failure"));
}
@Test
- public void testExecuteWorkFlowAPIVersionStartWithOne() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
+ public void testExecuteWorkFlowAPIVersionStartWithOne() throws SvcLogicException, Exception {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
- WorkflowResponse response=workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertTrue(response.getResponseContext().getStatus().getMessage().equals("success"));
}
@Test
- public void testExecuteWorkFlowException() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
-
- WorkflowRequest workflowRequest = Mockito.spy(getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD));
+ public void testExecuteWorkFlowException() throws SvcLogicException, Exception {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowRequest workflowRequest =
+ Mockito.spy(getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD));
Mockito.when(workflowRequest.getRequestContext()).thenThrow(new RuntimeException());
- WorkflowResponse response = workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Mockito.verify(workflowRequest, Mockito.times(2)).getResponseContext();
}
@Test
- public void testExecuteWorkAPIVersion1Exception() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
-
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ public void testExecuteWorkAPIVersion1Exception() throws SvcLogicException, Exception {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
PowerMockito.mockStatic(ObjectMapper.class);
PowerMockito.when(ObjectMapper.map(Mockito.any())).thenThrow(new RuntimeException());
- WorkflowResponse response=workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertEquals(501, response.getResponseContext().getStatus().getCode());
}
@Test
- public void testWorkFlowExist() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+ public void testWorkFlowExist() throws SvcLogicException {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(true);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
WorkflowExistsOutput response = workflowManger.workflowExists(workflowRequest);
@@ -181,12 +215,15 @@ public class TestWorkFlowManager {
}
@Test
- public void testWorkFlowNotExist() throws SvcLogicException {
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString())).thenReturn(false);
+ public void testWorkFlowNotExist() throws SvcLogicException {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(false);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
WorkflowExistsOutput response = workflowManger.workflowExists(workflowRequest);
@@ -194,11 +231,14 @@ public class TestWorkFlowManager {
}
@Test
- public void testWorkFlowExistNullKey() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(null);
- Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ public void testWorkFlowExistNullKey() throws SvcLogicException {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(null);
+ Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(true);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
WorkflowExistsOutput response = workflowManger.workflowExists(workflowRequest);
Assert.assertFalse(response.isMappingExist());
}
@@ -219,8 +259,9 @@ public class TestWorkFlowManager {
workflowResolver.resolve("ACTION", "VNF_TYPE", "VNF_VERSION", "API_VERSION");
}
- private WorkflowRequest getWorkflowRequest(String vnfType, int ttl, Date timeStamp, String apiVersion, String requestId,
- String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload) {
+ private WorkflowRequest getWorkflowRequest(String vnfType, int ttl, Date timeStamp, String apiVersion,
+ String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId,
+ String payload) {
WorkflowRequest workflowRequest = new WorkflowRequest();
RuntimeContext runtimeContext = createRuntimeContext();
@@ -241,10 +282,10 @@ public class TestWorkFlowManager {
workflowRequest.setResponseContext(runtimeContext.getResponseContext());
workflowRequest.setVnfContext(runtimeContext.getVnfContext());
- return workflowRequest;
+ return workflowRequest;
}
- private RequestContext creatRequestContext(){
+ private RequestContext creatRequestContext() {
RequestContext requestContext = new RequestContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
@@ -253,10 +294,10 @@ public class TestWorkFlowManager {
requestContext.setCommonHeader(commonHeader);
requestContext.setActionIdentifiers(actionIdentifiers);
- return requestContext;
+ return requestContext;
}
- private ResponseContext createResponseContext(){
+ private ResponseContext createResponseContext() {
ResponseContext responseContext = new ResponseContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
@@ -265,10 +306,10 @@ public class TestWorkFlowManager {
responseContext.setStatus(status);
commonHeader.setFlags(flags);
- return responseContext;
+ return responseContext;
}
- private RuntimeContext createRuntimeContext(){
+ private RuntimeContext createRuntimeContext() {
RuntimeContext runtimeContext = new RuntimeContext();
RequestContext requestContext = creatRequestContext();
ResponseContext responseContext = createResponseContext();
@@ -280,13 +321,13 @@ public class TestWorkFlowManager {
return runtimeContext;
}
- public WorkflowKey getWorkFlowKey(){
+ public WorkflowKey getWorkFlowKey() {
WorkflowKey workflowKey = new WorkflowKey("APPCDG", "2.0.0.0", "dgModule");
return workflowKey;
}
- private Properties createSvcExexuteSuccessResponse(){
+ private Properties createSvcExexuteSuccessResponse() {
Properties properties = new Properties();
properties.setProperty("output.payload", "success");
properties.setProperty(Constants.DG_ATTRIBUTE_STATUS, "success");
@@ -296,7 +337,7 @@ public class TestWorkFlowManager {
return properties;
}
- private Properties createSvcExexuteFailureResponse(){
+ private Properties createSvcExexuteFailureResponse() {
Properties properties = new Properties();
properties.setProperty("output.payload", "failure");
properties.setProperty(Constants.DG_ATTRIBUTE_STATUS, "failure");