diff options
author | Dunietz, Irwin <id1681@att.com> | 2020-01-16 15:13:14 -0500 |
---|---|---|
committer | Takamune Cho <takamune.cho@att.com> | 2020-01-29 19:44:48 +0000 |
commit | b5fe8a69e90b950c07dc11af481eab7e9bab52c6 (patch) | |
tree | 3da81ce60554e65b93776b9aea647f3c6d8679ab /appc-dispatcher/appc-request-handler | |
parent | 9b32cb60360a2a2973c621053510718de0072111 (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/appc-request-handler')
8 files changed, 286 insertions, 262 deletions
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; } |