From 781b1a6df324419c846c84ea983c18fc8362bfd3 Mon Sep 17 00:00:00 2001 From: Patrick Brady Date: Wed, 13 Dec 2017 11:19:06 -0800 Subject: Third part of onap rename This part of the commit changes the folder structure on all other folders of appc. Change-Id: I8acfa11cdfcdcd36be0e137245d1dd7324f1abd3 Signed-off-by: Patrick Brady Issue-ID: APPC-13 --- .../onap/appc/messageadapter/MessageAdapter.java | 43 ++ .../messageadapter/impl/MessageAdapterImpl.java | 139 +++++ .../appc/requesthandler/constant/Constants.java | 36 ++ .../onap/appc/requesthandler/conv/Converter.java | 411 +++++++++++++ .../exceptions/DGWorkflowNotFoundException.java | 38 ++ .../exceptions/DuplicateRequestException.java | 32 + .../exceptions/InvalidInputException.java | 32 + .../exceptions/LCMOperationsDisabledException.java | 39 ++ .../exceptions/MissingVNFDataInAAIException.java | 36 ++ .../exceptions/RequestExpiredException.java | 32 + .../exceptions/VNFNotFoundException.java | 32 + .../exceptions/WorkflowNotFoundException.java | 37 ++ .../requesthandler/helper/RequestRegistry.java | 93 +++ .../requesthandler/helper/RequestValidator.java | 42 ++ .../impl/AbstractRequestHandlerImpl.java | 626 ++++++++++++++++++++ .../impl/AbstractRequestValidatorImpl.java | 328 +++++++++++ .../requesthandler/impl/DmaapOutgoingMessage.java | 150 +++++ .../requesthandler/impl/LCMStateManagerImpl.java | 65 +++ .../requesthandler/impl/RequestHandlerImpl.java | 235 ++++++++ .../requesthandler/impl/RequestValidatorImpl.java | 132 +++++ .../requesthandler/impl/VMRequestHandlerImpl.java | 41 ++ .../impl/VMRequestValidatorImpl.java | 83 +++ .../workingstatemanager/WorkingStateManager.java | 51 ++ .../impl/JdbcWorkingStateManager.java | 47 ++ .../impl/RequestHandlerMessages.java | 31 + .../impl/WorkingStateManagerImpl.java | 231 ++++++++ .../objects/VNFWorkingState.java | 33 ++ .../objects/VnfWorkingStateDto.java | 93 +++ .../appc/messageadapter/MessageAdapter.java | 43 -- .../messageadapter/impl/MessageAdapterImpl.java | 139 ----- .../appc/requesthandler/constant/Constants.java | 36 -- .../appc/requesthandler/conv/Converter.java | 411 ------------- .../exceptions/DGWorkflowNotFoundException.java | 38 -- .../exceptions/DuplicateRequestException.java | 32 - .../exceptions/InvalidInputException.java | 32 - .../exceptions/LCMOperationsDisabledException.java | 39 -- .../exceptions/MissingVNFDataInAAIException.java | 36 -- .../exceptions/RequestExpiredException.java | 32 - .../exceptions/VNFNotFoundException.java | 32 - .../exceptions/WorkflowNotFoundException.java | 37 -- .../requesthandler/helper/RequestRegistry.java | 93 --- .../requesthandler/helper/RequestValidator.java | 42 -- .../impl/AbstractRequestHandlerImpl.java | 626 -------------------- .../impl/AbstractRequestValidatorImpl.java | 328 ----------- .../requesthandler/impl/DmaapOutgoingMessage.java | 150 ----- .../requesthandler/impl/LCMStateManagerImpl.java | 65 --- .../requesthandler/impl/RequestHandlerImpl.java | 235 -------- .../requesthandler/impl/RequestValidatorImpl.java | 132 ----- .../requesthandler/impl/VMRequestHandlerImpl.java | 41 -- .../impl/VMRequestValidatorImpl.java | 83 --- .../workingstatemanager/WorkingStateManager.java | 51 -- .../impl/JdbcWorkingStateManager.java | 47 -- .../impl/RequestHandlerMessages.java | 31 - .../impl/WorkingStateManagerImpl.java | 231 -------- .../objects/VNFWorkingState.java | 33 -- .../objects/VnfWorkingStateDto.java | 93 --- .../resources/org/onap/appc/default.properties | 49 ++ .../org/openecomp/appc/default.properties | 49 -- .../requesthandler/LCMStateManagerImplTest.java | 58 ++ .../appc/requesthandler/RequestValidatorTest.java | 570 ++++++++++++++++++ .../onap/appc/requesthandler/TestConverter.java | 372 ++++++++++++ .../appc/requesthandler/TestRequestHandler.java | 649 +++++++++++++++++++++ .../TestWorkingStateManager.java | 113 ++++ .../requesthandler/LCMStateManagerImplTest.java | 58 -- .../appc/requesthandler/RequestValidatorTest.java | 570 ------------------ .../appc/requesthandler/TestConverter.java | 372 ------------ .../appc/requesthandler/TestRequestHandler.java | 649 --------------------- .../TestWorkingStateManager.java | 113 ---- .../resources/org/onap/appc/default.properties | 98 ++++ .../org/openecomp/appc/default.properties | 98 ---- 70 files changed, 5097 insertions(+), 5097 deletions(-) create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java create mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties delete mode 100644 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties (limited to 'appc-dispatcher/appc-request-handler/appc-request-handler-core/src') diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java new file mode 100644 index 000000000..15e8d2436 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/MessageAdapter.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.messageadapter; + +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; + +public interface MessageAdapter { + /** + * Initialize dmaapProducer client to post messages using configuration properties + */ + void init(); + + /** + * 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 + */ + boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse); + +} 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 new file mode 100644 index 000000000..63a3c00a4 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.messageadapter.impl; + + +import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; +import org.onap.appc.adapter.factory.MessageService; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.messageadapter.MessageAdapter; +import org.onap.appc.requesthandler.conv.Converter; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.util.HashSet; +import java.util.Properties; + +public class MessageAdapterImpl implements MessageAdapter{ + + private MessageService messageService; + private Producer producer; + private String partition ; + private Configuration configuration; + private HashSet pool; + private String writeTopic; + private String apiKey; + private String apiSecret; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapterImpl.class); + + /** + * Initialize producer client to post messages using configuration properties + */ + @Override + public void init(){ + this.producer = getProducer(); + } + + private Producer getProducer() { + configuration = ConfigurationFactory.getConfiguration(); + Properties properties=configuration.getProperties(); + updateProperties(properties); + + BundleContext ctx = FrameworkUtil.getBundle(MessageAdapterImpl.class).getBundleContext(); + if (ctx != null) { + ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); + if (svcRef != null) { + producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); + } + } + return producer; + } + + + private void updateProperties(Properties props) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to updateProperties with Properties = "+ ObjectUtils.toString(props)); + } + pool = new HashSet<>(); + if (props != null) { + // readTopic = props.getProperty("dmaap.topic.read"); + writeTopic = props.getProperty("appc.LCM.topic.write"); + apiKey = props.getProperty("appc.LCM.client.key"); + apiSecret = props.getProperty("appc.LCM.client.secret"); + messageService = MessageService.parse(props.getProperty("message.service.type")); + // READ_TIMEOUT = Integer.valueOf(props.getProperty("dmaap.topic.read.timeout", String.valueOf(READ_TIMEOUT))); + String hostnames = props.getProperty("appc.LCM.poolMembers"); + if (hostnames != null && !hostnames.isEmpty()) { + for (String name : hostnames.split(",")) { + pool.add(name); + } + } + } + } + + /** + * 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 + */ + @Override + public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse){ + boolean success; + if (logger.isTraceEnabled()) { + logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(asyncResponse)); + } + + String jsonMessage; + try { + jsonMessage = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse); + if (logger.isDebugEnabled()) { + logger.debug("DMaaP Response = " + jsonMessage); + } + success = producer.post(this.partition, jsonMessage); + } catch (JsonProcessingException e1) { + logger.error("Error generating Json from DMaaP message "+ e1.getMessage()); + success= false; + }catch (Exception e){ + logger.error("Error sending message to DMaaP "+e.getMessage()); + success= false; + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from post with (success = "+ ObjectUtils.toString(success)+")"); + } + return success; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java new file mode 100644 index 000000000..4015181a1 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.constant; + +import java.util.concurrent.TimeUnit; + +public class Constants { + + public static final int DEFAULT_TTL = 30; + public static final String SUCCESS_MSG="SUCCESS"; + public static final String FAILURE_MSG="FAILURE"; + public static final String DEFAULT_LOGGING_FLAG="true"; + public static final long DEFAULT_IDLE_TIMEOUT = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); +} 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 new file mode 100644 index 000000000..5a791711e --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java @@ -0,0 +1,411 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.conv; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.*; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeaderBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.FlagsBuilder; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; +import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; +import org.opendaylight.yangtools.concepts.Builder; +import org.opendaylight.yangtools.yang.binding.DataContainer; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.requesthandler.impl.DmaapOutgoingMessage; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + + +public class Converter { + public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + public static final String MODE_FLAG = "MODE"; + public static final String FORCE_FLAG = "FORCE"; + public static final String TTL_FLAG = "TTL"; + public final static String DMaaP_ROOT_VALUE = "output"; + private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(Converter.class); + static { + isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + public static Builder convAsyncResponseToBuilder(VNFOperation vnfOperation, String rpcName, ResponseContext response) { + Builder outObj = null; + if(response == null){ + throw new IllegalArgumentException("empty asyncResponse"); + } + if(vnfOperation == null){ + throw new IllegalArgumentException("empty asyncResponse.action"); + } + Action action = Action.valueOf(vnfOperation.name()); + CommonHeader commonHeader = convAsyncResponseTorev160108CommonHeader(response); + Status status = convAsyncResponseTorev160108Status(response); + Payload payload = convAsyncResponseTorev160108Payload(response); + switch (action){ + case Rollback: + outObj = new RollbackOutputBuilder(); + ((RollbackOutputBuilder)outObj).setCommonHeader(commonHeader); + ((RollbackOutputBuilder)outObj).setStatus(status); + return outObj; + case Snapshot: + outObj = new SnapshotOutputBuilder(); + ((SnapshotOutputBuilder)outObj).setCommonHeader(commonHeader); + ((SnapshotOutputBuilder)outObj).setStatus(status); + try { + ((SnapshotOutputBuilder) outObj).setSnapshotId(response.getAdditionalContext().get("output.snapshot-id")); + } catch (NullPointerException ignored) { + // in case of negative response, snapshotID does not populated, so just ignore NPL + } + return outObj; + case Audit: + outObj = new AuditOutputBuilder(); + ((AuditOutputBuilder)outObj).setCommonHeader(commonHeader); + ((AuditOutputBuilder)outObj).setStatus(status); + ((AuditOutputBuilder)outObj).setPayload(payload); + return outObj; + case HealthCheck: + outObj = new HealthCheckOutputBuilder(); + ((HealthCheckOutputBuilder)outObj).setCommonHeader(commonHeader); + ((HealthCheckOutputBuilder)outObj).setStatus(status); + return outObj; + case LiveUpgrade: + outObj = new LiveUpgradeOutputBuilder(); + ((LiveUpgradeOutputBuilder)outObj).setCommonHeader(commonHeader); + ((LiveUpgradeOutputBuilder)outObj).setStatus(status); + return outObj; + case Lock: + outObj = new LockOutputBuilder(); + ((LockOutputBuilder)outObj).setCommonHeader(commonHeader); + ((LockOutputBuilder)outObj).setStatus(status); + return outObj; + case Configure: + outObj = new ConfigureOutputBuilder(); + ((ConfigureOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigureOutputBuilder)outObj).setStatus(status); + ((ConfigureOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigModify: + outObj = new ConfigModifyOutputBuilder(); + ((ConfigModifyOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigModifyOutputBuilder)outObj).setStatus(status); + ((ConfigModifyOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigScaleOut: + outObj = new ConfigScaleoutOutputBuilder(); + ((ConfigScaleoutOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigScaleoutOutputBuilder)outObj).setStatus(status); + ((ConfigScaleoutOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigRestore: + outObj = new ConfigRestoreOutputBuilder(); + ((ConfigRestoreOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigRestoreOutputBuilder)outObj).setStatus(status); + ((ConfigRestoreOutputBuilder)outObj).setPayload(payload); + return outObj; + case SoftwareUpload: + outObj = new SoftwareUploadOutputBuilder(); + ((SoftwareUploadOutputBuilder)outObj).setCommonHeader(commonHeader); + ((SoftwareUploadOutputBuilder)outObj).setStatus(status); + return outObj; + case Stop: + outObj = new StopOutputBuilder(); + ((StopOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StopOutputBuilder)outObj).setStatus(status); + return outObj; + case Sync: + outObj = new SyncOutputBuilder(); + ((SyncOutputBuilder)outObj).setCommonHeader(commonHeader); + ((SyncOutputBuilder)outObj).setStatus(status); + ((SyncOutputBuilder)outObj).setPayload(payload); + return outObj; + case Terminate: + outObj = new TerminateOutputBuilder(); + ((TerminateOutputBuilder)outObj).setCommonHeader(commonHeader); + ((TerminateOutputBuilder)outObj).setStatus(status); + return outObj; + case Test: + outObj = new TestOutputBuilder(); + ((TestOutputBuilder)outObj).setCommonHeader(commonHeader); + ((TestOutputBuilder)outObj).setStatus(status); + return outObj; + case Unlock: + outObj = new UnlockOutputBuilder(); + ((UnlockOutputBuilder)outObj).setCommonHeader(commonHeader); + ((UnlockOutputBuilder)outObj).setStatus(status); + return outObj; + case Restart: + outObj = new RestartOutputBuilder(); + ((RestartOutputBuilder)outObj).setCommonHeader(commonHeader); + ((RestartOutputBuilder)outObj).setStatus(status); + return outObj; + case Rebuild: + outObj = new RebuildOutputBuilder(); + ((RebuildOutputBuilder)outObj).setCommonHeader(commonHeader); + ((RebuildOutputBuilder)outObj).setStatus(status); + return outObj; + case Migrate: + outObj = new MigrateOutputBuilder(); + ((MigrateOutputBuilder)outObj).setCommonHeader(commonHeader); + ((MigrateOutputBuilder)outObj).setStatus(status); + return outObj; + case Evacuate: + outObj = new EvacuateOutputBuilder(); + ((EvacuateOutputBuilder)outObj).setCommonHeader(commonHeader); + ((EvacuateOutputBuilder)outObj).setStatus(status); + return outObj; + case ConfigBackup: + outObj = new ConfigBackupOutputBuilder(); + ((ConfigBackupOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigBackupOutputBuilder)outObj).setStatus(status); + ((ConfigBackupOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigBackupDelete: + outObj = new ConfigBackupDeleteOutputBuilder(); + ((ConfigBackupDeleteOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigBackupDeleteOutputBuilder)outObj).setStatus(status); + ((ConfigBackupDeleteOutputBuilder)outObj).setPayload(payload); + return outObj; + case ConfigExport: + outObj = new ConfigExportOutputBuilder(); + ((ConfigExportOutputBuilder)outObj).setCommonHeader(commonHeader); + ((ConfigExportOutputBuilder)outObj).setStatus(status); + return outObj; + case Start: + outObj = new StartOutputBuilder(); + ((StartOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StartOutputBuilder)outObj).setStatus(status); + return outObj; + case StopApplication: + outObj = new StopApplicationOutputBuilder(); + ((StopApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StopApplicationOutputBuilder)outObj).setStatus(status); + return outObj; + case StartApplication: + outObj = new StartApplicationOutputBuilder(); + ((StartApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); + ((StartApplicationOutputBuilder)outObj).setStatus(status); + return outObj; + default: + throw new IllegalArgumentException(action+" action is not supported"); + } + } + + public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) { + Payload payload = null; + if(inObj.getPayload() != null) { + payload = new Payload(inObj.getPayload()); + } + return payload; + } + + public static String convPayloadObjectToJsonString(Object inObj) throws ParseException { + String payloadAsString = null; + if(inObj != null) { + + if(inObj instanceof String){ + payloadAsString = (String)inObj; + }else { + try { + ObjectMapper objectMapper = new ObjectMapper(); + payloadAsString = objectMapper.writeValueAsString(inObj); +// payloadAsString = objectMapper.writeValueAsString(payloadAsString); + } 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) { + StatusBuilder statusBuilder = new StatusBuilder(); + statusBuilder.setCode(inObj.getStatus().getCode()); + statusBuilder.setMessage(inObj.getStatus().getMessage()); + return statusBuilder.build(); + } + + public static CommonHeader convAsyncResponseTorev160108CommonHeader(ResponseContext inObj) { + CommonHeader outObj = null; + if(inObj == null){ + throw new IllegalArgumentException("empty asyncResponse"); + } + + CommonHeaderBuilder commonHeaderBuilder = new CommonHeaderBuilder(); + org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags commonHeaderFlags = null; + if(inObj.getCommonHeader().getFlags() != null){ + commonHeaderFlags = Converter.convFlagsMapTorev160108Flags(inObj.getCommonHeader().getFlags()); + commonHeaderBuilder.setFlags(commonHeaderFlags); + } + + + commonHeaderBuilder.setApiVer(inObj.getCommonHeader().getApiVer()); + commonHeaderBuilder.setRequestId(inObj.getCommonHeader().getRequestId()); + if(inObj.getCommonHeader().getSubRequestId() != null){ + commonHeaderBuilder.setSubRequestId(inObj.getCommonHeader().getSubRequestId()); + } + + if(inObj.getCommonHeader().getOriginatorId() != null){ + commonHeaderBuilder.setOriginatorId(inObj.getCommonHeader().getOriginatorId()); + } + + if(inObj.getCommonHeader().getTimeStamp() != null){ + String zuluTimestampStr = Converter.convDateToZuluString(Date.from(inObj.getCommonHeader().getTimeStamp())); + ZULU zuluTimestamp = new ZULU(zuluTimestampStr); + commonHeaderBuilder.setTimestamp(zuluTimestamp); + } + outObj = commonHeaderBuilder.build(); + return outObj; + + } + + public static String convDateToZuluString(Date timeStamp) { + return isoFormatter.format(timeStamp); + } + + 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) { + Flags rev160108flags = null; + 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. + */ + /* + 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()); + flagsBuilder.setForce(force); + anyFlag = true; + } + 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()); + flagsBuilder.setMode(mode); + anyFlag = true; + } + if(flags.containsKey(TTL_FLAG)){ + flagsBuilder.setTtl(Integer.valueOf(flags.get(TTL_FLAG).toString())); + anyFlag = true; + } + if(anyFlag){ + rev160108flags = flagsBuilder.build(); + } + */ + + rev160108flags = flagsBuilder.build(); + return rev160108flags; + } + + public static String convAsyncResponseToJsonStringBody(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { + Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); + Object message = builder.build(); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.addMixInAnnotations(message.getClass(), MixInFlagsMessage.class); + objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); + objectMapper.addMixInAnnotations(Flags.class, MixIn.class); + objectMapper.addMixInAnnotations(Status.class, MixIn.class); + objectMapper.addMixInAnnotations(Payload.class, MixIn.class); + objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); + +// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true) + .writer(SerializationFeature.WRAP_ROOT_VALUE).withRootName(DMaaP_ROOT_VALUE).withoutFeatures(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + return writer.writeValueAsString(message); + } + + public static String convAsyncResponseToDmaapOutgoingMessageJsonString(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { + DmaapOutgoingMessage dmaapOutgoingMessage = convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.addMixInAnnotations(dmaapOutgoingMessage.getBody().getOutput().getClass(), MixInFlagsMessage.class); + objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); + objectMapper.addMixInAnnotations(Flags.class, MixIn.class); + objectMapper.addMixInAnnotations(Status.class, MixIn.class); + objectMapper.addMixInAnnotations(Payload.class, MixIn.class); + objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); + +// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true).writer(); + return writer.writeValueAsString(dmaapOutgoingMessage); + } + + public static DmaapOutgoingMessage convAsyncResponseToDmaapOutgoingMessage(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { + DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); + String correlationID = getCorrelationID(asyncResponse); + outObj.setCorrelationID(correlationID); + outObj.setType("response"); + outObj.setRpcName(rpcName); + Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); + Object messageBody = builder.build(); + DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody); + outObj.setBody(body); + return outObj; + } + + private static String getCorrelationID(ResponseContext context) { + return context.getCommonHeader().getRequestId() + + (context.getCommonHeader().getSubRequestId() == null ? + "":"-" + context.getCommonHeader().getSubRequestId()); + } + + abstract class MixIn { + @JsonIgnore + abstract Class getImplementedInterface(); // to be removed during serialization + + @JsonValue + abstract java.lang.String getValue(); + } + abstract class MixInCommonHeader extends MixIn { + @JsonProperty("api-ver") + abstract java.lang.String getApiVer(); + @JsonProperty("originator-id") + abstract java.lang.String getOriginatorId(); + @JsonProperty("request-id") + abstract java.lang.String getRequestId(); + @JsonProperty("sub-request-id") + abstract java.lang.String getSubRequestId(); + + } + abstract class MixInFlagsMessage extends MixIn { + @JsonProperty("common-header") + abstract CommonHeader getCommonHeader(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java new file mode 100644 index 000000000..5626cfe6f --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class DGWorkflowNotFoundException extends Exception { + public final String workflowModule; + public final String workflowName; + public final String workflowVersion; + public DGWorkflowNotFoundException(String message,String workflowModule,String workflowName,String workflowVersion){ + super(message); + this.workflowModule = workflowModule; + this.workflowName = workflowName; + this.workflowVersion = workflowVersion; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java new file mode 100644 index 000000000..b06788a99 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class DuplicateRequestException extends Exception { + public DuplicateRequestException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java new file mode 100644 index 000000000..6e2435559 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class InvalidInputException extends Exception { + public InvalidInputException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java new file mode 100644 index 000000000..ca5f72682 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + +/** + */ +public class LCMOperationsDisabledException extends Exception { + + /** + * Constructs a new exception with the specified detail message. + * + * @param message the detail message. + */ + public LCMOperationsDisabledException(String message) { + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java new file mode 100644 index 000000000..219265084 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + +public class MissingVNFDataInAAIException extends Exception { + String missingAttributeName; + public MissingVNFDataInAAIException(String attributeName) { + this.missingAttributeName = attributeName; + } + + public String getMissingAttributeName() { + return missingAttributeName; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java new file mode 100644 index 000000000..02a130c8b --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class RequestExpiredException extends Exception { + public RequestExpiredException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java new file mode 100644 index 000000000..d1b2759d6 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class VNFNotFoundException extends Exception { + public VNFNotFoundException(String message){ + super(message); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java new file mode 100644 index 000000000..85157e32f --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.exceptions; + + +public class WorkflowNotFoundException extends Exception { + public final String vnfTypeVersion; + public final String command; + public WorkflowNotFoundException(String message,String vnfTypeVersion,String command){ + super(message); + this.vnfTypeVersion = vnfTypeVersion; + this.command = command; + } + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java new file mode 100644 index 000000000..fd1292ff9 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.helper; + +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Collections; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * This class serves as Request Registry, which holds the + * request unique parameters (originatorId,requestId,subRequestId) + * in memory. + */ +public class RequestRegistry { + + static Set set = Collections.newSetFromMap(new ConcurrentHashMap()); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestRegistry.class); + public RequestRegistry(){ + + } + + /** + * This method accepts unique request parameters and adds it to Request Registry + * if Registry already contains same parameters it returns false, + * else returns true. + * @param requestIdentifier + * @return + */ + public boolean registerRequest(UniqueRequestIdentifier requestIdentifier){ + + if (logger.isTraceEnabled()) { + logger.trace("Entering to registerRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); + } + boolean output = set.add(requestIdentifier); + logger.debug(" Output = " + output); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from registerRequest with (output = "+ ObjectUtils.toString(output)+")"); + } + return output; + } + + /** + * This method accepts unique request parameters and removes request + * from the Request Registry + * @param requestIdentifier + */ + public void removeRequest(UniqueRequestIdentifier requestIdentifier){ + if (logger.isTraceEnabled()) { + logger.trace("Entering to removeRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); + } + set.remove(requestIdentifier); + } + + /** + * This method returns the count of currently registered requests + * in the request registry + * * @return currently registered requests count + */ + public int getRegisteredRequestCount() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getRegisteredRequestCount"); + } + return set.size(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java new file mode 100644 index 000000000..e45341d3d --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.helper; + +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; +import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; +import org.onap.appc.requesthandler.exceptions.InvalidInputException; +import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; +import org.onap.appc.requesthandler.exceptions.MissingVNFDataInAAIException; +import org.onap.appc.requesthandler.exceptions.RequestExpiredException; +import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; +import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; + +public interface RequestValidator { + public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; +} 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 new file mode 100644 index 000000000..8b56dda41 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java @@ -0,0 +1,626 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.requesthandler.constant.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.*; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executor.CommandExecutor; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.messageadapter.MessageAdapter; +import org.onap.appc.messageadapter.impl.MessageAdapterImpl; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.MetricService; +import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; +import org.onap.appc.metricservice.metric.Metric; +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.policy.PublishingPolicy; +import org.onap.appc.metricservice.publisher.LogPublisher; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.requesthandler.helper.RequestRegistry; +import org.onap.appc.requesthandler.helper.RequestValidator; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.transactionrecorder.objects.TransactionRecord; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.MDC; + +import java.net.InetAddress; +import java.time.Instant; +import java.util.HashMap; +import java.util.Properties; + +import static com.att.eelf.configuration.Configuration.*; + +/** + * This class provides application logic for the Request/Response Handler Component. + * + */ +public abstract class AbstractRequestHandlerImpl implements RequestHandler { + + private RequestValidator requestValidator; + + + + private RequestRegistry requestRegistry; + + private CommandExecutor commandExecutor; + + private TransactionRecorder transactionRecorder; + + private MessageAdapter messageAdapter; + + private static MetricRegistry metricRegistry; + + private boolean isMetricEnabled = false; + + protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class); + + public AbstractRequestHandlerImpl() { + requestRegistry = new RequestRegistry(); + messageAdapter = new MessageAdapterImpl(); + messageAdapter.init(); + Properties properties = configuration.getProperties(); + if (properties != null && properties.getProperty("metric.enabled") != null) { + isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled")); + } + if (isMetricEnabled) { + initMetric(); + } + } + + public void setTransactionRecorder(TransactionRecorder transactionRecorder) { + this.transactionRecorder = transactionRecorder; + } + + public void setRequestValidator(RequestValidator requestValidator) { + this.requestValidator = requestValidator; + } + + public void setMessageAdapter(MessageAdapter messageAdapter) { + this.messageAdapter = messageAdapter; + } + + + + public void setRequestRegistry(RequestRegistry requestRegistry) { + this.requestRegistry = requestRegistry; + } + + public void setCommandExecutor(CommandExecutor commandExecutor) { + this.commandExecutor = commandExecutor; + } + + + /** + * It receives requests from the north-bound REST API (Communication) Layer and + * performs following validations. + * 1. VNF exists in A&AI for the given targetID (VnfID) + * 2. For the current VNF Orchestration Status, the command can be executed + * 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. + * @return response for request as enum with Return code and message. + */ + @Override + public RequestHandlerOutput handleRequest(RequestHandlerInput input) { + if (logger.isTraceEnabled()) + logger.trace("Entering to handleRequest with RequestHandlerInput = " + ObjectUtils.toString(input) + ")"); + Params params ; + String vnfId, vnfType = null, errorMessage = null; + Instant startTime = Instant.now(); + RequestHandlerOutput output = null; + setInitialLogProperties(input.getRequestContext()); + + RuntimeContext runtimeContext = new RuntimeContext(); + runtimeContext.setRequestContext(input.getRequestContext()); + runtimeContext.setTimeStart(startTime); + runtimeContext.setRpcName(input.getRpcName()); + + final ResponseContext responseContext = new ResponseContext(); + responseContext.setStatus(new Status(0,"")); + responseContext.setAdditionalContext(new HashMap<>(4)); + responseContext.setCommonHeader(input.getRequestContext().getCommonHeader()); + runtimeContext.setResponseContext(responseContext); + runtimeContext.getResponseContext().setStatus(new Status(0,"")); + + vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + + try { + + requestValidator.validateRequest(runtimeContext); + + handleRequest(runtimeContext); + + final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); + if (statusCode % 100 == 2 || statusCode % 100 == 3) { + createTransactionRecord(runtimeContext); + } + output = new RequestHandlerOutput(); + output.setResponseContext(runtimeContext.getResponseContext()); + + } catch (VNFNotFoundException e) { + errorMessage = e.getMessage(); + String logMessage = EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId); + storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.AAI, "", logMessage); + params = new Params().addParam("vnfId", vnfId); + output = buildRequestHandlerOutput(LCMCommandStatus.VNF_NOT_FOUND, params); + } catch (NoTransitionDefinedException e) { + errorMessage = e.getMessage(); + String logMessage = EELFResourceManager.format(Msg.VF_UNDEFINED_STATE, input.getRequestContext().getCommonHeader().getOriginatorId(), input.getRequestContext().getAction().name()); + params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); + output = buildRequestHandlerOutput(LCMCommandStatus.NO_TRANSITION_DEFINE, params); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.STATE_MACHINE, + logMessage); + } catch (LifecycleException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); + output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_VNF_STATE, params); + } catch (UnstableVNFException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("vnfId", vnfId); + output = buildRequestHandlerOutput(LCMCommandStatus.UNSTABLE_VNF, params); + } catch (WorkflowNotFoundException e) { + errorMessage = e.getMessage(); + String vnfTypeVersion = e.vnfTypeVersion; + params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("vnfTypeVersion", vnfTypeVersion); + output = buildRequestHandlerOutput(LCMCommandStatus.WORKFLOW_NOT_FOUND, params); + } catch (DGWorkflowNotFoundException e) { + errorMessage = e.getMessage(); + String logMessage = EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, input.getRequestContext().getAction().name()); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.WORKFLOW_MANAGER, + logMessage); + params = new Params().addParam("actionName", input.getRequestContext().getAction().name()) + .addParam("dgModule", e.workflowModule).addParam("dgName", e.workflowName).addParam("dgVersion", e.workflowVersion); + output = buildRequestHandlerOutput(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND, params); + } catch (RequestExpiredException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("actionName", input.getRequestContext().getAction().name()); + output = buildRequestHandlerOutput(LCMCommandStatus.EXPIRED_REQUEST, params); + } catch (InvalidInputException e) { + errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + params = new Params().addParam("errorMsg", errorMessage); + output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, params); + } catch (DuplicateRequestException e) { + errorMessage = e.getMessage(); + output = buildRequestHandlerOutput(LCMCommandStatus.DUPLICATE_REQUEST, null); + } catch (MissingVNFDataInAAIException e) { + params = new Params().addParam("attributeName",e.getMissingAttributeName()) + .addParam("vnfId",vnfId); + output = buildRequestHandlerOutput(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI,params); + errorMessage = output.getResponseContext().getStatus().getMessage(); + } catch (LCMOperationsDisabledException e) { + errorMessage = e.getMessage(); + params = new Params().addParam("errorMsg", errorMessage); + output = buildRequestHandlerOutput(LCMCommandStatus.REJECTED, params); + } catch (Exception e) { + storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage()); + errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + params = new Params().addParam("errorMsg", errorMessage); + output = buildRequestHandlerOutput(LCMCommandStatus.UNEXPECTED_ERROR, params); + } finally { + try { + if (logger.isDebugEnabled() && errorMessage != null) + logger.debug("error occurred in handleRequest " + errorMessage); + logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.ACCEPTED.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())); + logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.SUCCESS.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())); + + runtimeContext.setResponseContext(output.getResponseContext()); + if ((null == output) || !(output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())) { + if (isMetricEnabled) { + if((output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())) { + ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); + }else { + ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest(); + } + } + removeRequestFromRegistry(input.getRequestContext().getCommonHeader()); + } + } finally { + storeAuditLogRecord(runtimeContext); + storeMetricLogRecord(runtimeContext); + clearRequestLogProperties(); + } + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " + ObjectUtils.toString(output.getResponseContext()) + ")"); + } + return output; + } + + protected void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName, String additionalMessage) { + LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ? + String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "", + runtimeContext.getResponseContext().getStatus() != null ? + String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "", + targetEntity, + targetServiceName, + additionalMessage, + this.getClass().getCanonicalName()); + } + + private void createTransactionRecord(RuntimeContext runtimeContext) { + TransactionRecord transactionRecord = new TransactionRecord(); + transactionRecord.setTimeStamp(runtimeContext.getResponseContext().getCommonHeader().getTimeStamp()); + transactionRecord.setRequestID(runtimeContext.getResponseContext().getCommonHeader().getRequestId()); + transactionRecord.setStartTime(runtimeContext.getTimeStart()); + transactionRecord.setEndTime(Instant.now()); + transactionRecord.setTargetID(runtimeContext.getVnfContext().getId()); + transactionRecord.setTargetType(runtimeContext.getVnfContext().getType()); + transactionRecord.setOperation(runtimeContext.getRequestContext().getAction().name()); + transactionRecord.setResultCode(String.valueOf(runtimeContext.getResponseContext().getStatus().getCode())); + transactionRecord.setDescription(runtimeContext.getResponseContext().getStatus().getMessage()); + transactionRecorder.store(transactionRecord); + } + + protected abstract void handleRequest(RuntimeContext runtimeContext) ; + + protected void callWfOperation(RuntimeContext runtimeContext) { + int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader()); + if (remainingTTL > 0) { + if (logger.isDebugEnabled()) { + logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL); + } + + RuntimeContext clonedContext = cloneContext(runtimeContext); + + try { + commandExecutor.executeCommand(clonedContext); + if(logger.isTraceEnabled()) { + logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId())); + } + fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null); + if (isMetricEnabled) { + ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); + } + } catch (APPCException e) { + String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); + Params params = new Params().addParam("errorMsg", errorMessage); + fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params); + } + + } else { + fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.REQUEST_HANDLER, + EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST, + runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(), + runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(), + String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl()))); + } + } + + protected void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) { + runtimeContext.getResponseContext().setStatus(new Status(lcmCommandStatus.getResponseCode(),lcmCommandStatus.getFormattedMessage(params))); + } + + /* + * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted + * status code and other - depending on DG status). Other properties should not be a problem + */ + private RuntimeContext cloneContext(RuntimeContext runtimeContext) { + RuntimeContext other = new RuntimeContext(); + other.setRequestContext(runtimeContext.getRequestContext()); + other.setResponseContext(new ResponseContext()); + other.getResponseContext().setStatus(new Status(0,"")); + other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader()); + other.setVnfContext(runtimeContext.getVnfContext()); + other.setRpcName(runtimeContext.getRpcName()); + other.setTimeStart(runtimeContext.getTimeStart()); + other.setIsLockAcquired(runtimeContext.isLockAcquired()); + return other; + } + + + private void clearRequestLogProperties() { + try { + MDC.remove(MDC_KEY_REQUEST_ID); + MDC.remove(MDC_SERVICE_INSTANCE_ID); + MDC.remove(MDC_SERVICE_NAME); + MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME); + MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY); + } catch (Exception e) { + //do nothing + } + } + + private void removeRequestFromRegistry(CommonHeader commonHeader) { + if (logger.isTraceEnabled()) + logger.trace("Entering to removeRequestFromRegistry with RequestHeader = " + ObjectUtils.toString(commonHeader)); + requestRegistry.removeRequest( + new UniqueRequestIdentifier(commonHeader.getOriginatorId(), + commonHeader.getRequestId(), + commonHeader.getSubRequestId())); + } + + + private void setInitialLogProperties(RequestContext requestContext) { + + try { + MDC.put(MDC_KEY_REQUEST_ID, requestContext.getCommonHeader().getRequestId()); + if (requestContext.getActionIdentifiers().getServiceInstanceId() != null) { + MDC.put(MDC_SERVICE_INSTANCE_ID, requestContext.getActionIdentifiers().getServiceInstanceId()); + } + MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, requestContext.getCommonHeader().getOriginatorId()); + MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future + try { + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong! + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name()); + MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId()); + + } catch (Exception e) { + logger.debug(e.getMessage()); + } + } catch (RuntimeException e) { + //ignore + } + } + + + private int calculateRemainingTTL(CommonHeader commonHeader) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader)); + } + long usedTimeInMillis = (System.currentTimeMillis() - commonHeader.getTimeStamp().toEpochMilli()); + logger.debug("usedTimeInMillis = " + usedTimeInMillis); + int usedTimeInSeconds = Math.round(usedTimeInMillis / 1000); + logger.debug("usedTimeInSeconds = " + usedTimeInSeconds); + Integer inputTTL = this.getInputTTL(commonHeader); + logger.debug("inputTTL = " + inputTTL); + Integer remainingTTL = inputTTL - usedTimeInSeconds; + logger.debug("Remaining TTL = " + remainingTTL); + if (logger.isTraceEnabled()) + logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")"); + return remainingTTL; + } + + private Integer getInputTTL(CommonHeader header) { + if (logger.isTraceEnabled()) + logger.trace("Entering in getInputTTL with RequestHeader = " + ObjectUtils.toString(header)); + if (!isValidTTL(String.valueOf(header.getFlags().getTtl()))) { + String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); + Integer defaultTTL = Integer.parseInt(defaultTTLStr); + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (defaultTTL = " + ObjectUtils.toString(defaultTTL) + ")"); + return defaultTTL; + } + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (inputTTL = " + ObjectUtils.toString(header.getFlags().getTtl()) + ")"); + + return header.getFlags().getTtl(); + } + + private boolean isValidTTL(String ttl) { + if (ttl == null || ttl.length() == 0) { + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (result = false)"); + return false; + } + try { + Integer i = Integer.parseInt(ttl); + return (i > 0); + } catch (NumberFormatException e) { + if (logger.isTraceEnabled()) + logger.trace("Exiting from getInputTTL with (result = false)"); + return false; + } + } + + private Boolean isLoggingEnabled() { + String defaultFlagStr = configuration.getProperty("org.onap.appc.localTransactionRecorder.enable", String.valueOf(Constants.DEFAULT_LOGGING_FLAG)); + return Boolean.parseBoolean(defaultFlagStr); + } + + private static RequestHandlerOutput buildRequestHandlerOutput(LCMCommandStatus response, Params params) { + RequestHandlerOutput output = new RequestHandlerOutput(); + ResponseContext responseContext = new ResponseContext(); + org.onap.appc.domainmodel.lcm.Status status = new org.onap.appc.domainmodel.lcm.Status(response.getResponseCode(),response.getFormattedMessage(params)); + responseContext.setStatus(status); + output.setResponseContext(responseContext); + return output; + } + + /** + * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. + * + * @param vnfId String of VNF ID + * @param readOnlyActivity boolean indicator + * @param requestIdentifierString - string contains id uniquely represents the request + * @param forceFlag boolean indicator + * @throws UnstableVNFException when failed + */ + @Override + public abstract void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException ; + + /** + * This method perform following operations required after execution of workflow. + * It posts asynchronous response to message bus (DMaaP). + * Unlock VNF Id + * Removes request from request registry. + * Generate audit logs. + * Adds transaction record to database id if transaction logging is enabled. + * + * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion. + */ + @Override + public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " + ObjectUtils.toString(runtimeContext)); + } + + postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); + requestRegistry.removeRequest( + new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), + runtimeContext.getResponseContext().getCommonHeader().getRequestId(), + runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); + + storeAuditLogRecord(runtimeContext); + if (isLoggingEnabled()) { + createTransactionRecord(runtimeContext); + } + } + + private void storeAuditLogRecord(RuntimeContext runtimeContext) { + LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(), + 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()); + } + + + + + private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " + ObjectUtils.toString(responseContext)); + } + boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext); + if (!callbackResponse) { + logger.error("DMaaP posting status: " + callbackResponse, "dmaapMessage: " + responseContext); + } + if (logger.isTraceEnabled()) + logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " + ObjectUtils.toString(callbackResponse) + ")"); + } + + /** + * This method perform following operations required if TTL ends when request still waiting in execution queue . + * It posts asynchronous response to message bus (DMaaP). + * Unlock VNF Id + * Removes request from request registry. + * + * @param runtimeContext AsyncResponse object which contains VNF Id , timestamp , apiVersion, responseId, executionSuccess, payload, isExpired, action, startTime, vnfType, originatorId, subResponseId; + * @param updateAAI boolean flag which indicate AAI upodate status after request completion. + */ + @Override + public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to onRequestTTLEnd with " + + "AsyncResponse = " + ObjectUtils.toString(runtimeContext) + + ", updateAAI = " + ObjectUtils.toString(updateAAI)); + } + logger.error(LCMCommandStatus.EXPIRED_REQUEST_FAILURE.getResponseMessage()); + fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST_FAILURE, null); + postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); + + requestRegistry.removeRequest( + new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), + runtimeContext.getResponseContext().getCommonHeader().getRequestId(), + runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); + } + + private void initMetric() { + if (logger.isDebugEnabled()) + logger.debug("Metric getting initialized"); + MetricService metricService = getMetricservice(); + metricRegistry = metricService.createRegistry("APPC"); + 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(); + if (logger.isDebugEnabled()) + logger.debug("Policy getting initialized"); + manuallyScheduledPublishingPolicy.init(); + if (logger.isDebugEnabled()) + logger.debug("Metric initialized"); + } + } + + + private MetricService getMetricservice() { + BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); + if (sref != null) { + logger.info("Metric Service from bundlecontext"); + return (MetricService) bctx.getService(sref); + } else { + logger.info("Metric Service error from bundlecontext"); + logger.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); + return null; + } + } + + /** + * This method returns the count of in progress requests + * * @return in progress requests count + */ + @Override + public int getInprogressRequestCount() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getInprogressRequestCount"); + } + return requestRegistry.getRegisteredRequestCount(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java new file mode 100644 index 000000000..4f4942b8a --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java @@ -0,0 +1,328 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.appc.requesthandler.constant.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.requesthandler.helper.RequestRegistry; +import org.onap.appc.requesthandler.helper.RequestValidator; +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.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 java.time.Instant; +import java.util.Calendar; +import java.util.Date; + +public abstract class AbstractRequestValidatorImpl implements RequestValidator { + + protected final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class); + private final Configuration configuration = ConfigurationFactory.getConfiguration(); + protected LifecycleManager lifecyclemanager; + protected LCMStateManager lcmStateManager; + private AAIService aaiService; + private WorkFlowManager workflowManager; + private RequestRegistry requestRegistry = new RequestRegistry(); + + protected static Calendar DateToCalendar(Date date) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + return cal; + } + + public void setWorkflowManager(WorkFlowManager workflowManager) { + this.workflowManager = workflowManager; + } + + public void setLcmStateManager(LCMStateManager lcmStateManager) { + this.lcmStateManager = lcmStateManager; + } + + public void setRequestRegistry(RequestRegistry requestRegistry) { + this.requestRegistry = requestRegistry; + } + + public abstract void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; + + private boolean isValidTTL(String ttl) { + if (logger.isTraceEnabled()){ + logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl)); + } + if (ttl == null || ttl.length() == 0) { + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")"); + } + return false; + } + try { + Integer i = Integer.parseInt(ttl); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")"); + } + return (i > 0); + } catch (NumberFormatException e) { + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")"); + } + return false; + } + } + + protected void getAAIservice() { + BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); + // Get AAIadapter reference + ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); + if (sref != null) { + logger.info("AAIService from bundlecontext"); + aaiService = (AAIService) bctx.getService(sref); + + } else { + logger.info("AAIService error from bundlecontext"); + logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService"); + + } + } + + protected VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException { + SvcLogicContext ctx = new SvcLogicContext(); + ctx = getVnfdata(vnfId, "vnf", ctx); + + VNFContext vnfContext = new VNFContext(); + populateVnfContext(vnfContext, ctx); + + return vnfContext; + } + + protected void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { + + checkWorkflowExists(vnfContext, requestContext); + } + + private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { + + WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext)); + if (!workflowExistsOutput.isMappingExist()) { + if (logger.isDebugEnabled()) { + logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()); + } + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.WORKFLOW_MANAGER, + EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), + this.getClass().getCanonicalName()); + + + throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name()); + } + if (!workflowExistsOutput.isDgExist()) { + if (logger.isDebugEnabled()) { + logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput); + } + + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.WORKFLOW_MANAGER, + EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), + this.getClass().getCanonicalName()); + + + throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(), + workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion()); + } + } + + private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException { + String vnfType = ctx.getAttribute("vnf.vnf-type"); + String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status"); + if(StringUtils.isEmpty(vnfType)){ + throw new MissingVNFDataInAAIException("vnf-type"); + } + else if(StringUtils.isEmpty(orchestrationStatus)){ + throw new MissingVNFDataInAAIException("orchestration-status"); + } + vnfContext.setType(vnfType); + vnfContext.setStatus(orchestrationStatus); + vnfContext.setId(ctx.getAttribute("vnf.vnf-id")); + } + + private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) { + + WorkflowRequest workflowRequest = new WorkflowRequest(); + workflowRequest.setVnfContext(vnfContext); + workflowRequest.setRequestContext(requestContext); + if (logger.isTraceEnabled()) { + logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")"); + } + return workflowRequest; + } + + protected void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header)); + } + + UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId()); + boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier); + if (!requestAccepted) { + if (logger.isDebugEnabled()) { + logger.debug("Duplicate Request with " + requestIdentifier); + } + throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier); + } + } + + protected Integer readTTL(CommonHeader header) { + if (logger.isTraceEnabled()) { + logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header)); + } + if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) { + String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); + return Integer.parseInt(defaultTTLStr); + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from readTTL with (TTL = "+ ObjectUtils.toString(header.getFlags().getTtl())+")"); + } + return header.getFlags().getTtl(); + } + + private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx)); + } + + String key = "vnf-id = '" + vnf_id + "'"; + logger.debug("inside getVnfdata=== " + key); + try { + Instant beginTimestamp = Instant.now(); + SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx); + Instant endTimestamp = Instant.now(); + String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR; + LoggingUtils.logMetricsMessage( + beginTimestamp, + endTimestamp, + LoggingConstants.TargetNames.AAI, + LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY, + status, + "", + response.name(), + this.getClass().getCanonicalName()); + if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { + throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id); + } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { + throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id); + } + logger.info("AAIResponse: " + response.toString()); + } catch (SvcLogicException e) { + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA, + "Error in getVnfdata" + e, + this.getClass().getCanonicalName()); + + throw new RuntimeException(e); + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")"); + } + return ctx; + } + + protected void validateInput(RequestContext requestContext) + throws RequestExpiredException, InvalidInputException, DuplicateRequestException { + if (logger.isTraceEnabled()){ + logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext)); + } + if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null + || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 || + null == requestContext.getCommonHeader().getApiVer()) { + if (logger.isDebugEnabled()) { + logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name()); + } + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + EELFResourceManager.format(Msg.APPC_INVALID_INPUT), + this.getClass().getCanonicalName()); + + throw new InvalidInputException("vnfID or command is null"); + } + CommonHeader commonHeader = requestContext.getCommonHeader(); + + checkForDuplicateRequest(commonHeader); + + Calendar inputTimeStamp = DateToCalendar(Date.from(commonHeader.getTimeStamp())); + Calendar currentTime = Calendar.getInstance(); + + // If input timestamp is of future, we reject the request + if (inputTimeStamp.getTime().getTime() > currentTime.getTime().getTime()) { + if (logger.isDebugEnabled()) { + logger.debug("Input Timestamp is of future = " + inputTimeStamp.getTime()); + } + throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime()); + } + Integer ttl = readTTL(commonHeader); + logger.debug("TTL value set to (seconds) : " + ttl); + inputTimeStamp.add(Calendar.SECOND, ttl); + if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) { + + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + "TTL Expired: Current time - " + currentTime.getTime().getTime() + " Request time: " + inputTimeStamp.getTime().getTime() + " with TTL value: " + ttl, + this.getClass().getCanonicalName()); + + throw new RequestExpiredException("TTL Expired"); + } + if (logger.isDebugEnabled()) { + logger.debug("Validation of the request is successful"); + } + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java new file mode 100644 index 000000000..0df57a754 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/DmaapOutgoingMessage.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +/** + * This class represents a message being sent out to DMaaP by APPC as async response. + * note the structure of this class must be adapted to the sync message sent to DMaaP represened in org.onap.appc.listener.LCM.domainmodel.DmaapOutgoingMessage + * + */ +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DmaapOutgoingMessage { + + @JsonProperty("version") + private String version; + + @JsonProperty("type") + private String type; + + @JsonProperty("correlation-id") + private String correlationID; + + private final static String defaultCambriaPartition = "MSO"; + @JsonProperty("cambria.partition") + private String cambriaPartition = defaultCambriaPartition; + + @JsonProperty("rpc-name") + private String rpcName; + + @JsonProperty("body") + private Body body; + + public DmaapOutgoingMessage() { + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCorrelationID() { + return correlationID; + } + + public void setCorrelationID(String correlationID) { + this.correlationID = correlationID; + } + + public String getCambriaPartition() { + return cambriaPartition; + } + + public void setCambriaPartition(String cambriaPartition) { + this.cambriaPartition = cambriaPartition; + } + + public String getRpcName() { + return rpcName; + } + + public void setRpcName(String rpcName) { + this.rpcName = rpcName; + } + + public Body getBody() { + return body; + } + + public void setBody(Body body) { + this.body = body; + } + + @Override + public String toString() { + return "DmaapOutgoingMessage{" + + "cambriaPartition='" + cambriaPartition + '\'' + + ", rpcName='" + rpcName + '\'' + + ", body=" + body + + '}'; + } + + @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Body { + public Body() { + } + + public Body(Object output) { + this.output = output; + } + + @JsonProperty("output") + private Object output; + + public Object getOutput() { + return output; + } + + public void setOutput(Object body) { + this.output = body; + } + + @Override + public String toString() { + return "Body{" + + "output=" + output + + '}'; + } + } +} + diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java new file mode 100644 index 000000000..276eaddab --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.concurrent.atomic.AtomicBoolean; + +import org.onap.appc.requesthandler.LCMStateManager; + +public class LCMStateManagerImpl implements LCMStateManager { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMStateManagerImpl.class); + private static AtomicBoolean isLCMEnabled = new AtomicBoolean(true); + + /** + * This method checks if the LCM operations are enabled or not + * * @return true if enabled else false + */ + public boolean isLCMOperationEnabled() { + return isLCMEnabled.get(); + } + + /** + * This method disables the LCM operations + */ + public void disableLCMOperations() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to disableLCMOperations"); + } + isLCMEnabled.set(false); + } + + /** + * This method enables the LCM operations + */ + public void enableLCMOperations() { + if (logger.isTraceEnabled()) { + logger.trace("Entering to enableLCMOperations"); + } + isLCMEnabled.set(true); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java new file mode 100644 index 000000000..1f07b277c --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.appc.requesthandler.constant.Constants; +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.UnstableVNFException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.executor.objects.UniqueRequestIdentifier; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.workingstatemanager.WorkingStateManager; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; + +/** + * This class provides application logic for the Request/Response Handler Component. + * + */ +public class RequestHandlerImpl extends AbstractRequestHandlerImpl { + + /** + * APP-C VNF lock idle timeout in milliseconds. Applied only when locking VNF using northbound API "lock" + */ + private static final String PROP_IDLE_TIMEOUT = "org.onap.appc.lock.idleTimeout"; + + private LockManager lockManager; + + private WorkingStateManager workingStateManager; + + public void setLockManager(LockManager lockManager) { + this.lockManager = lockManager; + } + + public void setWorkingStateManager(WorkingStateManager workingStateManager) { + this.workingStateManager = workingStateManager; + } + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class); + + protected void handleRequest(RuntimeContext runtimeContext) { + + switch (runtimeContext.getRequestContext().getAction()) { + case Lock: + try { + lockWithTimeout(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); + fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null); + } catch (LockException e) { + Params params = new Params().addParam("errorMsg", e.getMessage()); + fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); + storeErrorMessageToLog(runtimeContext, + LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.LOCK_MANAGER, + EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); + } + break; + + case Unlock: + try { + releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); + fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); + } catch (LockException e) { + //TODO add proper error code and message + // logger.error(EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); + Params params = new Params().addParam("errorMsg", e.getMessage()); + fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); + } + break; + + case CheckLock: + boolean isLocked = lockManager.isLocked(runtimeContext.getVnfContext().getId()); + fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); + runtimeContext.getResponseContext().addKeyValueToAdditionalContext("locked", String.valueOf(isLocked).toUpperCase()); + break; + default: + try { + boolean lockAcquired = acquireVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId(), 0); + runtimeContext.setIsLockAcquired(lockAcquired); + callWfOperation(runtimeContext); + } catch (LockException e) { + Params params = new Params().addParam("errorMsg", e.getMessage()); + fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); + } finally { + if (runtimeContext.isLockAcquired()) { + final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); + if (statusCode % 100 == 2 || statusCode % 100 == 3) { + try { + releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); + } catch (LockException e) { + logger.error("Error releasing the lock",e); + } + } + } + } + } + } + + private void releaseVNFLock(String vnfId, String transactionId) throws LockException { + lockManager.releaseLock(vnfId, transactionId); + logger.info("Lock released for vnfID = " + vnfId); + } + + protected void lockWithTimeout(String vnfId, String requestId) throws LockException { + long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT); + acquireVNFLock(vnfId, requestId, timeout); + } + + private boolean acquireVNFLock(String vnfID, String requestId, long timeout) throws LockException { + if (logger.isTraceEnabled()) + logger.trace("Entering to acquireVNFLock with vnfID = " + vnfID); + boolean lockAcquired = lockManager.acquireLock(vnfID, requestId, timeout); + if (lockAcquired) { + logger.info("Lock acquired for vnfID = " + vnfID); + } else { + logger.info("vnfID = " + vnfID + " was already locked"); + } + return lockAcquired; + } + + /** + * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. + * + * @param vnfId String of VNF ID + * @param readOnlyActivity boolean indicator + * @param requestIdentifierString - string contains id uniquely represents the request + * @param forceFlag boolean indicator + * @throws UnstableVNFException when failed + */ + @Override + public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to onRequestExecutionStart with vnfId = " + vnfId + "and requestIdentifierString = " + requestIdentifierString); + } + + if(!readOnlyActivity || !forceFlag || workingStateManager.isVNFStable(vnfId)) { + boolean updated = false; + try { + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, requestIdentifierString, forceFlag); + } catch (Exception e) { + logger.error("Error updating working state for vnf " + vnfId + e); + throw new RuntimeException(e); + } + if (!updated) { + throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); + } + } + + if (logger.isTraceEnabled()) + logger.trace("Exiting from onRequestExecutionStart "); + } + + private boolean isReadOnlyAction(VNFOperation action) { + if (VNFOperation.Sync.toString().equals(action) || + VNFOperation.Audit.toString().equals(action) || + VNFOperation.ConfigBackup.toString().equals(action) || + VNFOperation.ConfigBackupDelete.toString().equals(action) || + VNFOperation.ConfigExport.toString().equals(action)){ + return true; + } + return false; + } + + @Override + public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { + super.onRequestExecutionEnd(runtimeContext,isAAIUpdated); + VNFWorkingState workingState; + Status status = runtimeContext.getResponseContext().getStatus(); + if (status.getCode() == LCMCommandStatus.SUCCESS.getResponseCode() || isReadOnlyAction(runtimeContext.getRequestContext().getAction())) { + workingState = VNFWorkingState.STABLE; + } else { + workingState = VNFWorkingState.UNKNOWN; + } + + UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), + runtimeContext.getResponseContext().getCommonHeader().getRequestId(), + runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()); + + String requestIdentifierString = requestIdentifier.toIdentifierString(); + workingStateManager.setWorkingState(runtimeContext.getVnfContext().getId(), workingState, requestIdentifierString, false); + logger.debug("Reset lock for vnfId " + runtimeContext.getVnfContext().getId()); + resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); + } + + private void resetLock(String vnfId, String requestId, boolean lockAcquired, boolean resetLockTimeout) { + if (lockAcquired) { + try { + releaseVNFLock(vnfId, requestId); + } catch (LockException e) { + logger.error("Unlock VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); + } + } else if (resetLockTimeout) { + try { + // reset timeout to previous value + lockWithTimeout(vnfId, requestId); + } catch (LockException e) { + logger.error("Reset lock idle timeout for VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); + } + } + } + + @Override + public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { + super.onRequestTTLEnd(runtimeContext,updateAAI); + resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); + } +} 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 new file mode 100644 index 000000000..8724adc59 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.i18n.EELFResourceManager; +import org.apache.commons.lang.ObjectUtils; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.workingstatemanager.WorkingStateManager; + + +public class RequestValidatorImpl extends AbstractRequestValidatorImpl { + + private WorkingStateManager workingStateManager; + private LCMStateManager lcmStateManager; + + public void setLifecyclemanager(LifecycleManager lifecyclemanager) { + this.lifecyclemanager = lifecyclemanager; + } + + public void setWorkingStateManager(WorkingStateManager workingStateManager) { + this.workingStateManager = workingStateManager; + } + + public void setLcmStateManager(LCMStateManager lcmStateManager) { + this.lcmStateManager = lcmStateManager; + } + + public RequestValidatorImpl() { + } + + @Override + public void validateRequest(RuntimeContext runtimeContext) + throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, + DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, + DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + if (logger.isTraceEnabled()){ + logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext)); + } + if(!lcmStateManager.isLCMOperationEnabled()) { + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), + this.getClass().getCanonicalName()); + throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); + } + + getAAIservice(); + validateInput(runtimeContext.getRequestContext()); + checkVNFWorkingState(runtimeContext); + String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + VNFContext vnfContext = queryAAI(vnfId); + runtimeContext.setVnfContext(vnfContext); + + queryLCM(runtimeContext.getVnfContext().getStatus(), runtimeContext.getRequestContext().getAction()); + VNFOperation operation = runtimeContext.getRequestContext().getAction(); + if(!operation.isBuiltIn()) { + // for built-in operations skip WF presence check + queryWFM(vnfContext, runtimeContext.getRequestContext()); + } + } + + + private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException { + if (logger.isTraceEnabled()) { + logger.trace("Entering to queryLCM with Orchestration Status = "+ ObjectUtils.toString(orchestrationStatus)+ + ", command = "+ ObjectUtils.toString(action)); + } + + String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name()); + if (logger.isDebugEnabled()) { + logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")"); + } + return nextState; + } + + + private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException { + + if (logger.isTraceEnabled()) { + logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext())); + } + boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null && runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce(); + String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + + if (logger.isDebugEnabled()) { + logger.debug("forceFlag = " + forceFlag); + } + boolean isVNFStable = workingStateManager.isVNFStable(vnfId); + if (!isVNFStable && !forceFlag) { + if (logger.isDebugEnabled()) { + logger.debug("VNF is not stable for VNF ID = " + vnfId); + } + throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); + } + + } + + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java new file mode 100644 index 000000000..7e3917313 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.executor.UnstableVNFException; + +public class VMRequestHandlerImpl extends AbstractRequestHandlerImpl{ + + protected void handleRequest(RuntimeContext runtimeContext) { + runtimeContext.setIsLockAcquired(false); + callWfOperation(runtimeContext); + } + + @Override + public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { + + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java new file mode 100644 index 000000000..79f83fbc6 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import com.att.eelf.i18n.EELFResourceManager; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.i18n.Msg; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.logging.LoggingUtils; +import org.onap.appc.requesthandler.exceptions.*; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +public class VMRequestValidatorImpl extends AbstractRequestValidatorImpl { + + @Override + public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, InvalidInputException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException, DuplicateRequestException { + if(!lcmStateManager.isLCMOperationEnabled()) { + LoggingUtils.logErrorMessage( + LoggingConstants.TargetNames.REQUEST_VALIDATOR, + EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), + this.getClass().getCanonicalName()); + throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); + } + + getAAIservice(); + super.validateInput(runtimeContext.getRequestContext()); + String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); + + VNFContext vnfContext = queryAAI(vnfId); + runtimeContext.setVnfContext(vnfContext); + + VNFOperation operation = runtimeContext.getRequestContext().getAction(); + if(supportedVMLevelAction().contains(operation)) { + queryWFM(vnfContext, runtimeContext.getRequestContext()); + } + else{ + throw new LCMOperationsDisabledException("Action "+ operation.name() + " is not supported on VM level"); + } + } + + public Set supportedVMLevelAction(){ + Set vnfOperations = new HashSet<>(); + vnfOperations.add(VNFOperation.Start); + vnfOperations.add(VNFOperation.Stop); + vnfOperations.add(VNFOperation.Restart); + vnfOperations.add(VNFOperation.Rebuild); + vnfOperations.add(VNFOperation.Terminate); + vnfOperations.add(VNFOperation.Migrate); + vnfOperations.add(VNFOperation.Evacuate); + vnfOperations.add(VNFOperation.Snapshot); + return vnfOperations; + } + + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java new file mode 100644 index 000000000..e9b3d0f3a --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager; + +import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; + + +public interface WorkingStateManager { + + /** + * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. + * @param vnfId vnf Id to be verified for stable state + * @return True if vnf Exists and state is STABLE else False. + */ + public boolean isVNFStable(String vnfId); + + /** + * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or + * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. + * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. + * @param vnfId vnf Id to be updated + * @param workingState new working state + * @param ownerId + * @param forceFlag - force to update also on case given onwerId is different then the registered one + */ + public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag); + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java new file mode 100644 index 000000000..041cf7e84 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.impl; + +import java.sql.Connection; + +import org.onap.appc.dao.util.JdbcConnectionFactory; +import org.onap.appc.workingstatemanager.WorkingStateManager; + +public abstract class JdbcWorkingStateManager implements WorkingStateManager { + + private JdbcConnectionFactory connectionFactory; + + public void setConnectionFactory(JdbcConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } + + protected Connection openDbConnection() { + return connectionFactory.openDbConnection(); + } + + protected void closeDbConnection(Connection connection) { + connectionFactory.closeDbConnection(connection); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java new file mode 100644 index 000000000..206d57229 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.impl; + + +public class RequestHandlerMessages { + public final static String VNF_WORKING_STATE_UPDATED = "VNF WorkingState for vnfId ${vnfId} was updated to ${workingState} at attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; + public final static String VNF_WORKING_STATE_WAS_NOT_UPDATED = "VNF WorkingState for vnfId ${vnfId} was not updated to ${workingState} attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java new file mode 100644 index 000000000..e2fb3f298 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java @@ -0,0 +1,231 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.impl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.message.RequestHandlerMessages; +import org.onap.appc.util.MessageFormatter; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; +import org.onap.appc.workingstatemanager.objects.VnfWorkingStateDto; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang3.StringUtils; + + +public class WorkingStateManagerImpl extends JdbcWorkingStateManager { + + private static final String SQL_RETRIEVE_VNF_STATE_MANAGEMENT = "SELECT VNF_ID,STATE,OWNER_ID,UPDATED,VER FROM VNF_STATE_MANAGEMENT WHERE VNF_ID=?"; + private static final String SQL_INSERT_VNF_STATE_MANAGEMENT = "INSERT IGNORE INTO VNF_STATE_MANAGEMENT (VNF_ID,STATE,OWNER_ID,UPDATED,VER) VALUES (?, ?, ?, ?, ?)"; + private static final String SQL_UPDATE_VNF_STATE_MANAGEMENT = "UPDATE VNF_STATE_MANAGEMENT SET OWNER_ID=?, UPDATED=?, STATE=?, VER=? WHERE VNF_ID=? AND VER=?"; + private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; + private static int maxAttempts = ConfigurationFactory.getConfiguration().getIntegerProperty("org.onap.appc.workingstatemanager.maxAttempts",20); + + private static Map workingStateMap = new ConcurrentHashMap<>(); + private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkingStateManagerImpl.class); + + + /** + * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. + * @param vnfId vnf Id to be verified for stable state + * @return True if vnf Exists and state is STABLE else False. + */ + @Override + public boolean isVNFStable(String vnfId){ + if (logger.isTraceEnabled()) { + logger.trace("Entering to isVNFStable with vnfId = "+ vnfId); + } + Connection connection = null; + boolean vnfStable = false; + try { + connection = openDbConnection(); + VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); + vnfStable = isVNFStable(vnfWorkingStateDto); + } catch (SQLException e) { + String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); + throw new RuntimeException(errMsg); + } finally { + if(connection != null) { + closeDbConnection(connection); + } + } + if (logger.isTraceEnabled()) { + logger.trace("Exiting from isVNFStable for vnfId = "+ vnfId+" with Result = "+vnfStable); + } + return vnfStable; + } + + /** + * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or + * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. + * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. + * @param vnfId vnf Id to be updated + * @param workingState new working state + * @param ownerId + * @param forceFlag - force to update also on case given onwerId is different then the registered one + */ + @Override + public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag){ + boolean updated = false; + if (logger.isTraceEnabled()) { + logger.trace("Entering to setWorkingState with vnfId = "+ ObjectUtils.toString(vnfId)+ ", VNFWorkingState = " + workingState.name() + ", ownerId = "+ownerId+", forceFlag = "+forceFlag); + } + Connection connection = null; + try { + connection = openDbConnection(); + updated = setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag, maxAttempts); + } catch (SQLException e) { + String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); + throw new RuntimeException(errMsg); + } finally { + if(connection != null) { + closeDbConnection(connection); + } + } + + logger.trace("setWorkingState exit with output updated = "+updated); + return updated; + } + + public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag, int maxAttempts) throws SQLException { + return setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag,1,maxAttempts); + } + public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag,int attempt, int maxAttempts) throws SQLException { + boolean updated = false; + VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); + Long currentVersion = vnfWorkingStateDto != null ? vnfWorkingStateDto.getVer() : null; + if(forceFlag || isVNFStable(vnfWorkingStateDto) || + ( vnfWorkingStateDto != null && vnfWorkingStateDto.getOwnerId().equals(ownerId)) ) { + updated = storeWorkingStateIfSameVersion(connection, vnfId, workingState, ownerId, currentVersion); + + Params params = new Params().addParam("vnfId", vnfId).addParam("workingState",workingState.name()) + .addParam("attempt",attempt).addParam("maxAttempts",maxAttempts).addParam("ownerId",ownerId).addParam("forceFlag",forceFlag); + String logMessage; + if(updated) { + logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_UPDATED, params.getParams()); + }else { + logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_WAS_NOT_UPDATED, params.getParams()); + } + logger.debug(logMessage); + if(!updated && attempt= Long.MAX_VALUE) ? 1 : (currentVer + 1); + statement.setString(1, ownerId); + statement.setLong(2, getCurrentTime(connection)); + statement.setString(3, state); + statement.setLong(4, newVer); + statement.setString(5, vnfId); + statement.setLong(6, currentVer); + return (statement.executeUpdate() != 0); + } + } + + protected VnfWorkingStateDto retrieveVnfWorkingState(Connection connection, String vnfId) throws SQLException { + VnfWorkingStateDto res = null; + + try(PreparedStatement statement = connection.prepareStatement(SQL_RETRIEVE_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER + statement.setString(1, vnfId); + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = new VnfWorkingStateDto(vnfId); + String stateString = resultSet.getString(2); + VNFWorkingState vnfWorkingState = VNFWorkingState.valueOf(stateString); + res.setState(vnfWorkingState); + res.setOwnerId(resultSet.getString(3)); + res.setUpdated(resultSet.getLong(4)); + res.setVer(resultSet.getLong(5)); + } + } + } + return res; + } + + private long getCurrentTime(Connection connection) throws SQLException { + long res = -1; + if(connection != null) { + try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { + try(ResultSet resultSet = statement.executeQuery()) { + if(resultSet.next()) { + res = resultSet.getTimestamp(1).getTime(); + } + } + } + } + if(res == -1) { + res = System.currentTimeMillis(); + } + return res; + } + + protected boolean addVnfWorkingStateIfNotExists(Connection connection, String vnfId, String ownerId, String state) throws SQLException { + boolean added = false; + try(PreparedStatement statement = connection.prepareStatement(SQL_INSERT_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER + statement.setString(1, vnfId); + statement.setString(2, state); + statement.setString(3, ownerId); + statement.setLong(4, getCurrentTime(connection)); + statement.setLong(5, 1L); + int rowCount = statement.executeUpdate(); + added = rowCount != 0 ? true : false; + } + return added; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java new file mode 100644 index 000000000..9c638de20 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.objects; + + +public enum VNFWorkingState { + STABLE,UNSTABLE,UNKNOWN; + public String toString(){ + return this.name(); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java new file mode 100644 index 000000000..948d4ca59 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager.objects; + + +public class VnfWorkingStateDto { + private String vnfId; + private VNFWorkingState state; + private String ownerId; + private long updated; + private long ver; + + public VnfWorkingStateDto() { + } + + public VnfWorkingStateDto(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public VNFWorkingState getState() { + return state; + } + + public void setState(VNFWorkingState state) { + this.state = state; + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public long getUpdated() { + return updated; + } + + public void setUpdated(long updated) { + this.updated = updated; + } + + public long getVer() { + return ver; + } + + public void setVer(long ver) { + this.ver = ver; + } + + + @Override + public String toString() { + return "VnfWorkingStateDto{" + + "vnfId='" + vnfId + '\'' + + ", state=" + state + + ", ownerId='" + ownerId + '\'' + + ", updated=" + updated + + ", ver=" + ver + + '}'; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java deleted file mode 100644 index 15e8d2436..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/MessageAdapter.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.messageadapter; - -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; - -public interface MessageAdapter { - /** - * Initialize dmaapProducer client to post messages using configuration properties - */ - void init(); - - /** - * 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 - */ - boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse); - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java deleted file mode 100644 index 63a3c00a4..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/messageadapter/impl/MessageAdapterImpl.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.messageadapter.impl; - - -import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; -import org.onap.appc.adapter.factory.MessageService; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import com.fasterxml.jackson.core.JsonProcessingException; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.messageadapter.MessageAdapter; -import org.onap.appc.requesthandler.conv.Converter; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; - -import java.util.HashSet; -import java.util.Properties; - -public class MessageAdapterImpl implements MessageAdapter{ - - private MessageService messageService; - private Producer producer; - private String partition ; - private Configuration configuration; - private HashSet pool; - private String writeTopic; - private String apiKey; - private String apiSecret; - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapterImpl.class); - - /** - * Initialize producer client to post messages using configuration properties - */ - @Override - public void init(){ - this.producer = getProducer(); - } - - private Producer getProducer() { - configuration = ConfigurationFactory.getConfiguration(); - Properties properties=configuration.getProperties(); - updateProperties(properties); - - BundleContext ctx = FrameworkUtil.getBundle(MessageAdapterImpl.class).getBundleContext(); - if (ctx != null) { - ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName()); - if (svcRef != null) { - producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret); - } - } - return producer; - } - - - private void updateProperties(Properties props) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to updateProperties with Properties = "+ ObjectUtils.toString(props)); - } - pool = new HashSet<>(); - if (props != null) { - // readTopic = props.getProperty("dmaap.topic.read"); - writeTopic = props.getProperty("appc.LCM.topic.write"); - apiKey = props.getProperty("appc.LCM.client.key"); - apiSecret = props.getProperty("appc.LCM.client.secret"); - messageService = MessageService.parse(props.getProperty("message.service.type")); - // READ_TIMEOUT = Integer.valueOf(props.getProperty("dmaap.topic.read.timeout", String.valueOf(READ_TIMEOUT))); - String hostnames = props.getProperty("appc.LCM.poolMembers"); - if (hostnames != null && !hostnames.isEmpty()) { - for (String name : hostnames.split(",")) { - pool.add(name); - } - } - } - } - - /** - * 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 - */ - @Override - public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse){ - boolean success; - if (logger.isTraceEnabled()) { - logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(asyncResponse)); - } - - String jsonMessage; - try { - jsonMessage = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse); - if (logger.isDebugEnabled()) { - logger.debug("DMaaP Response = " + jsonMessage); - } - success = producer.post(this.partition, jsonMessage); - } catch (JsonProcessingException e1) { - logger.error("Error generating Json from DMaaP message "+ e1.getMessage()); - success= false; - }catch (Exception e){ - logger.error("Error sending message to DMaaP "+e.getMessage()); - success= false; - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from post with (success = "+ ObjectUtils.toString(success)+")"); - } - return success; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java deleted file mode 100644 index 4015181a1..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/constant/Constants.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.constant; - -import java.util.concurrent.TimeUnit; - -public class Constants { - - public static final int DEFAULT_TTL = 30; - public static final String SUCCESS_MSG="SUCCESS"; - public static final String FAILURE_MSG="FAILURE"; - public static final String DEFAULT_LOGGING_FLAG="true"; - public static final long DEFAULT_IDLE_TIMEOUT = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java deleted file mode 100644 index 5a791711e..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/conv/Converter.java +++ /dev/null @@ -1,411 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.conv; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.SerializationFeature; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.*; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeader; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.CommonHeaderBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.FlagsBuilder; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.Status; -import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.status.StatusBuilder; -import org.opendaylight.yangtools.concepts.Builder; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.onap.appc.domainmodel.lcm.ResponseContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.requesthandler.impl.DmaapOutgoingMessage; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - - -public class Converter { - public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - public static final String MODE_FLAG = "MODE"; - public static final String FORCE_FLAG = "FORCE"; - public static final String TTL_FLAG = "TTL"; - public final static String DMaaP_ROOT_VALUE = "output"; - private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(Converter.class); - static { - isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - public static Builder convAsyncResponseToBuilder(VNFOperation vnfOperation, String rpcName, ResponseContext response) { - Builder outObj = null; - if(response == null){ - throw new IllegalArgumentException("empty asyncResponse"); - } - if(vnfOperation == null){ - throw new IllegalArgumentException("empty asyncResponse.action"); - } - Action action = Action.valueOf(vnfOperation.name()); - CommonHeader commonHeader = convAsyncResponseTorev160108CommonHeader(response); - Status status = convAsyncResponseTorev160108Status(response); - Payload payload = convAsyncResponseTorev160108Payload(response); - switch (action){ - case Rollback: - outObj = new RollbackOutputBuilder(); - ((RollbackOutputBuilder)outObj).setCommonHeader(commonHeader); - ((RollbackOutputBuilder)outObj).setStatus(status); - return outObj; - case Snapshot: - outObj = new SnapshotOutputBuilder(); - ((SnapshotOutputBuilder)outObj).setCommonHeader(commonHeader); - ((SnapshotOutputBuilder)outObj).setStatus(status); - try { - ((SnapshotOutputBuilder) outObj).setSnapshotId(response.getAdditionalContext().get("output.snapshot-id")); - } catch (NullPointerException ignored) { - // in case of negative response, snapshotID does not populated, so just ignore NPL - } - return outObj; - case Audit: - outObj = new AuditOutputBuilder(); - ((AuditOutputBuilder)outObj).setCommonHeader(commonHeader); - ((AuditOutputBuilder)outObj).setStatus(status); - ((AuditOutputBuilder)outObj).setPayload(payload); - return outObj; - case HealthCheck: - outObj = new HealthCheckOutputBuilder(); - ((HealthCheckOutputBuilder)outObj).setCommonHeader(commonHeader); - ((HealthCheckOutputBuilder)outObj).setStatus(status); - return outObj; - case LiveUpgrade: - outObj = new LiveUpgradeOutputBuilder(); - ((LiveUpgradeOutputBuilder)outObj).setCommonHeader(commonHeader); - ((LiveUpgradeOutputBuilder)outObj).setStatus(status); - return outObj; - case Lock: - outObj = new LockOutputBuilder(); - ((LockOutputBuilder)outObj).setCommonHeader(commonHeader); - ((LockOutputBuilder)outObj).setStatus(status); - return outObj; - case Configure: - outObj = new ConfigureOutputBuilder(); - ((ConfigureOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigureOutputBuilder)outObj).setStatus(status); - ((ConfigureOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigModify: - outObj = new ConfigModifyOutputBuilder(); - ((ConfigModifyOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigModifyOutputBuilder)outObj).setStatus(status); - ((ConfigModifyOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigScaleOut: - outObj = new ConfigScaleoutOutputBuilder(); - ((ConfigScaleoutOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigScaleoutOutputBuilder)outObj).setStatus(status); - ((ConfigScaleoutOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigRestore: - outObj = new ConfigRestoreOutputBuilder(); - ((ConfigRestoreOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigRestoreOutputBuilder)outObj).setStatus(status); - ((ConfigRestoreOutputBuilder)outObj).setPayload(payload); - return outObj; - case SoftwareUpload: - outObj = new SoftwareUploadOutputBuilder(); - ((SoftwareUploadOutputBuilder)outObj).setCommonHeader(commonHeader); - ((SoftwareUploadOutputBuilder)outObj).setStatus(status); - return outObj; - case Stop: - outObj = new StopOutputBuilder(); - ((StopOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StopOutputBuilder)outObj).setStatus(status); - return outObj; - case Sync: - outObj = new SyncOutputBuilder(); - ((SyncOutputBuilder)outObj).setCommonHeader(commonHeader); - ((SyncOutputBuilder)outObj).setStatus(status); - ((SyncOutputBuilder)outObj).setPayload(payload); - return outObj; - case Terminate: - outObj = new TerminateOutputBuilder(); - ((TerminateOutputBuilder)outObj).setCommonHeader(commonHeader); - ((TerminateOutputBuilder)outObj).setStatus(status); - return outObj; - case Test: - outObj = new TestOutputBuilder(); - ((TestOutputBuilder)outObj).setCommonHeader(commonHeader); - ((TestOutputBuilder)outObj).setStatus(status); - return outObj; - case Unlock: - outObj = new UnlockOutputBuilder(); - ((UnlockOutputBuilder)outObj).setCommonHeader(commonHeader); - ((UnlockOutputBuilder)outObj).setStatus(status); - return outObj; - case Restart: - outObj = new RestartOutputBuilder(); - ((RestartOutputBuilder)outObj).setCommonHeader(commonHeader); - ((RestartOutputBuilder)outObj).setStatus(status); - return outObj; - case Rebuild: - outObj = new RebuildOutputBuilder(); - ((RebuildOutputBuilder)outObj).setCommonHeader(commonHeader); - ((RebuildOutputBuilder)outObj).setStatus(status); - return outObj; - case Migrate: - outObj = new MigrateOutputBuilder(); - ((MigrateOutputBuilder)outObj).setCommonHeader(commonHeader); - ((MigrateOutputBuilder)outObj).setStatus(status); - return outObj; - case Evacuate: - outObj = new EvacuateOutputBuilder(); - ((EvacuateOutputBuilder)outObj).setCommonHeader(commonHeader); - ((EvacuateOutputBuilder)outObj).setStatus(status); - return outObj; - case ConfigBackup: - outObj = new ConfigBackupOutputBuilder(); - ((ConfigBackupOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigBackupOutputBuilder)outObj).setStatus(status); - ((ConfigBackupOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigBackupDelete: - outObj = new ConfigBackupDeleteOutputBuilder(); - ((ConfigBackupDeleteOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigBackupDeleteOutputBuilder)outObj).setStatus(status); - ((ConfigBackupDeleteOutputBuilder)outObj).setPayload(payload); - return outObj; - case ConfigExport: - outObj = new ConfigExportOutputBuilder(); - ((ConfigExportOutputBuilder)outObj).setCommonHeader(commonHeader); - ((ConfigExportOutputBuilder)outObj).setStatus(status); - return outObj; - case Start: - outObj = new StartOutputBuilder(); - ((StartOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StartOutputBuilder)outObj).setStatus(status); - return outObj; - case StopApplication: - outObj = new StopApplicationOutputBuilder(); - ((StopApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StopApplicationOutputBuilder)outObj).setStatus(status); - return outObj; - case StartApplication: - outObj = new StartApplicationOutputBuilder(); - ((StartApplicationOutputBuilder)outObj).setCommonHeader(commonHeader); - ((StartApplicationOutputBuilder)outObj).setStatus(status); - return outObj; - default: - throw new IllegalArgumentException(action+" action is not supported"); - } - } - - public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) { - Payload payload = null; - if(inObj.getPayload() != null) { - payload = new Payload(inObj.getPayload()); - } - return payload; - } - - public static String convPayloadObjectToJsonString(Object inObj) throws ParseException { - String payloadAsString = null; - if(inObj != null) { - - if(inObj instanceof String){ - payloadAsString = (String)inObj; - }else { - try { - ObjectMapper objectMapper = new ObjectMapper(); - payloadAsString = objectMapper.writeValueAsString(inObj); -// payloadAsString = objectMapper.writeValueAsString(payloadAsString); - } 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) { - StatusBuilder statusBuilder = new StatusBuilder(); - statusBuilder.setCode(inObj.getStatus().getCode()); - statusBuilder.setMessage(inObj.getStatus().getMessage()); - return statusBuilder.build(); - } - - public static CommonHeader convAsyncResponseTorev160108CommonHeader(ResponseContext inObj) { - CommonHeader outObj = null; - if(inObj == null){ - throw new IllegalArgumentException("empty asyncResponse"); - } - - CommonHeaderBuilder commonHeaderBuilder = new CommonHeaderBuilder(); - org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags commonHeaderFlags = null; - if(inObj.getCommonHeader().getFlags() != null){ - commonHeaderFlags = Converter.convFlagsMapTorev160108Flags(inObj.getCommonHeader().getFlags()); - commonHeaderBuilder.setFlags(commonHeaderFlags); - } - - - commonHeaderBuilder.setApiVer(inObj.getCommonHeader().getApiVer()); - commonHeaderBuilder.setRequestId(inObj.getCommonHeader().getRequestId()); - if(inObj.getCommonHeader().getSubRequestId() != null){ - commonHeaderBuilder.setSubRequestId(inObj.getCommonHeader().getSubRequestId()); - } - - if(inObj.getCommonHeader().getOriginatorId() != null){ - commonHeaderBuilder.setOriginatorId(inObj.getCommonHeader().getOriginatorId()); - } - - if(inObj.getCommonHeader().getTimeStamp() != null){ - String zuluTimestampStr = Converter.convDateToZuluString(Date.from(inObj.getCommonHeader().getTimeStamp())); - ZULU zuluTimestamp = new ZULU(zuluTimestampStr); - commonHeaderBuilder.setTimestamp(zuluTimestamp); - } - outObj = commonHeaderBuilder.build(); - return outObj; - - } - - public static String convDateToZuluString(Date timeStamp) { - return isoFormatter.format(timeStamp); - } - - 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) { - Flags rev160108flags = null; - 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. - */ - /* - 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()); - flagsBuilder.setForce(force); - anyFlag = true; - } - 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()); - flagsBuilder.setMode(mode); - anyFlag = true; - } - if(flags.containsKey(TTL_FLAG)){ - flagsBuilder.setTtl(Integer.valueOf(flags.get(TTL_FLAG).toString())); - anyFlag = true; - } - if(anyFlag){ - rev160108flags = flagsBuilder.build(); - } - */ - - rev160108flags = flagsBuilder.build(); - return rev160108flags; - } - - public static String convAsyncResponseToJsonStringBody(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { - Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); - Object message = builder.build(); - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.addMixInAnnotations(message.getClass(), MixInFlagsMessage.class); - objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); - objectMapper.addMixInAnnotations(Flags.class, MixIn.class); - objectMapper.addMixInAnnotations(Status.class, MixIn.class); - objectMapper.addMixInAnnotations(Payload.class, MixIn.class); - objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); - -// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) - ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true) - .writer(SerializationFeature.WRAP_ROOT_VALUE).withRootName(DMaaP_ROOT_VALUE).withoutFeatures(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); - return writer.writeValueAsString(message); - } - - public static String convAsyncResponseToDmaapOutgoingMessageJsonString(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { - DmaapOutgoingMessage dmaapOutgoingMessage = convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse); - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.addMixInAnnotations(dmaapOutgoingMessage.getBody().getOutput().getClass(), MixInFlagsMessage.class); - objectMapper.addMixInAnnotations(CommonHeader.class, MixInCommonHeader.class); - objectMapper.addMixInAnnotations(Flags.class, MixIn.class); - objectMapper.addMixInAnnotations(Status.class, MixIn.class); - objectMapper.addMixInAnnotations(Payload.class, MixIn.class); - objectMapper.addMixInAnnotations(ZULU.class, MixIn.class); - -// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true) - ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true).writer(); - return writer.writeValueAsString(dmaapOutgoingMessage); - } - - public static DmaapOutgoingMessage convAsyncResponseToDmaapOutgoingMessage(VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse) throws JsonProcessingException { - DmaapOutgoingMessage outObj = new DmaapOutgoingMessage(); - String correlationID = getCorrelationID(asyncResponse); - outObj.setCorrelationID(correlationID); - outObj.setType("response"); - outObj.setRpcName(rpcName); - Builder builder = Converter.convAsyncResponseToBuilder(vnfOperation, rpcName, asyncResponse); - Object messageBody = builder.build(); - DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody); - outObj.setBody(body); - return outObj; - } - - private static String getCorrelationID(ResponseContext context) { - return context.getCommonHeader().getRequestId() - + (context.getCommonHeader().getSubRequestId() == null ? - "":"-" + context.getCommonHeader().getSubRequestId()); - } - - abstract class MixIn { - @JsonIgnore - abstract Class getImplementedInterface(); // to be removed during serialization - - @JsonValue - abstract java.lang.String getValue(); - } - abstract class MixInCommonHeader extends MixIn { - @JsonProperty("api-ver") - abstract java.lang.String getApiVer(); - @JsonProperty("originator-id") - abstract java.lang.String getOriginatorId(); - @JsonProperty("request-id") - abstract java.lang.String getRequestId(); - @JsonProperty("sub-request-id") - abstract java.lang.String getSubRequestId(); - - } - abstract class MixInFlagsMessage extends MixIn { - @JsonProperty("common-header") - abstract CommonHeader getCommonHeader(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java deleted file mode 100644 index 5626cfe6f..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class DGWorkflowNotFoundException extends Exception { - public final String workflowModule; - public final String workflowName; - public final String workflowVersion; - public DGWorkflowNotFoundException(String message,String workflowModule,String workflowName,String workflowVersion){ - super(message); - this.workflowModule = workflowModule; - this.workflowName = workflowName; - this.workflowVersion = workflowVersion; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java deleted file mode 100644 index b06788a99..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/DuplicateRequestException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class DuplicateRequestException extends Exception { - public DuplicateRequestException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java deleted file mode 100644 index 6e2435559..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/InvalidInputException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class InvalidInputException extends Exception { - public InvalidInputException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java deleted file mode 100644 index ca5f72682..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/LCMOperationsDisabledException.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - -/** - */ -public class LCMOperationsDisabledException extends Exception { - - /** - * Constructs a new exception with the specified detail message. - * - * @param message the detail message. - */ - public LCMOperationsDisabledException(String message) { - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java deleted file mode 100644 index 219265084..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - -public class MissingVNFDataInAAIException extends Exception { - String missingAttributeName; - public MissingVNFDataInAAIException(String attributeName) { - this.missingAttributeName = attributeName; - } - - public String getMissingAttributeName() { - return missingAttributeName; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java deleted file mode 100644 index 02a130c8b..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/RequestExpiredException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class RequestExpiredException extends Exception { - public RequestExpiredException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java deleted file mode 100644 index d1b2759d6..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/VNFNotFoundException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class VNFNotFoundException extends Exception { - public VNFNotFoundException(String message){ - super(message); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java deleted file mode 100644 index 85157e32f..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/exceptions/WorkflowNotFoundException.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.exceptions; - - -public class WorkflowNotFoundException extends Exception { - public final String vnfTypeVersion; - public final String command; - public WorkflowNotFoundException(String message,String vnfTypeVersion,String command){ - super(message); - this.vnfTypeVersion = vnfTypeVersion; - this.command = command; - } - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java deleted file mode 100644 index fd1292ff9..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestRegistry.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.helper; - -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.Collections; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * This class serves as Request Registry, which holds the - * request unique parameters (originatorId,requestId,subRequestId) - * in memory. - */ -public class RequestRegistry { - - static Set set = Collections.newSetFromMap(new ConcurrentHashMap()); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestRegistry.class); - public RequestRegistry(){ - - } - - /** - * This method accepts unique request parameters and adds it to Request Registry - * if Registry already contains same parameters it returns false, - * else returns true. - * @param requestIdentifier - * @return - */ - public boolean registerRequest(UniqueRequestIdentifier requestIdentifier){ - - if (logger.isTraceEnabled()) { - logger.trace("Entering to registerRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); - } - boolean output = set.add(requestIdentifier); - logger.debug(" Output = " + output); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from registerRequest with (output = "+ ObjectUtils.toString(output)+")"); - } - return output; - } - - /** - * This method accepts unique request parameters and removes request - * from the Request Registry - * @param requestIdentifier - */ - public void removeRequest(UniqueRequestIdentifier requestIdentifier){ - if (logger.isTraceEnabled()) { - logger.trace("Entering to removeRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier)); - } - set.remove(requestIdentifier); - } - - /** - * This method returns the count of currently registered requests - * in the request registry - * * @return currently registered requests count - */ - public int getRegisteredRequestCount() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getRegisteredRequestCount"); - } - return set.size(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java deleted file mode 100644 index e45341d3d..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/helper/RequestValidator.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.helper; - -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; -import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; -import org.onap.appc.requesthandler.exceptions.InvalidInputException; -import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; -import org.onap.appc.requesthandler.exceptions.MissingVNFDataInAAIException; -import org.onap.appc.requesthandler.exceptions.RequestExpiredException; -import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; -import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; - -public interface RequestValidator { - public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java deleted file mode 100644 index 8b56dda41..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java +++ /dev/null @@ -1,626 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.requesthandler.constant.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.*; -import org.onap.appc.exceptions.APPCException; -import org.onap.appc.executor.CommandExecutor; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.messageadapter.MessageAdapter; -import org.onap.appc.messageadapter.impl.MessageAdapterImpl; -import org.onap.appc.metricservice.MetricRegistry; -import org.onap.appc.metricservice.MetricService; -import org.onap.appc.metricservice.metric.DispatchingFuntionMetric; -import org.onap.appc.metricservice.metric.Metric; -import org.onap.appc.metricservice.metric.MetricType; -import org.onap.appc.metricservice.policy.PublishingPolicy; -import org.onap.appc.metricservice.publisher.LogPublisher; -import org.onap.appc.requesthandler.RequestHandler; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.requesthandler.helper.RequestRegistry; -import org.onap.appc.requesthandler.helper.RequestValidator; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.requesthandler.objects.RequestHandlerOutput; -import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.onap.appc.transactionrecorder.objects.TransactionRecord; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.time.Instant; -import java.util.HashMap; -import java.util.Properties; - -import static com.att.eelf.configuration.Configuration.*; - -/** - * This class provides application logic for the Request/Response Handler Component. - * - */ -public abstract class AbstractRequestHandlerImpl implements RequestHandler { - - private RequestValidator requestValidator; - - - - private RequestRegistry requestRegistry; - - private CommandExecutor commandExecutor; - - private TransactionRecorder transactionRecorder; - - private MessageAdapter messageAdapter; - - private static MetricRegistry metricRegistry; - - private boolean isMetricEnabled = false; - - protected static final Configuration configuration = ConfigurationFactory.getConfiguration(); - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class); - - public AbstractRequestHandlerImpl() { - requestRegistry = new RequestRegistry(); - messageAdapter = new MessageAdapterImpl(); - messageAdapter.init(); - Properties properties = configuration.getProperties(); - if (properties != null && properties.getProperty("metric.enabled") != null) { - isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled")); - } - if (isMetricEnabled) { - initMetric(); - } - } - - public void setTransactionRecorder(TransactionRecorder transactionRecorder) { - this.transactionRecorder = transactionRecorder; - } - - public void setRequestValidator(RequestValidator requestValidator) { - this.requestValidator = requestValidator; - } - - public void setMessageAdapter(MessageAdapter messageAdapter) { - this.messageAdapter = messageAdapter; - } - - - - public void setRequestRegistry(RequestRegistry requestRegistry) { - this.requestRegistry = requestRegistry; - } - - public void setCommandExecutor(CommandExecutor commandExecutor) { - this.commandExecutor = commandExecutor; - } - - - /** - * It receives requests from the north-bound REST API (Communication) Layer and - * performs following validations. - * 1. VNF exists in A&AI for the given targetID (VnfID) - * 2. For the current VNF Orchestration Status, the command can be executed - * 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. - * @return response for request as enum with Return code and message. - */ - @Override - public RequestHandlerOutput handleRequest(RequestHandlerInput input) { - if (logger.isTraceEnabled()) - logger.trace("Entering to handleRequest with RequestHandlerInput = " + ObjectUtils.toString(input) + ")"); - Params params ; - String vnfId, vnfType = null, errorMessage = null; - Instant startTime = Instant.now(); - RequestHandlerOutput output = null; - setInitialLogProperties(input.getRequestContext()); - - RuntimeContext runtimeContext = new RuntimeContext(); - runtimeContext.setRequestContext(input.getRequestContext()); - runtimeContext.setTimeStart(startTime); - runtimeContext.setRpcName(input.getRpcName()); - - final ResponseContext responseContext = new ResponseContext(); - responseContext.setStatus(new Status(0,"")); - responseContext.setAdditionalContext(new HashMap<>(4)); - responseContext.setCommonHeader(input.getRequestContext().getCommonHeader()); - runtimeContext.setResponseContext(responseContext); - runtimeContext.getResponseContext().setStatus(new Status(0,"")); - - vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - - try { - - requestValidator.validateRequest(runtimeContext); - - handleRequest(runtimeContext); - - final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); - if (statusCode % 100 == 2 || statusCode % 100 == 3) { - createTransactionRecord(runtimeContext); - } - output = new RequestHandlerOutput(); - output.setResponseContext(runtimeContext.getResponseContext()); - - } catch (VNFNotFoundException e) { - errorMessage = e.getMessage(); - String logMessage = EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId); - storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.AAI, "", logMessage); - params = new Params().addParam("vnfId", vnfId); - output = buildRequestHandlerOutput(LCMCommandStatus.VNF_NOT_FOUND, params); - } catch (NoTransitionDefinedException e) { - errorMessage = e.getMessage(); - String logMessage = EELFResourceManager.format(Msg.VF_UNDEFINED_STATE, input.getRequestContext().getCommonHeader().getOriginatorId(), input.getRequestContext().getAction().name()); - params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); - output = buildRequestHandlerOutput(LCMCommandStatus.NO_TRANSITION_DEFINE, params); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.STATE_MACHINE, - logMessage); - } catch (LifecycleException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState); - output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_VNF_STATE, params); - } catch (UnstableVNFException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("vnfId", vnfId); - output = buildRequestHandlerOutput(LCMCommandStatus.UNSTABLE_VNF, params); - } catch (WorkflowNotFoundException e) { - errorMessage = e.getMessage(); - String vnfTypeVersion = e.vnfTypeVersion; - params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("vnfTypeVersion", vnfTypeVersion); - output = buildRequestHandlerOutput(LCMCommandStatus.WORKFLOW_NOT_FOUND, params); - } catch (DGWorkflowNotFoundException e) { - errorMessage = e.getMessage(); - String logMessage = EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, input.getRequestContext().getAction().name()); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.WORKFLOW_MANAGER, - logMessage); - params = new Params().addParam("actionName", input.getRequestContext().getAction().name()) - .addParam("dgModule", e.workflowModule).addParam("dgName", e.workflowName).addParam("dgVersion", e.workflowVersion); - output = buildRequestHandlerOutput(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND, params); - } catch (RequestExpiredException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("actionName", input.getRequestContext().getAction().name()); - output = buildRequestHandlerOutput(LCMCommandStatus.EXPIRED_REQUEST, params); - } catch (InvalidInputException e) { - errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - params = new Params().addParam("errorMsg", errorMessage); - output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, params); - } catch (DuplicateRequestException e) { - errorMessage = e.getMessage(); - output = buildRequestHandlerOutput(LCMCommandStatus.DUPLICATE_REQUEST, null); - } catch (MissingVNFDataInAAIException e) { - params = new Params().addParam("attributeName",e.getMissingAttributeName()) - .addParam("vnfId",vnfId); - output = buildRequestHandlerOutput(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI,params); - errorMessage = output.getResponseContext().getStatus().getMessage(); - } catch (LCMOperationsDisabledException e) { - errorMessage = e.getMessage(); - params = new Params().addParam("errorMsg", errorMessage); - output = buildRequestHandlerOutput(LCMCommandStatus.REJECTED, params); - } catch (Exception e) { - storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage()); - errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - params = new Params().addParam("errorMsg", errorMessage); - output = buildRequestHandlerOutput(LCMCommandStatus.UNEXPECTED_ERROR, params); - } finally { - try { - if (logger.isDebugEnabled() && errorMessage != null) - logger.debug("error occurred in handleRequest " + errorMessage); - logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.ACCEPTED.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())); - logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.SUCCESS.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())); - - runtimeContext.setResponseContext(output.getResponseContext()); - if ((null == output) || !(output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())) { - if (isMetricEnabled) { - if((output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())) { - ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); - }else { - ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest(); - } - } - removeRequestFromRegistry(input.getRequestContext().getCommonHeader()); - } - } finally { - storeAuditLogRecord(runtimeContext); - storeMetricLogRecord(runtimeContext); - clearRequestLogProperties(); - } - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " + ObjectUtils.toString(output.getResponseContext()) + ")"); - } - return output; - } - - protected void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName, String additionalMessage) { - LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ? - String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "", - runtimeContext.getResponseContext().getStatus() != null ? - String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "", - targetEntity, - targetServiceName, - additionalMessage, - this.getClass().getCanonicalName()); - } - - private void createTransactionRecord(RuntimeContext runtimeContext) { - TransactionRecord transactionRecord = new TransactionRecord(); - transactionRecord.setTimeStamp(runtimeContext.getResponseContext().getCommonHeader().getTimeStamp()); - transactionRecord.setRequestID(runtimeContext.getResponseContext().getCommonHeader().getRequestId()); - transactionRecord.setStartTime(runtimeContext.getTimeStart()); - transactionRecord.setEndTime(Instant.now()); - transactionRecord.setTargetID(runtimeContext.getVnfContext().getId()); - transactionRecord.setTargetType(runtimeContext.getVnfContext().getType()); - transactionRecord.setOperation(runtimeContext.getRequestContext().getAction().name()); - transactionRecord.setResultCode(String.valueOf(runtimeContext.getResponseContext().getStatus().getCode())); - transactionRecord.setDescription(runtimeContext.getResponseContext().getStatus().getMessage()); - transactionRecorder.store(transactionRecord); - } - - protected abstract void handleRequest(RuntimeContext runtimeContext) ; - - protected void callWfOperation(RuntimeContext runtimeContext) { - int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader()); - if (remainingTTL > 0) { - if (logger.isDebugEnabled()) { - logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL); - } - - RuntimeContext clonedContext = cloneContext(runtimeContext); - - try { - commandExecutor.executeCommand(clonedContext); - if(logger.isTraceEnabled()) { - logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId())); - } - fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null); - if (isMetricEnabled) { - ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest(); - } - } catch (APPCException e) { - String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString(); - Params params = new Params().addParam("errorMsg", errorMessage); - fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params); - } - - } else { - fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.REQUEST_HANDLER, - EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST, - runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(), - runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(), - String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl()))); - } - } - - protected void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) { - runtimeContext.getResponseContext().setStatus(new Status(lcmCommandStatus.getResponseCode(),lcmCommandStatus.getFormattedMessage(params))); - } - - /* - * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted - * status code and other - depending on DG status). Other properties should not be a problem - */ - private RuntimeContext cloneContext(RuntimeContext runtimeContext) { - RuntimeContext other = new RuntimeContext(); - other.setRequestContext(runtimeContext.getRequestContext()); - other.setResponseContext(new ResponseContext()); - other.getResponseContext().setStatus(new Status(0,"")); - other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader()); - other.setVnfContext(runtimeContext.getVnfContext()); - other.setRpcName(runtimeContext.getRpcName()); - other.setTimeStart(runtimeContext.getTimeStart()); - other.setIsLockAcquired(runtimeContext.isLockAcquired()); - return other; - } - - - private void clearRequestLogProperties() { - try { - MDC.remove(MDC_KEY_REQUEST_ID); - MDC.remove(MDC_SERVICE_INSTANCE_ID); - MDC.remove(MDC_SERVICE_NAME); - MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME); - MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY); - } catch (Exception e) { - //do nothing - } - } - - private void removeRequestFromRegistry(CommonHeader commonHeader) { - if (logger.isTraceEnabled()) - logger.trace("Entering to removeRequestFromRegistry with RequestHeader = " + ObjectUtils.toString(commonHeader)); - requestRegistry.removeRequest( - new UniqueRequestIdentifier(commonHeader.getOriginatorId(), - commonHeader.getRequestId(), - commonHeader.getSubRequestId())); - } - - - private void setInitialLogProperties(RequestContext requestContext) { - - try { - MDC.put(MDC_KEY_REQUEST_ID, requestContext.getCommonHeader().getRequestId()); - if (requestContext.getActionIdentifiers().getServiceInstanceId() != null) { - MDC.put(MDC_SERVICE_INSTANCE_ID, requestContext.getActionIdentifiers().getServiceInstanceId()); - } - MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, requestContext.getCommonHeader().getOriginatorId()); - MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong! - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name()); - MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId()); - - } catch (Exception e) { - logger.debug(e.getMessage()); - } - } catch (RuntimeException e) { - //ignore - } - } - - - private int calculateRemainingTTL(CommonHeader commonHeader) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader)); - } - long usedTimeInMillis = (System.currentTimeMillis() - commonHeader.getTimeStamp().toEpochMilli()); - logger.debug("usedTimeInMillis = " + usedTimeInMillis); - int usedTimeInSeconds = Math.round(usedTimeInMillis / 1000); - logger.debug("usedTimeInSeconds = " + usedTimeInSeconds); - Integer inputTTL = this.getInputTTL(commonHeader); - logger.debug("inputTTL = " + inputTTL); - Integer remainingTTL = inputTTL - usedTimeInSeconds; - logger.debug("Remaining TTL = " + remainingTTL); - if (logger.isTraceEnabled()) - logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")"); - return remainingTTL; - } - - private Integer getInputTTL(CommonHeader header) { - if (logger.isTraceEnabled()) - logger.trace("Entering in getInputTTL with RequestHeader = " + ObjectUtils.toString(header)); - if (!isValidTTL(String.valueOf(header.getFlags().getTtl()))) { - String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); - Integer defaultTTL = Integer.parseInt(defaultTTLStr); - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (defaultTTL = " + ObjectUtils.toString(defaultTTL) + ")"); - return defaultTTL; - } - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (inputTTL = " + ObjectUtils.toString(header.getFlags().getTtl()) + ")"); - - return header.getFlags().getTtl(); - } - - private boolean isValidTTL(String ttl) { - if (ttl == null || ttl.length() == 0) { - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (result = false)"); - return false; - } - try { - Integer i = Integer.parseInt(ttl); - return (i > 0); - } catch (NumberFormatException e) { - if (logger.isTraceEnabled()) - logger.trace("Exiting from getInputTTL with (result = false)"); - return false; - } - } - - private Boolean isLoggingEnabled() { - String defaultFlagStr = configuration.getProperty("org.onap.appc.localTransactionRecorder.enable", String.valueOf(Constants.DEFAULT_LOGGING_FLAG)); - return Boolean.parseBoolean(defaultFlagStr); - } - - private static RequestHandlerOutput buildRequestHandlerOutput(LCMCommandStatus response, Params params) { - RequestHandlerOutput output = new RequestHandlerOutput(); - ResponseContext responseContext = new ResponseContext(); - org.onap.appc.domainmodel.lcm.Status status = new org.onap.appc.domainmodel.lcm.Status(response.getResponseCode(),response.getFormattedMessage(params)); - responseContext.setStatus(status); - output.setResponseContext(responseContext); - return output; - } - - /** - * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. - * - * @param vnfId String of VNF ID - * @param readOnlyActivity boolean indicator - * @param requestIdentifierString - string contains id uniquely represents the request - * @param forceFlag boolean indicator - * @throws UnstableVNFException when failed - */ - @Override - public abstract void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException ; - - /** - * This method perform following operations required after execution of workflow. - * It posts asynchronous response to message bus (DMaaP). - * Unlock VNF Id - * Removes request from request registry. - * Generate audit logs. - * Adds transaction record to database id if transaction logging is enabled. - * - * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion. - */ - @Override - public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " + ObjectUtils.toString(runtimeContext)); - } - - postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); - requestRegistry.removeRequest( - new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), - runtimeContext.getResponseContext().getCommonHeader().getRequestId(), - runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); - - storeAuditLogRecord(runtimeContext); - if (isLoggingEnabled()) { - createTransactionRecord(runtimeContext); - } - } - - private void storeAuditLogRecord(RuntimeContext runtimeContext) { - LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(), - 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()); - } - - - - - private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " + ObjectUtils.toString(responseContext)); - } - boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext); - if (!callbackResponse) { - logger.error("DMaaP posting status: " + callbackResponse, "dmaapMessage: " + responseContext); - } - if (logger.isTraceEnabled()) - logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " + ObjectUtils.toString(callbackResponse) + ")"); - } - - /** - * This method perform following operations required if TTL ends when request still waiting in execution queue . - * It posts asynchronous response to message bus (DMaaP). - * Unlock VNF Id - * Removes request from request registry. - * - * @param runtimeContext AsyncResponse object which contains VNF Id , timestamp , apiVersion, responseId, executionSuccess, payload, isExpired, action, startTime, vnfType, originatorId, subResponseId; - * @param updateAAI boolean flag which indicate AAI upodate status after request completion. - */ - @Override - public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to onRequestTTLEnd with " + - "AsyncResponse = " + ObjectUtils.toString(runtimeContext) + - ", updateAAI = " + ObjectUtils.toString(updateAAI)); - } - logger.error(LCMCommandStatus.EXPIRED_REQUEST_FAILURE.getResponseMessage()); - fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST_FAILURE, null); - postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext()); - - requestRegistry.removeRequest( - new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), - runtimeContext.getResponseContext().getCommonHeader().getRequestId(), - runtimeContext.getResponseContext().getCommonHeader().getSubRequestId())); - } - - private void initMetric() { - if (logger.isDebugEnabled()) - logger.debug("Metric getting initialized"); - MetricService metricService = getMetricservice(); - metricRegistry = metricService.createRegistry("APPC"); - 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(); - if (logger.isDebugEnabled()) - logger.debug("Policy getting initialized"); - manuallyScheduledPublishingPolicy.init(); - if (logger.isDebugEnabled()) - logger.debug("Metric initialized"); - } - } - - - private MetricService getMetricservice() { - BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext(); - ServiceReference sref = bctx.getServiceReference(MetricService.class.getName()); - if (sref != null) { - logger.info("Metric Service from bundlecontext"); - return (MetricService) bctx.getService(sref); - } else { - logger.info("Metric Service error from bundlecontext"); - logger.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService"); - return null; - } - } - - /** - * This method returns the count of in progress requests - * * @return in progress requests count - */ - @Override - public int getInprogressRequestCount() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getInprogressRequestCount"); - } - return requestRegistry.getRegisteredRequestCount(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java deleted file mode 100644 index 4f4942b8a..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java +++ /dev/null @@ -1,328 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.appc.requesthandler.constant.Constants; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.RequestContext; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.requesthandler.LCMStateManager; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.requesthandler.helper.RequestRegistry; -import org.onap.appc.requesthandler.helper.RequestValidator; -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.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 java.time.Instant; -import java.util.Calendar; -import java.util.Date; - -public abstract class AbstractRequestValidatorImpl implements RequestValidator { - - protected final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class); - private final Configuration configuration = ConfigurationFactory.getConfiguration(); - protected LifecycleManager lifecyclemanager; - protected LCMStateManager lcmStateManager; - private AAIService aaiService; - private WorkFlowManager workflowManager; - private RequestRegistry requestRegistry = new RequestRegistry(); - - protected static Calendar DateToCalendar(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return cal; - } - - public void setWorkflowManager(WorkFlowManager workflowManager) { - this.workflowManager = workflowManager; - } - - public void setLcmStateManager(LCMStateManager lcmStateManager) { - this.lcmStateManager = lcmStateManager; - } - - public void setRequestRegistry(RequestRegistry requestRegistry) { - this.requestRegistry = requestRegistry; - } - - public abstract void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException; - - private boolean isValidTTL(String ttl) { - if (logger.isTraceEnabled()){ - logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl)); - } - if (ttl == null || ttl.length() == 0) { - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")"); - } - return false; - } - try { - Integer i = Integer.parseInt(ttl); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")"); - } - return (i > 0); - } catch (NumberFormatException e) { - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")"); - } - return false; - } - } - - protected void getAAIservice() { - BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext(); - // Get AAIadapter reference - ServiceReference sref = bctx.getServiceReference(AAIService.class.getName()); - if (sref != null) { - logger.info("AAIService from bundlecontext"); - aaiService = (AAIService) bctx.getService(sref); - - } else { - logger.info("AAIService error from bundlecontext"); - logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService"); - - } - } - - protected VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException { - SvcLogicContext ctx = new SvcLogicContext(); - ctx = getVnfdata(vnfId, "vnf", ctx); - - VNFContext vnfContext = new VNFContext(); - populateVnfContext(vnfContext, ctx); - - return vnfContext; - } - - protected void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { - - checkWorkflowExists(vnfContext, requestContext); - } - - private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException { - - WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext)); - if (!workflowExistsOutput.isMappingExist()) { - if (logger.isDebugEnabled()) { - logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()); - } - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.WORKFLOW_MANAGER, - EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), - this.getClass().getCanonicalName()); - - - throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name()); - } - if (!workflowExistsOutput.isDgExist()) { - if (logger.isDebugEnabled()) { - logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput); - } - - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.WORKFLOW_MANAGER, - EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()), - this.getClass().getCanonicalName()); - - - throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(), - workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion()); - } - } - - private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException { - String vnfType = ctx.getAttribute("vnf.vnf-type"); - String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status"); - if(StringUtils.isEmpty(vnfType)){ - throw new MissingVNFDataInAAIException("vnf-type"); - } - else if(StringUtils.isEmpty(orchestrationStatus)){ - throw new MissingVNFDataInAAIException("orchestration-status"); - } - vnfContext.setType(vnfType); - vnfContext.setStatus(orchestrationStatus); - vnfContext.setId(ctx.getAttribute("vnf.vnf-id")); - } - - private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) { - - WorkflowRequest workflowRequest = new WorkflowRequest(); - workflowRequest.setVnfContext(vnfContext); - workflowRequest.setRequestContext(requestContext); - if (logger.isTraceEnabled()) { - logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")"); - } - return workflowRequest; - } - - protected void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header)); - } - - UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId()); - boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier); - if (!requestAccepted) { - if (logger.isDebugEnabled()) { - logger.debug("Duplicate Request with " + requestIdentifier); - } - throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier); - } - } - - protected Integer readTTL(CommonHeader header) { - if (logger.isTraceEnabled()) { - logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header)); - } - if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) { - String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL)); - return Integer.parseInt(defaultTTLStr); - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from readTTL with (TTL = "+ ObjectUtils.toString(header.getFlags().getTtl())+")"); - } - return header.getFlags().getTtl(); - } - - private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx)); - } - - String key = "vnf-id = '" + vnf_id + "'"; - logger.debug("inside getVnfdata=== " + key); - try { - Instant beginTimestamp = Instant.now(); - SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx); - Instant endTimestamp = Instant.now(); - String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR; - LoggingUtils.logMetricsMessage( - beginTimestamp, - endTimestamp, - LoggingConstants.TargetNames.AAI, - LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY, - status, - "", - response.name(), - this.getClass().getCanonicalName()); - if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) { - throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id); - } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) { - throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id); - } - logger.info("AAIResponse: " + response.toString()); - } catch (SvcLogicException e) { - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA, - "Error in getVnfdata" + e, - this.getClass().getCanonicalName()); - - throw new RuntimeException(e); - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")"); - } - return ctx; - } - - protected void validateInput(RequestContext requestContext) - throws RequestExpiredException, InvalidInputException, DuplicateRequestException { - if (logger.isTraceEnabled()){ - logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext)); - } - if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null - || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 || - null == requestContext.getCommonHeader().getApiVer()) { - if (logger.isDebugEnabled()) { - logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name()); - } - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - EELFResourceManager.format(Msg.APPC_INVALID_INPUT), - this.getClass().getCanonicalName()); - - throw new InvalidInputException("vnfID or command is null"); - } - CommonHeader commonHeader = requestContext.getCommonHeader(); - - checkForDuplicateRequest(commonHeader); - - Calendar inputTimeStamp = DateToCalendar(Date.from(commonHeader.getTimeStamp())); - Calendar currentTime = Calendar.getInstance(); - - // If input timestamp is of future, we reject the request - if (inputTimeStamp.getTime().getTime() > currentTime.getTime().getTime()) { - if (logger.isDebugEnabled()) { - logger.debug("Input Timestamp is of future = " + inputTimeStamp.getTime()); - } - throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime()); - } - Integer ttl = readTTL(commonHeader); - logger.debug("TTL value set to (seconds) : " + ttl); - inputTimeStamp.add(Calendar.SECOND, ttl); - if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) { - - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - "TTL Expired: Current time - " + currentTime.getTime().getTime() + " Request time: " + inputTimeStamp.getTime().getTime() + " with TTL value: " + ttl, - this.getClass().getCanonicalName()); - - throw new RequestExpiredException("TTL Expired"); - } - if (logger.isDebugEnabled()) { - logger.debug("Validation of the request is successful"); - } - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java deleted file mode 100644 index 0df57a754..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/DmaapOutgoingMessage.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - - - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -/** - * This class represents a message being sent out to DMaaP by APPC as async response. - * note the structure of this class must be adapted to the sync message sent to DMaaP represened in org.onap.appc.listener.LCM.domainmodel.DmaapOutgoingMessage - * - */ -@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class DmaapOutgoingMessage { - - @JsonProperty("version") - private String version; - - @JsonProperty("type") - private String type; - - @JsonProperty("correlation-id") - private String correlationID; - - private final static String defaultCambriaPartition = "MSO"; - @JsonProperty("cambria.partition") - private String cambriaPartition = defaultCambriaPartition; - - @JsonProperty("rpc-name") - private String rpcName; - - @JsonProperty("body") - private Body body; - - public DmaapOutgoingMessage() { - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCorrelationID() { - return correlationID; - } - - public void setCorrelationID(String correlationID) { - this.correlationID = correlationID; - } - - public String getCambriaPartition() { - return cambriaPartition; - } - - public void setCambriaPartition(String cambriaPartition) { - this.cambriaPartition = cambriaPartition; - } - - public String getRpcName() { - return rpcName; - } - - public void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - public Body getBody() { - return body; - } - - public void setBody(Body body) { - this.body = body; - } - - @Override - public String toString() { - return "DmaapOutgoingMessage{" + - "cambriaPartition='" + cambriaPartition + '\'' + - ", rpcName='" + rpcName + '\'' + - ", body=" + body + - '}'; - } - - @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) - @JsonIgnoreProperties(ignoreUnknown = true) - public static class Body { - public Body() { - } - - public Body(Object output) { - this.output = output; - } - - @JsonProperty("output") - private Object output; - - public Object getOutput() { - return output; - } - - public void setOutput(Object body) { - this.output = body; - } - - @Override - public String toString() { - return "Body{" + - "output=" + output + - '}'; - } - } -} - diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java deleted file mode 100644 index 276eaddab..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/LCMStateManagerImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.concurrent.atomic.AtomicBoolean; - -import org.onap.appc.requesthandler.LCMStateManager; - -public class LCMStateManagerImpl implements LCMStateManager { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMStateManagerImpl.class); - private static AtomicBoolean isLCMEnabled = new AtomicBoolean(true); - - /** - * This method checks if the LCM operations are enabled or not - * * @return true if enabled else false - */ - public boolean isLCMOperationEnabled() { - return isLCMEnabled.get(); - } - - /** - * This method disables the LCM operations - */ - public void disableLCMOperations() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to disableLCMOperations"); - } - isLCMEnabled.set(false); - } - - /** - * This method enables the LCM operations - */ - public void enableLCMOperations() { - if (logger.isTraceEnabled()) { - logger.trace("Entering to enableLCMOperations"); - } - isLCMEnabled.set(true); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java deleted file mode 100644 index 1f07b277c..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java +++ /dev/null @@ -1,235 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.appc.requesthandler.constant.Constants; -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.UnstableVNFException; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.executor.objects.UniqueRequestIdentifier; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockManager; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.workingstatemanager.WorkingStateManager; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; - -/** - * This class provides application logic for the Request/Response Handler Component. - * - */ -public class RequestHandlerImpl extends AbstractRequestHandlerImpl { - - /** - * APP-C VNF lock idle timeout in milliseconds. Applied only when locking VNF using northbound API "lock" - */ - private static final String PROP_IDLE_TIMEOUT = "org.onap.appc.lock.idleTimeout"; - - private LockManager lockManager; - - private WorkingStateManager workingStateManager; - - public void setLockManager(LockManager lockManager) { - this.lockManager = lockManager; - } - - public void setWorkingStateManager(WorkingStateManager workingStateManager) { - this.workingStateManager = workingStateManager; - } - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class); - - protected void handleRequest(RuntimeContext runtimeContext) { - - switch (runtimeContext.getRequestContext().getAction()) { - case Lock: - try { - lockWithTimeout(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); - fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null); - } catch (LockException e) { - Params params = new Params().addParam("errorMsg", e.getMessage()); - fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); - storeErrorMessageToLog(runtimeContext, - LoggingConstants.TargetNames.APPC, - LoggingConstants.TargetNames.LOCK_MANAGER, - EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); - } - break; - - case Unlock: - try { - releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); - fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); - } catch (LockException e) { - //TODO add proper error code and message - // logger.error(EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId())); - Params params = new Params().addParam("errorMsg", e.getMessage()); - fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); - } - break; - - case CheckLock: - boolean isLocked = lockManager.isLocked(runtimeContext.getVnfContext().getId()); - fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null); - runtimeContext.getResponseContext().addKeyValueToAdditionalContext("locked", String.valueOf(isLocked).toUpperCase()); - break; - default: - try { - boolean lockAcquired = acquireVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId(), 0); - runtimeContext.setIsLockAcquired(lockAcquired); - callWfOperation(runtimeContext); - } catch (LockException e) { - Params params = new Params().addParam("errorMsg", e.getMessage()); - fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params); - } finally { - if (runtimeContext.isLockAcquired()) { - final int statusCode = runtimeContext.getResponseContext().getStatus().getCode(); - if (statusCode % 100 == 2 || statusCode % 100 == 3) { - try { - releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId()); - } catch (LockException e) { - logger.error("Error releasing the lock",e); - } - } - } - } - } - } - - private void releaseVNFLock(String vnfId, String transactionId) throws LockException { - lockManager.releaseLock(vnfId, transactionId); - logger.info("Lock released for vnfID = " + vnfId); - } - - protected void lockWithTimeout(String vnfId, String requestId) throws LockException { - long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT); - acquireVNFLock(vnfId, requestId, timeout); - } - - private boolean acquireVNFLock(String vnfID, String requestId, long timeout) throws LockException { - if (logger.isTraceEnabled()) - logger.trace("Entering to acquireVNFLock with vnfID = " + vnfID); - boolean lockAcquired = lockManager.acquireLock(vnfID, requestId, timeout); - if (lockAcquired) { - logger.info("Lock acquired for vnfID = " + vnfID); - } else { - logger.info("vnfID = " + vnfID + " was already locked"); - } - return lockAcquired; - } - - /** - * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI. - * - * @param vnfId String of VNF ID - * @param readOnlyActivity boolean indicator - * @param requestIdentifierString - string contains id uniquely represents the request - * @param forceFlag boolean indicator - * @throws UnstableVNFException when failed - */ - @Override - public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to onRequestExecutionStart with vnfId = " + vnfId + "and requestIdentifierString = " + requestIdentifierString); - } - - if(!readOnlyActivity || !forceFlag || workingStateManager.isVNFStable(vnfId)) { - boolean updated = false; - try { - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, requestIdentifierString, forceFlag); - } catch (Exception e) { - logger.error("Error updating working state for vnf " + vnfId + e); - throw new RuntimeException(e); - } - if (!updated) { - throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); - } - } - - if (logger.isTraceEnabled()) - logger.trace("Exiting from onRequestExecutionStart "); - } - - private boolean isReadOnlyAction(VNFOperation action) { - if (VNFOperation.Sync.toString().equals(action) || - VNFOperation.Audit.toString().equals(action) || - VNFOperation.ConfigBackup.toString().equals(action) || - VNFOperation.ConfigBackupDelete.toString().equals(action) || - VNFOperation.ConfigExport.toString().equals(action)){ - return true; - } - return false; - } - - @Override - public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) { - super.onRequestExecutionEnd(runtimeContext,isAAIUpdated); - VNFWorkingState workingState; - Status status = runtimeContext.getResponseContext().getStatus(); - if (status.getCode() == LCMCommandStatus.SUCCESS.getResponseCode() || isReadOnlyAction(runtimeContext.getRequestContext().getAction())) { - workingState = VNFWorkingState.STABLE; - } else { - workingState = VNFWorkingState.UNKNOWN; - } - - UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(), - runtimeContext.getResponseContext().getCommonHeader().getRequestId(), - runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()); - - String requestIdentifierString = requestIdentifier.toIdentifierString(); - workingStateManager.setWorkingState(runtimeContext.getVnfContext().getId(), workingState, requestIdentifierString, false); - logger.debug("Reset lock for vnfId " + runtimeContext.getVnfContext().getId()); - resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); - } - - private void resetLock(String vnfId, String requestId, boolean lockAcquired, boolean resetLockTimeout) { - if (lockAcquired) { - try { - releaseVNFLock(vnfId, requestId); - } catch (LockException e) { - logger.error("Unlock VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); - } - } else if (resetLockTimeout) { - try { - // reset timeout to previous value - lockWithTimeout(vnfId, requestId); - } catch (LockException e) { - logger.error("Reset lock idle timeout for VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e); - } - } - } - - @Override - public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) { - super.onRequestTTLEnd(runtimeContext,updateAAI); - resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java deleted file mode 100644 index 8724adc59..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.i18n.EELFResourceManager; -import org.apache.commons.lang.ObjectUtils; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.i18n.Msg; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.requesthandler.LCMStateManager; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.workingstatemanager.WorkingStateManager; - - -public class RequestValidatorImpl extends AbstractRequestValidatorImpl { - - private WorkingStateManager workingStateManager; - private LCMStateManager lcmStateManager; - - public void setLifecyclemanager(LifecycleManager lifecyclemanager) { - this.lifecyclemanager = lifecyclemanager; - } - - public void setWorkingStateManager(WorkingStateManager workingStateManager) { - this.workingStateManager = workingStateManager; - } - - public void setLcmStateManager(LCMStateManager lcmStateManager) { - this.lcmStateManager = lcmStateManager; - } - - public RequestValidatorImpl() { - } - - @Override - public void validateRequest(RuntimeContext runtimeContext) - throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, - DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, - DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - if (logger.isTraceEnabled()){ - logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext)); - } - if(!lcmStateManager.isLCMOperationEnabled()) { - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), - this.getClass().getCanonicalName()); - throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); - } - - getAAIservice(); - validateInput(runtimeContext.getRequestContext()); - checkVNFWorkingState(runtimeContext); - String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - VNFContext vnfContext = queryAAI(vnfId); - runtimeContext.setVnfContext(vnfContext); - - queryLCM(runtimeContext.getVnfContext().getStatus(), runtimeContext.getRequestContext().getAction()); - VNFOperation operation = runtimeContext.getRequestContext().getAction(); - if(!operation.isBuiltIn()) { - // for built-in operations skip WF presence check - queryWFM(vnfContext, runtimeContext.getRequestContext()); - } - } - - - private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException { - if (logger.isTraceEnabled()) { - logger.trace("Entering to queryLCM with Orchestration Status = "+ ObjectUtils.toString(orchestrationStatus)+ - ", command = "+ ObjectUtils.toString(action)); - } - - String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name()); - if (logger.isDebugEnabled()) { - logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")"); - } - return nextState; - } - - - private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException { - - if (logger.isTraceEnabled()) { - logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext())); - } - boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null && runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce(); - String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - - if (logger.isDebugEnabled()) { - logger.debug("forceFlag = " + forceFlag); - } - boolean isVNFStable = workingStateManager.isVNFStable(vnfId); - if (!isVNFStable && !forceFlag) { - if (logger.isDebugEnabled()) { - logger.debug("VNF is not stable for VNF ID = " + vnfId); - } - throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId); - } - - } - - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java deleted file mode 100644 index 7e3917313..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.executor.UnstableVNFException; - -public class VMRequestHandlerImpl extends AbstractRequestHandlerImpl{ - - protected void handleRequest(RuntimeContext runtimeContext) { - runtimeContext.setIsLockAcquired(false); - callWfOperation(runtimeContext); - } - - @Override - public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException { - - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java deleted file mode 100644 index 79f83fbc6..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler.impl; - -import com.att.eelf.i18n.EELFResourceManager; -import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.i18n.Msg; -import org.onap.appc.logging.LoggingConstants; -import org.onap.appc.logging.LoggingUtils; -import org.onap.appc.requesthandler.exceptions.*; - -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -public class VMRequestValidatorImpl extends AbstractRequestValidatorImpl { - - @Override - public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, InvalidInputException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException, DuplicateRequestException { - if(!lcmStateManager.isLCMOperationEnabled()) { - LoggingUtils.logErrorMessage( - LoggingConstants.TargetNames.REQUEST_VALIDATOR, - EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), - this.getClass().getCanonicalName()); - throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled"); - } - - getAAIservice(); - super.validateInput(runtimeContext.getRequestContext()); - String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(); - - VNFContext vnfContext = queryAAI(vnfId); - runtimeContext.setVnfContext(vnfContext); - - VNFOperation operation = runtimeContext.getRequestContext().getAction(); - if(supportedVMLevelAction().contains(operation)) { - queryWFM(vnfContext, runtimeContext.getRequestContext()); - } - else{ - throw new LCMOperationsDisabledException("Action "+ operation.name() + " is not supported on VM level"); - } - } - - public Set supportedVMLevelAction(){ - Set vnfOperations = new HashSet<>(); - vnfOperations.add(VNFOperation.Start); - vnfOperations.add(VNFOperation.Stop); - vnfOperations.add(VNFOperation.Restart); - vnfOperations.add(VNFOperation.Rebuild); - vnfOperations.add(VNFOperation.Terminate); - vnfOperations.add(VNFOperation.Migrate); - vnfOperations.add(VNFOperation.Evacuate); - vnfOperations.add(VNFOperation.Snapshot); - return vnfOperations; - } - - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java deleted file mode 100644 index e9b3d0f3a..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/WorkingStateManager.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager; - -import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; - - -public interface WorkingStateManager { - - /** - * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. - * @param vnfId vnf Id to be verified for stable state - * @return True if vnf Exists and state is STABLE else False. - */ - public boolean isVNFStable(String vnfId); - - /** - * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or - * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. - * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. - * @param vnfId vnf Id to be updated - * @param workingState new working state - * @param ownerId - * @param forceFlag - force to update also on case given onwerId is different then the registered one - */ - public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag); - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java deleted file mode 100644 index 041cf7e84..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/JdbcWorkingStateManager.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.impl; - -import java.sql.Connection; - -import org.onap.appc.dao.util.JdbcConnectionFactory; -import org.onap.appc.workingstatemanager.WorkingStateManager; - -public abstract class JdbcWorkingStateManager implements WorkingStateManager { - - private JdbcConnectionFactory connectionFactory; - - public void setConnectionFactory(JdbcConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } - - protected Connection openDbConnection() { - return connectionFactory.openDbConnection(); - } - - protected void closeDbConnection(Connection connection) { - connectionFactory.closeDbConnection(connection); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java deleted file mode 100644 index 206d57229..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/RequestHandlerMessages.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.impl; - - -public class RequestHandlerMessages { - public final static String VNF_WORKING_STATE_UPDATED = "VNF WorkingState for vnfId ${vnfId} was updated to ${workingState} at attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; - public final static String VNF_WORKING_STATE_WAS_NOT_UPDATED = "VNF WorkingState for vnfId ${vnfId} was not updated to ${workingState} attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}"; -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java deleted file mode 100644 index e2fb3f298..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/impl/WorkingStateManagerImpl.java +++ /dev/null @@ -1,231 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.impl; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.executor.objects.Params; -import org.onap.appc.message.RequestHandlerMessages; -import org.onap.appc.util.MessageFormatter; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; -import org.onap.appc.workingstatemanager.objects.VnfWorkingStateDto; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.commons.lang3.StringUtils; - - -public class WorkingStateManagerImpl extends JdbcWorkingStateManager { - - private static final String SQL_RETRIEVE_VNF_STATE_MANAGEMENT = "SELECT VNF_ID,STATE,OWNER_ID,UPDATED,VER FROM VNF_STATE_MANAGEMENT WHERE VNF_ID=?"; - private static final String SQL_INSERT_VNF_STATE_MANAGEMENT = "INSERT IGNORE INTO VNF_STATE_MANAGEMENT (VNF_ID,STATE,OWNER_ID,UPDATED,VER) VALUES (?, ?, ?, ?, ?)"; - private static final String SQL_UPDATE_VNF_STATE_MANAGEMENT = "UPDATE VNF_STATE_MANAGEMENT SET OWNER_ID=?, UPDATED=?, STATE=?, VER=? WHERE VNF_ID=? AND VER=?"; - private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()"; - private static int maxAttempts = ConfigurationFactory.getConfiguration().getIntegerProperty("org.onap.appc.workingstatemanager.maxAttempts",20); - - private static Map workingStateMap = new ConcurrentHashMap<>(); - private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkingStateManagerImpl.class); - - - /** - * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception. - * @param vnfId vnf Id to be verified for stable state - * @return True if vnf Exists and state is STABLE else False. - */ - @Override - public boolean isVNFStable(String vnfId){ - if (logger.isTraceEnabled()) { - logger.trace("Entering to isVNFStable with vnfId = "+ vnfId); - } - Connection connection = null; - boolean vnfStable = false; - try { - connection = openDbConnection(); - VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); - vnfStable = isVNFStable(vnfWorkingStateDto); - } catch (SQLException e) { - String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); - throw new RuntimeException(errMsg); - } finally { - if(connection != null) { - closeDbConnection(connection); - } - } - if (logger.isTraceEnabled()) { - logger.trace("Exiting from isVNFStable for vnfId = "+ vnfId+" with Result = "+vnfStable); - } - return vnfStable; - } - - /** - * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or - * if the registered ownerId is equal to the given ownerId or if the forceFlag is true. - * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store. - * @param vnfId vnf Id to be updated - * @param workingState new working state - * @param ownerId - * @param forceFlag - force to update also on case given onwerId is different then the registered one - */ - @Override - public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag){ - boolean updated = false; - if (logger.isTraceEnabled()) { - logger.trace("Entering to setWorkingState with vnfId = "+ ObjectUtils.toString(vnfId)+ ", VNFWorkingState = " + workingState.name() + ", ownerId = "+ownerId+", forceFlag = "+forceFlag); - } - Connection connection = null; - try { - connection = openDbConnection(); - updated = setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag, maxAttempts); - } catch (SQLException e) { - String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage(); - throw new RuntimeException(errMsg); - } finally { - if(connection != null) { - closeDbConnection(connection); - } - } - - logger.trace("setWorkingState exit with output updated = "+updated); - return updated; - } - - public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag, int maxAttempts) throws SQLException { - return setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag,1,maxAttempts); - } - public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag,int attempt, int maxAttempts) throws SQLException { - boolean updated = false; - VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId); - Long currentVersion = vnfWorkingStateDto != null ? vnfWorkingStateDto.getVer() : null; - if(forceFlag || isVNFStable(vnfWorkingStateDto) || - ( vnfWorkingStateDto != null && vnfWorkingStateDto.getOwnerId().equals(ownerId)) ) { - updated = storeWorkingStateIfSameVersion(connection, vnfId, workingState, ownerId, currentVersion); - - Params params = new Params().addParam("vnfId", vnfId).addParam("workingState",workingState.name()) - .addParam("attempt",attempt).addParam("maxAttempts",maxAttempts).addParam("ownerId",ownerId).addParam("forceFlag",forceFlag); - String logMessage; - if(updated) { - logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_UPDATED, params.getParams()); - }else { - logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_WAS_NOT_UPDATED, params.getParams()); - } - logger.debug(logMessage); - if(!updated && attempt= Long.MAX_VALUE) ? 1 : (currentVer + 1); - statement.setString(1, ownerId); - statement.setLong(2, getCurrentTime(connection)); - statement.setString(3, state); - statement.setLong(4, newVer); - statement.setString(5, vnfId); - statement.setLong(6, currentVer); - return (statement.executeUpdate() != 0); - } - } - - protected VnfWorkingStateDto retrieveVnfWorkingState(Connection connection, String vnfId) throws SQLException { - VnfWorkingStateDto res = null; - - try(PreparedStatement statement = connection.prepareStatement(SQL_RETRIEVE_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER - statement.setString(1, vnfId); - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = new VnfWorkingStateDto(vnfId); - String stateString = resultSet.getString(2); - VNFWorkingState vnfWorkingState = VNFWorkingState.valueOf(stateString); - res.setState(vnfWorkingState); - res.setOwnerId(resultSet.getString(3)); - res.setUpdated(resultSet.getLong(4)); - res.setVer(resultSet.getLong(5)); - } - } - } - return res; - } - - private long getCurrentTime(Connection connection) throws SQLException { - long res = -1; - if(connection != null) { - try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) { - try(ResultSet resultSet = statement.executeQuery()) { - if(resultSet.next()) { - res = resultSet.getTimestamp(1).getTime(); - } - } - } - } - if(res == -1) { - res = System.currentTimeMillis(); - } - return res; - } - - protected boolean addVnfWorkingStateIfNotExists(Connection connection, String vnfId, String ownerId, String state) throws SQLException { - boolean added = false; - try(PreparedStatement statement = connection.prepareStatement(SQL_INSERT_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER - statement.setString(1, vnfId); - statement.setString(2, state); - statement.setString(3, ownerId); - statement.setLong(4, getCurrentTime(connection)); - statement.setLong(5, 1L); - int rowCount = statement.executeUpdate(); - added = rowCount != 0 ? true : false; - } - return added; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java deleted file mode 100644 index 9c638de20..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VNFWorkingState.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.objects; - - -public enum VNFWorkingState { - STABLE,UNSTABLE,UNKNOWN; - public String toString(){ - return this.name(); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java deleted file mode 100644 index 948d4ca59..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/workingstatemanager/objects/VnfWorkingStateDto.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager.objects; - - -public class VnfWorkingStateDto { - private String vnfId; - private VNFWorkingState state; - private String ownerId; - private long updated; - private long ver; - - public VnfWorkingStateDto() { - } - - public VnfWorkingStateDto(String vnfId) { - this.vnfId = vnfId; - } - - public String getVnfId() { - return vnfId; - } - - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - - public VNFWorkingState getState() { - return state; - } - - public void setState(VNFWorkingState state) { - this.state = state; - } - - public String getOwnerId() { - return ownerId; - } - - public void setOwnerId(String ownerId) { - this.ownerId = ownerId; - } - - public long getUpdated() { - return updated; - } - - public void setUpdated(long updated) { - this.updated = updated; - } - - public long getVer() { - return ver; - } - - public void setVer(long ver) { - this.ver = ver; - } - - - @Override - public String toString() { - return "VnfWorkingStateDto{" + - "vnfId='" + vnfId + '\'' + - ", state=" + state + - ", ownerId='" + ownerId + '\'' + - ", updated=" + updated + - ", ver=" + ver + - '}'; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..9bf3b6c1a --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/onap/appc/default.properties @@ -0,0 +1,49 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded +# to supply configuration options +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HLDR-MAIN +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + + +org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test +org.onap.appc.db.user.sdnctl=test +org.onap.appc.db.pass.sdnctl=123456 + +# +# This needs to be changed so that the action can be appended to the end of the URL path +# +#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider:topology-service +#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider: +org.onap.appc.workingstatemanager.maxAttempts=20 diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 9bf3b6c1a..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,49 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded -# to supply configuration options -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HLDR-MAIN -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - - -org.onap.appc.db.url.sdnctl=jdbc:mysql://127.0.0.1:3306/test -org.onap.appc.db.user.sdnctl=test -org.onap.appc.db.pass.sdnctl=123456 - -# -# This needs to be changed so that the action can be appended to the end of the URL path -# -#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider:topology-service -#provider.urls.topology=https://admin:password@:8443/restconf/operations/appc-provider: -org.onap.appc.workingstatemanager.maxAttempts=20 diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java new file mode 100644 index 000000000..95146fbfa --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/LCMStateManagerImplTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.requesthandler.impl.LCMStateManagerImpl; + +public class LCMStateManagerImplTest { + + LCMStateManager lcmStateManager; + + @Before + public void init() throws Exception { + lcmStateManager = new LCMStateManagerImpl(); + } + + /** + * Test to check the disable LCM operations method + */ + @Test + public void disableLCMOperations() throws Exception { + lcmStateManager.disableLCMOperations(); + Assert.assertFalse(lcmStateManager.isLCMOperationEnabled()); + } + + /** + * Test to check the enable LCM operations method + */ + @Test + public void enableLCMOperations() throws Exception { + lcmStateManager.enableLCMOperations(); + Assert.assertTrue(lcmStateManager.isLCMOperationEnabled()); + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java new file mode 100644 index 000000000..9339931e8 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/RequestValidatorTest.java @@ -0,0 +1,570 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +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.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.requesthandler.exceptions.InvalidInputException; +import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; +import org.onap.appc.requesthandler.impl.RequestHandlerImpl; +import org.onap.appc.requesthandler.impl.RequestValidatorImpl; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workingstatemanager.WorkingStateManager; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.Instant; +import java.util.UUID; + +import static junit.framework.TestCase.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.*; + +@SuppressWarnings("unchecked") +@RunWith(PowerMockRunner.class) +@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class, + RequestValidatorImpl.class, TransactionRecorder.class}) +public class RequestValidatorTest { + private final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); + + private RequestValidatorImpl requestValidator; + + private AAIService aaiAdapter ; + private LifecycleManager lifecyclemanager; + private WorkFlowManager workflowManager; + private WorkingStateManager workingStateManager ; + private LCMStateManager lcmStateManager; + + private final BundleContext bundleContext= Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + + @Before + public void init() throws Exception { + // *** + AAIService 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); + PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(),anyString(), + anyObject())).thenAnswer(invocation -> { + 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 ; + }); + PowerMockito.when(aaiService.update(anyString(),anyString(), anyObject(),anyString(), anyObject())) + .thenReturn(SvcLogicResource.QueryStatus.SUCCESS); + // *** + + aaiAdapter = Mockito.mock(AAIService.class); + lifecyclemanager= Mockito.mock(LifecycleManager.class); + workflowManager= Mockito.mock(WorkFlowManager.class); + workingStateManager = Mockito.mock(WorkingStateManager.class); + lcmStateManager = Mockito.mock(LCMStateManager.class); + + requestValidator = new RequestValidatorImpl(); + requestValidator.setWorkflowManager(workflowManager); + requestValidator.setLifecyclemanager(lifecyclemanager); + requestValidator.setWorkingStateManager(workingStateManager); + requestValidator.setLcmStateManager(lcmStateManager); + + Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true); + } + + public AAIService getAaiadapter() { + return this.aaiAdapter; + } + + private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, + boolean force, String originatorId, String requestId, + String subRequestId, Instant timeStamp){ + String API_VERSION= "2.0.0"; + RequestHandlerInput input = new RequestHandlerInput(); + RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); + RequestContext requestContext = runtimeContext.getRequestContext(); + input.setRequestContext(requestContext); + requestContext.getActionIdentifiers().setVnfId(vnfID); + requestContext.setAction(action); + if (action != null) { + input.setRpcName(convertActionNameToUrl(action.name())); + } else{ + input.setRpcName(null); + } + requestContext.getCommonHeader().setRequestId(requestId); + requestContext.getCommonHeader().setSubRequestId(subRequestId); + requestContext.getCommonHeader().setOriginatorId(originatorId); + requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); + requestContext.getCommonHeader().getTimeStamp(); + requestContext.getCommonHeader().setApiVer(API_VERSION); + requestContext.getCommonHeader().setTimestamp(timeStamp); + return input; + } + + @Test + public void testNullVnfID() throws Exception { + logger.debug("=====================testNullVnfID============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput(null, VNFOperation.Configure, 30, + false, UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(InvalidInputException e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testNullVnfID============================="); + } + + @Test + public void testPositiveFlowWithConfigure() throws Exception { + logger.debug("=====================testPositiveFlowWithConfigure============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workingStateManager.isVNFStable("1")).thenReturn(true); + RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNull(ex); + logger.debug("testPositiveFlowWithConfigure"); + logger.debug("=====================testPositiveFlowWithConfigure============================="); + } + + @Test + public void testVnfNotFound() throws Exception { + logger.debug("=====================testVnfNotFound============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("8", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testVnfNotFound============================="); + } + + @Test + public void testNullCommand() throws Exception { + logger.debug("=====================testNullCommand============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("7", null,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(InvalidInputException e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testNullCommand============================="); + } + + @Test + public void testNullVnfIDAndCommand() throws Exception { + logger.debug("=====================testNullVnfIDAndCommand============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput(null, null,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(InvalidInputException e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testNullVnfIDAndCommand============================="); + } + + @Test + public void testWorkflowNotFound() throws Exception { + logger.debug("=====================testWorkflowNotFound============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(false,false)); + RequestHandlerInput input = this.getRequestHandlerInput("10", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testWorkflowNotFound============================="); + } + + @Test + public void testUnstableVnfWithConfigure() throws Exception { + logger.debug("=====================testUnstableVnfWithConfigure============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("11", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithConfigure============================="); + } + + @Test + public void testUnstableVnfWithTest() throws Exception { + logger.debug("=====================testUnstableVnfWithTest============================="); + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + RequestHandlerInput input = this.getRequestHandlerInput("12", VNFOperation.Test,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithTest============================="); + } + + @Test + public void testUnstableVnfWithStart() throws Exception { + logger.debug("=====================testUnstableVnfWithStart============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("13", VNFOperation.Start,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithStart============================="); + } + + @Test + public void testUnstableVnfWithTerminate() throws Exception { + logger.debug("=====================testUnstableVnfWithTerminate============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + RequestHandlerInput input = this.getRequestHandlerInput("14", VNFOperation.Terminate,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithTerminate============================="); + } + + @Test + public void testUnstableVnfWithRestart() throws Exception { + logger.debug("=====================testUnstableVnfWithRestart============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("26", VNFOperation.Restart,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithRestart============================="); + } + + @Test + public void testUnstableVnfWithRebuild() throws Exception { + logger.debug("=====================testUnstableVnfWithRebuild============================="); + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) + .thenThrow( new NoTransitionDefinedException("","","")); + + RequestHandlerInput input = this.getRequestHandlerInput("27", VNFOperation.Rebuild,30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testUnstableVnfWithRebuild============================="); + } + + @Test + public void testAAIDown() throws Exception { + logger.debug("=====================testAAIDown============================="); + RequestHandlerInput input = this.getRequestHandlerInput("28", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), + Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("=====================testAAIDown============================="); + } + + @Test + public void testNegativeFlowWithTimeStamp() throws Exception { + logger.debug("=====================testNegativeFlowWithTimeStamp============================="); + Instant now = Instant.now(); + Instant past = now.minusMillis(1000000); + RequestHandlerInput input = this.getRequestHandlerInput("35", VNFOperation.Configure, 30, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(),past); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + logger.debug("testNegativeFlowWithTimeStamp"); + logger.debug("=====================testNegativeFlowWithTimeStamp============================="); + } + + @Test + public void rejectDuplicateRequest() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + Mockito.when(workflowManager.workflowExists(anyObject())) + .thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true); + RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false, + originatorID, requestID, subRequestID, Instant.now()); + + RequestHandlerInput input1 = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false, + originatorID, requestID, subRequestID, Instant.now()); + Exception ex =null; + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + RuntimeContext runtimeContext1 = putInputToRuntimeContext(input1); + + try { + requestValidator.validateRequest(runtimeContext); + }catch(Exception e ) { + ex = e; + } + assertNull(ex); + + try { + requestValidator.validateRequest(runtimeContext1); + }catch(Exception e ) { + ex = e; + } + assertNotNull(ex); + } + + @Test + public void testLockOperation() throws Exception { + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Lock); + } + + @Test + public void testUnlockOperation() throws Exception { + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Unlock); + } + + @Test + public void testCheckLockOperation() throws Exception { + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.CheckLock); + } + + @Test(expected = NoTransitionDefinedException.class) + public void testLockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Lock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Lock); + } + + @Test(expected = NoTransitionDefinedException.class) + public void testUnlockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Unlock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.Unlock); + } + + @Test(expected = NoTransitionDefinedException.class) + public void testCheckLockOperationNegative() throws Exception { + Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.CheckLock.toString()))) + .thenThrow(new NoTransitionDefinedException("", "", "")); + Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); + testOperation("no-matter", VNFOperation.CheckLock); + } + + @Test(expected = LCMOperationsDisabledException.class) + public void testLCMOperationsDisabled() throws Exception { + Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(false); + testOperation("no-matter", VNFOperation.Configure); + } + private void testOperation(String resource, VNFOperation operation) throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0, false, originatorID, + requestID, subRequestID, Instant.now()); + RuntimeContext runtimeContext = putInputToRuntimeContext(input); + requestValidator.validateRequest(runtimeContext); + } + + private RuntimeContext createRuntimeContextWithSubObjects() { + RuntimeContext runtimeContext = new RuntimeContext(); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + ResponseContext responseContext = createResponseContextWithSuObjects(); + runtimeContext.setResponseContext(responseContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + return runtimeContext; + + } + + private ResponseContext createResponseContextWithSuObjects(){ + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + + private String convertActionNameToUrl(String action) { + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1-$2"; + return action.replaceAll(regex, replacement) + .toLowerCase(); + } + + private RuntimeContext putInputToRuntimeContext(RequestHandlerInput input) { + RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); + runtimeContext.setRequestContext(input.getRequestContext()); + runtimeContext.setRpcName(input.getRpcName()); + runtimeContext.getVnfContext().setId(input.getRequestContext().getActionIdentifiers().getVnfId()); + return runtimeContext; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java new file mode 100644 index 000000000..a65af669b --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestConverter.java @@ -0,0 +1,372 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.domainmodel.lcm.*; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.requesthandler.conv.Converter; + +import java.text.ParseException; +import java.time.Instant; +import java.util.Date; +import java.util.HashMap; + + +public class TestConverter { + private String expectedJsonBodyStr ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; + private String expectedDmaapOutgoingMessageJsonStringTest ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"test\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringRollback ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"rollback\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringSnapshot ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"snapshot\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringAudit ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"audit\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringHealthCheck ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"health-check\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringLiveUpgrade ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"live-upgrade\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringLock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"lock\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringModifyConfig ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"config-modify\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringSoftwareUpload ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"software-upload\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringStop ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"stop\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringSync ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"sync\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringTerminate ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"terminate\",\"type\":\"response\"}"; + private String expectedDmaapOutgoingMessageJsonStringUnlock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"unlock\",\"type\":\"response\"}"; + private String expectedJsonBodyStrwithPayload ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; + + @Test + public void convDateToZuluStringTest(){ + String dateToZuluString = Converter.convDateToZuluString(new Date(0L)); + Assert.assertEquals("1970-01-01T00:00:00.000Z", dateToZuluString); + } + + @Test + public void convAsyncResponseToBuilderTestTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Test; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringTestTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Test; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTest,jsonStr); + } + + @Test + public void convPayloadObjectToJsonStringTest() throws JsonProcessingException, ParseException { + String jsonString = Converter.convPayloadObjectToJsonString("any valid JSON string value"); + Assert.assertEquals("any valid JSON string value", jsonString); + + HashMap hashMap = new HashMap<>(); + hashMap.put("key","value"); + jsonString = Converter.convPayloadObjectToJsonString(hashMap); + Assert.assertEquals("{\"key\":\"value\"}", jsonString); + } + + @Test + public void convAsyncResponseToBuilderRollbackTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Rollback; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringRollbackTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Rollback; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringRollback,jsonStr); + } + + @Test + public void convAsyncResponseToBuilderSnapshotTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Snapshot; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringSnapshotTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Snapshot; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSnapshot,jsonStr); + } + @Test + public void convAsyncResponseToBuilderAuditTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Audit; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringAuditTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Audit; + String rpcName = action.name().toLowerCase(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringAudit,jsonStr); + } + @Test + public void convAsyncResponseToBuilderHealthCheckTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.HealthCheck; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringHealthCheckTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.HealthCheck; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringHealthCheck,jsonStr); + } + @Test + public void convAsyncResponseToBuilderLiveUpgradeTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.LiveUpgrade; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringLiveUpgradeTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.LiveUpgrade; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLiveUpgrade,jsonStr); + } + @Test + public void convAsyncResponseToBuilderLockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Lock; + String rpcName = convertActionNameToUrl(action.name()); + + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringLockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Lock; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLock,jsonStr); + } + @Test + public void convAsyncResponseToBuilderModifyConfigTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.ConfigModify; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringModifyConfigTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.ConfigModify; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringModifyConfig,jsonStr); + } + @Test + public void convAsyncResponseToBuilderSoftwareUploadTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.SoftwareUpload; + String rpcName = convertActionNameToUrl(action.name()); + + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringSoftwareUploadTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.SoftwareUpload; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSoftwareUpload,jsonStr); + } + @Test + public void convAsyncResponseToBuilderStopTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Stop; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringStopTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Stop; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringStop,jsonStr); + } + @Test + public void convAsyncResponseToBuilderSync() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Sync; + String rpcName = convertActionNameToUrl(action.name()); + + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringSync() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Sync; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSync,jsonStr); + } + @Test + public void convAsyncResponseToBuilderTerminateTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponsewithPayload(); + VNFOperation action = VNFOperation.Sync; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringTerminateTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Terminate; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTerminate,jsonStr); + } + @Test + public void convAsyncResponseToBuilderUnlockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Unlock; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringUnlockTest() throws JsonProcessingException { + ResponseContext asyncResponse = buildAsyncResponse(); + VNFOperation action = VNFOperation.Unlock; + String rpcName = convertActionNameToUrl(action.name()); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringUnlock,jsonStr); + } + /*@Test + public void convAsyncResponseToBuilderTest() throws JsonProcessingException { + AsyncResponse asyncResponse = buildAsyncResponse(); + String jsonStr = Converter.convAsyncResponseToJsonStringBody(asyncResponse); + Assert.assertEquals(expectedJsonBodyStr,jsonStr); + } + + @Test + public void convAsyncResponseToDmaapOutgoingMessageJsonStringTest() throws JsonProcessingException { + AsyncResponse asyncResponse = buildAsyncResponse(); + String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(asyncResponse); + System.out.println("jsonStr = " + jsonStr); + Assert.assertEquals(expectedDmaapOutgoingMessageJsonString,jsonStr); + }*/ + + + private ResponseContext buildAsyncResponse() { + ResponseContext asyncResponse = createResponseContextWithSubObjects(); + asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); + asyncResponse.getCommonHeader().setOriginatorId("oid"); + asyncResponse.getCommonHeader().setApiVer("2.0.0"); + asyncResponse.getCommonHeader().setRequestId("reqid"); + asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); + asyncResponse.setPayload("any valid JSON string value. Json escape characters need to be added to make it a valid json string value"); + return asyncResponse; + } + + private ResponseContext buildAsyncResponsewithPayload() { + ResponseContext asyncResponse = createResponseContextWithSubObjects(); + asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); + asyncResponse.getCommonHeader().setOriginatorId("oid"); + asyncResponse.getCommonHeader().setApiVer("2.0.0"); + asyncResponse.getCommonHeader().setRequestId("reqid"); + asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); + asyncResponse.setPayload("{}"); + return asyncResponse; + } + + private ResponseContext createResponseContextWithSubObjects() { + + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + + private String convertActionNameToUrl(String action) { + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1-$2"; + return action.replaceAll(regex, replacement) + .toLowerCase(); + } + + +} + + + diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java new file mode 100644 index 000000000..dfb45389d --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/TestRequestHandler.java @@ -0,0 +1,649 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler; + +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.time.Instant; +import java.util.HashMap; +import java.util.UUID; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.*; +import org.onap.appc.domainmodel.lcm.Flags.Mode; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +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.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.executor.CommandExecutor; +import org.onap.appc.executor.UnstableVNFException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.messageadapter.MessageAdapter; +import org.onap.appc.messageadapter.impl.MessageAdapterImpl; +import org.onap.appc.requesthandler.exceptions.*; +import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; +import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; +import org.onap.appc.requesthandler.exceptions.InvalidInputException; +import org.onap.appc.requesthandler.exceptions.RequestExpiredException; +import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; +import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; +import org.onap.appc.requesthandler.impl.RequestHandlerImpl; +import org.onap.appc.requesthandler.impl.RequestValidatorImpl; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.transactionrecorder.objects.TransactionRecord; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.appc.workingstatemanager.WorkingStateManager; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@Ignore +@RunWith(PowerMockRunner.class) +@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class,RequestValidatorImpl.class, TransactionRecorder.class, MessageAdapterImpl.class}) +public class TestRequestHandler { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); + + private RequestHandlerImpl requestHandler; + private RequestValidatorImpl requestValidator; + private WorkFlowManager workflowManager; + private WorkingStateManager workingStateManager ; + private LockManager lockManager; + private Configuration configuration; + + private final BundleContext bundleContext=Mockito.mock(BundleContext.class); + private final Bundle bundleService=Mockito.mock(Bundle.class); + private final ServiceReference sref=Mockito.mock(ServiceReference.class); + MessageAdapterFactory factory = new DmaapMessageAdapterFactoryImpl(); + + + @Before + public void init() throws Exception { + configuration = ConfigurationFactory.getConfiguration(); + + configuration.setProperty("appc.LCM.topic.write" , "TEST"); + configuration.setProperty("appc.LCM.client.key" , "TEST"); + configuration.setProperty("appc.LCM.client.secret" , "TEST"); + + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(MessageAdapterImpl.class)).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(factory); + + + requestHandler = new RequestHandlerImpl(); + LifecycleManager lifecyclemanager= mock(LifecycleManager.class); + workflowManager= mock(WorkFlowManager.class); + CommandExecutor commandExecutor= mock(CommandExecutor.class); + MessageAdapter messageAdapter = mock(MessageAdapter.class); + workingStateManager = mock(WorkingStateManager.class); + lockManager = mock(LockManager.class); + TransactionRecorder transactionRecorder= mock(TransactionRecorder.class); + + requestHandler.setWorkingStateManager(workingStateManager); + requestHandler.setMessageAdapter(messageAdapter); + requestValidator = mock(RequestValidatorImpl.class); + requestValidator.setLifecyclemanager(lifecyclemanager); + requestValidator.setWorkingStateManager(workingStateManager); + requestValidator.setWorkflowManager(workflowManager); + requestValidator.setLifecyclemanager(lifecyclemanager); + requestHandler.setCommandExecutor(commandExecutor); + requestHandler.setRequestValidator(requestValidator); + requestHandler.setLockManager(lockManager); + requestHandler.setTransactionRecorder(transactionRecorder); + + doNothing().when(transactionRecorder).store((TransactionRecord) anyObject()); +// Mockito.when(commandExecutor.executeCommand((CommandExecutorInput)anyObject())).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); + for(Integer i=130; i<=140 ; i++) + { + Mockito.when(workingStateManager.isVNFStable(i.toString())).thenReturn(true); + } + Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("40")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("38")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("201")).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("202")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true).thenReturn(false); + Mockito.when(workingStateManager.isVNFStable("302")).thenReturn(true).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("303")).thenReturn(true).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true).thenReturn(true); + Mockito.when(workingStateManager.isVNFStable("310")).thenReturn(true).thenReturn(true); + } + + private void threadSleep(){ + try { + Thread.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Test + public void testNegativeFlowWithRequestingUsedVnfId() throws Exception { + logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("131", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); + RequestHandlerOutput output1 = requestHandler.handleRequest(input1); + threadSleep (); + Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); + logger.debug("testNegativeFlowWithRequestingUsedVnfId"); + logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); + } + + @Test + public void testInvalidVNFExceptionRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testLifecycleException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new LifecycleException(new Exception(),"Configured","test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.INVALID_VNF_STATE.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + + @Test + public void testRequestExpiredException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new RequestExpiredException("")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.EXPIRED_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testMissingVNFdata() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID,Instant.now()); + PowerMockito.doThrow(new MissingVNFDataInAAIException("vnf-type")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testWorkflowNotFoundException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new WorkflowNotFoundException("Unable to find the DG","VNF-2.0.0.0", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode());} + + @Test + public void testDGWorkflowNotFoundException() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + Mockito.when(workflowManager.workflowExists((WorkflowRequest) anyObject())).thenReturn(new WorkflowExistsOutput(true, true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0, false, originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new DGWorkflowNotFoundException("Unable to find the DG", "VNF-2.0.0.0", "temp", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testInvalidInputException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID1 = UUID.randomUUID().toString(); + String requestID1 = UUID.randomUUID().toString(); + String subRequestID1 = UUID.randomUUID().toString(); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID1, requestID1, subRequestID1, Instant.now()); + PowerMockito.doThrow(new InvalidInputException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output1 = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.INVALID_INPUT_PARAMETER.getResponseCode(), output1.getResponseContext().getStatus().getCode()); + } + + @Test + public void testNoTransitionDefinedException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3010", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new NoTransitionDefinedException("Invalid VNF State","Unstable","Test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.NO_TRANSITION_DEFINE.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void rejectInvalidRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testUnstableWorkingState() throws Exception { + logger.debug("=====================testUnstableWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + Mockito.when(workingStateManager.isVNFStable("37")).thenReturn(true,false); + RequestHandlerInput input = this.getRequestHandlerInput("37", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + mockRuntimeContextAndVnfContext(input); + RequestHandlerOutput output = requestHandler.handleRequest(input); + + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + RequestHandlerInput input1 = this.getRequestHandlerInput("37", VNFOperation.Configure,1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); + mockRuntimeContextAndVnfContext(input1); + RequestHandlerOutput output1 = requestHandler.handleRequest(input1); + + Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); + logger.debug("=====================testUnstableWorkingState============================="); + } + + @Test + public void testOnRequestExecutionEndSuccessForWorkingState() throws Exception { + logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"137", "", "", ""),true); + + input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); + } + + private void mockRuntimeContextAndVnfContext(RequestHandlerInput input1) throws Exception { + RuntimeContext runtimeContext = PowerMockito.mock(RuntimeContext.class); + VNFContext vnfContext = new VNFContext(); + vnfContext.setType("SCP"); + vnfContext.setId("137"); + when(runtimeContext.getVnfContext()).thenReturn(vnfContext); + when(runtimeContext.getRequestContext()).thenReturn(input1.getRequestContext()); + when(runtimeContext.getRpcName()).thenReturn(input1.getRpcName()); + + + ResponseContext responseContext = new ResponseContext(); + responseContext.setStatus(new Status(0, null)); + responseContext.setAdditionalContext(new HashMap(4)); + responseContext.setCommonHeader(input1.getRequestContext().getCommonHeader()); + runtimeContext.setResponseContext(responseContext); + when(runtimeContext.getResponseContext()).thenReturn(responseContext); + responseContext.setStatus(new Status(0, null)); + runtimeContext.setResponseContext(responseContext); + PowerMockito.whenNew(RuntimeContext.class).withAnyArguments().thenReturn(runtimeContext); + + } + + @Test + public void testOnRequestExecutionEndFailureForWorkingState() throws Exception { + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + RequestHandlerInput input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.NO_TRANSITION_DEFINE,"38", "", "", ""),true); + + input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + mockRuntimeContextAndVnfContext(input1); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); + + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + } + + @Test + public void testOnRequestExecutionEndTTLExpiredForWorkingState() throws Exception { + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + + RequestHandlerInput input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + mockRuntimeContextAndVnfContext(input1); + + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); + } + + @Test + public void testOnRequestTTLEndForWorkingState() throws Exception { + logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + RequestHandlerInput input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.EXPIRED_REQUEST_FAILURE,"40", "", "", ""); + requestHandler.onRequestTTLEnd(response,true); + input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); + } + + @Test + public void testForceCommandExecution() throws Exception { + logger.debug("=====================testForceCommandExecution============================="); + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + mockRuntimeContextAndVnfContext(input1); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + RequestHandlerOutput output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + threadSleep(); + RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.ACCEPTED,"138", "", "", ""); + requestHandler.onRequestTTLEnd(response,true); + input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, + false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); + input1.getRequestContext().getCommonHeader().setFlags(new Flags(null, true, 1200)); + mockRuntimeContextAndVnfContext(input1); + output = requestHandler.handleRequest(input1); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); + logger.debug("=====================testForceCommandExecution============================="); + } + + @Test + public void testOnRequestExecutionEndSuccess() throws VNFNotFoundException { + logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Starts ============================="); + Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"201", "", "", ""),true); + logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Ends ============================="); + } + + @Test + public void testOnRequestExecutionEndFailure() throws VNFNotFoundException { + logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Starts ============================="); + Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); + requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.DG_FAILURE,"202", "", "", ""),true); + logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Ends ============================="); + } + + private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, boolean force,String originatorId, String requestId, String subRequestId, Instant timeStamp){ + String API_VERSION= "2.0.0"; + RequestHandlerInput input = new RequestHandlerInput(); + RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); + RequestContext requestContext = runtimeContext.getRequestContext(); + input.setRequestContext(requestContext); + requestContext.getActionIdentifiers().setVnfId(vnfID); + requestContext.setAction(action); + input.setRpcName(convertActionNameToUrl(action.name())); + requestContext.getCommonHeader().setRequestId(requestId); + requestContext.getCommonHeader().setSubRequestId(subRequestId); + requestContext.getCommonHeader().setOriginatorId(originatorId); + requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); + requestContext.getCommonHeader().setTimestamp(timeStamp); + requestContext.getCommonHeader().setApiVer(API_VERSION); + return input; + } + + private RuntimeContext getAsyncResponse(boolean wfStatus, LCMCommandStatus commandStatus, String vnfId, String originatorId, String requestId, String subRequestId) + { + RuntimeContext output = createRuntimeContextWithSubObjects(); + + + output.getRequestContext().getActionIdentifiers().setVnfId(vnfId); + output.getVnfContext().setId(vnfId); + output.getResponseContext().getCommonHeader().setApiVer("2.0.0"); + output.getResponseContext().getCommonHeader().setTimestamp( Instant.now()); + output.getResponseContext().setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); + output.setTimeStart( Instant.now()); + output.getResponseContext().getCommonHeader().setOriginatorId(originatorId); + output.getResponseContext().getCommonHeader().setRequestId(requestId); + output.getResponseContext().getCommonHeader().setSubRequestId(subRequestId); + + output.getVnfContext().setType("FIREWALL"); + output.getRequestContext().setAction(VNFOperation.Configure); + output.setRpcName("configure"); + output.getResponseContext().setPayload(""); + return output; + } + + @Test + public void rejectDuplicateRequest() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + input = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + + PowerMockito.doThrow(new DuplicateRequestException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.DUPLICATE_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void removeRequestFromRegistryOnRequestCompletion() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("302", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"302",originatorID,requestID,subRequestID); + requestHandler.onRequestExecutionEnd(asyncResponse,true); + + input = this.getRequestHandlerInput("310", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + @Test + public void removeRequestFromRegistryOnTTLExpiration() throws Exception { + String originatorID = UUID.randomUUID().toString(); + String requestID = UUID.randomUUID().toString(); + String subRequestID = UUID.randomUUID().toString(); + + PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); + + Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); + RequestHandlerInput input = this.getRequestHandlerInput("303", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); + mockRuntimeContextAndVnfContext(input); + RequestHandlerOutput output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + + RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.ACCEPTED,"303",originatorID,requestID,subRequestID); + requestHandler.onRequestTTLEnd(asyncResponse,false); + + output = requestHandler.handleRequest(input); + Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); + } + + /*@Test + public void getMetricserviceTest() throws Exception{ + Method method = RequestHandlerImpl.class.getDeclaredMethod("getMetricservice", null); + method.setAccessible(true); + method.invoke(null, null); + + }*/ + @Test + public void onRequestExecutionStartTest() throws Exception{ + Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); + requestHandler.onRequestExecutionStart("303",false, null, true); + Assert.assertNotNull(requestHandler); + } + + + private RuntimeContext createRuntimeContextWithSubObjects() { + RuntimeContext runtimeContext = new RuntimeContext(); + RequestContext requestContext = new RequestContext(); + runtimeContext.setRequestContext(requestContext); + ResponseContext responseContext = createResponseContextWithSuObjects(); + runtimeContext.setResponseContext(responseContext); + CommonHeader commonHeader = new CommonHeader(); + requestContext.setCommonHeader(commonHeader); + commonHeader.setFlags(new Flags(null, false, 0)); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + requestContext.setActionIdentifiers(actionIdentifiers); + VNFContext vnfContext = new VNFContext(); + runtimeContext.setVnfContext(vnfContext); + return runtimeContext; + + } + + private ResponseContext createResponseContextWithSuObjects(){ + ResponseContext responseContext = new ResponseContext(); + CommonHeader commonHeader = new CommonHeader(); + responseContext.setCommonHeader(commonHeader); + responseContext.setStatus(new Status(0, null)); + commonHeader.setFlags(new Flags(null, false, 0)); + return responseContext; + } + + private String convertActionNameToUrl(String action) { + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1-$2"; + return action.replaceAll(regex, replacement) + .toLowerCase(); + } +} + diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java new file mode 100644 index 000000000..fc14f2ac9 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/workingstatemanager/TestWorkingStateManager.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.workingstatemanager; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.dao.util.AppcJdbcConnectionFactory; +import org.onap.appc.workingstatemanager.impl.WorkingStateManagerImpl; +import org.onap.appc.workingstatemanager.objects.VNFWorkingState; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.UUID; + + + +public class TestWorkingStateManager { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestWorkingStateManager.class); + WorkingStateManagerImpl workingStateManager; + + @Before + public void init() throws Exception { + workingStateManager = new WorkingStateManagerImpl(); + AppcJdbcConnectionFactory appcJdbcConnectionFactory = new AppcJdbcConnectionFactory(); + String schema = "sdnctl"; + appcJdbcConnectionFactory.setSchema(schema); + workingStateManager.setConnectionFactory(appcJdbcConnectionFactory); + String property = ConfigurationFactory.getConfiguration().getProperty(String.format("org.onap.appc.db.url.%s", schema)); + logger.info(property+" will be used as connection URL to mySQL."); + logger.warn("you can set connection URL to other IP by adding -DmysqlIp= in VM Option"); +// System.getProperties().getProperty("mys") + } + + @Test + // this test run on mysql you need to uncomment Ignore and to add -DmysqlIp= in VM Option, to make that test pass successfully. + @Ignore + public void testUpdateWorkingState() { + String vnfId = UUID.randomUUID().toString(); + String myOwnerId = "myOwnerId"; + String otherOwnerId = "otherOwnerId"; + boolean vnfStable = workingStateManager.isVNFStable(vnfId); + logger.info("isVNFStable returns "+vnfStable+" for vnfId "+vnfId); + + //set to unstable with force true + boolean updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + + //negative test - try to set to any value by other ownerId when vnf state is UNSTABLE + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, otherOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, otherOwnerId, false); + Assert.assertFalse(updated); + + //positive test - set with same ownerId and force false + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); + Assert.assertTrue(updated); + Assert.assertTrue(workingStateManager.isVNFStable(vnfId)); + + //positive test - set with otherOwnerId and force false when VNF is stable + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + + //negative test - try to set to any value by myOwnerId when vnf state is UNKNOWN + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); + Assert.assertFalse(updated); + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); + Assert.assertFalse(updated); + + //positive test - try to set to any value by myOwnerId when vnf state is UNKNOWN but with force + updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); + Assert.assertTrue(updated); + Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); + } + + +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java deleted file mode 100644 index 95146fbfa..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/LCMStateManagerImplTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.requesthandler.impl.LCMStateManagerImpl; - -public class LCMStateManagerImplTest { - - LCMStateManager lcmStateManager; - - @Before - public void init() throws Exception { - lcmStateManager = new LCMStateManagerImpl(); - } - - /** - * Test to check the disable LCM operations method - */ - @Test - public void disableLCMOperations() throws Exception { - lcmStateManager.disableLCMOperations(); - Assert.assertFalse(lcmStateManager.isLCMOperationEnabled()); - } - - /** - * Test to check the enable LCM operations method - */ - @Test - public void enableLCMOperations() throws Exception { - lcmStateManager.enableLCMOperations(); - Assert.assertTrue(lcmStateManager.isLCMOperationEnabled()); - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java deleted file mode 100644 index 9339931e8..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/RequestValidatorTest.java +++ /dev/null @@ -1,570 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.appc.domainmodel.lcm.ActionIdentifiers; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.Flags; -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.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.requesthandler.exceptions.InvalidInputException; -import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; -import org.onap.appc.requesthandler.impl.RequestHandlerImpl; -import org.onap.appc.requesthandler.impl.RequestValidatorImpl; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowExistsOutput; -import org.onap.appc.workingstatemanager.WorkingStateManager; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.time.Instant; -import java.util.UUID; - -import static junit.framework.TestCase.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.*; - -@SuppressWarnings("unchecked") -@RunWith(PowerMockRunner.class) -@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class, - RequestValidatorImpl.class, TransactionRecorder.class}) -public class RequestValidatorTest { - private final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); - - private RequestValidatorImpl requestValidator; - - private AAIService aaiAdapter ; - private LifecycleManager lifecyclemanager; - private WorkFlowManager workflowManager; - private WorkingStateManager workingStateManager ; - private LCMStateManager lcmStateManager; - - private final BundleContext bundleContext= Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - - @Before - public void init() throws Exception { - // *** - AAIService 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); - PowerMockito.when(aaiService.query(anyString(),anyBoolean(),anyString(),anyString(),anyString(),anyString(), - anyObject())).thenAnswer(invocation -> { - 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 ; - }); - PowerMockito.when(aaiService.update(anyString(),anyString(), anyObject(),anyString(), anyObject())) - .thenReturn(SvcLogicResource.QueryStatus.SUCCESS); - // *** - - aaiAdapter = Mockito.mock(AAIService.class); - lifecyclemanager= Mockito.mock(LifecycleManager.class); - workflowManager= Mockito.mock(WorkFlowManager.class); - workingStateManager = Mockito.mock(WorkingStateManager.class); - lcmStateManager = Mockito.mock(LCMStateManager.class); - - requestValidator = new RequestValidatorImpl(); - requestValidator.setWorkflowManager(workflowManager); - requestValidator.setLifecyclemanager(lifecyclemanager); - requestValidator.setWorkingStateManager(workingStateManager); - requestValidator.setLcmStateManager(lcmStateManager); - - Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true); - } - - public AAIService getAaiadapter() { - return this.aaiAdapter; - } - - private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, - boolean force, String originatorId, String requestId, - String subRequestId, Instant timeStamp){ - String API_VERSION= "2.0.0"; - RequestHandlerInput input = new RequestHandlerInput(); - RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); - RequestContext requestContext = runtimeContext.getRequestContext(); - input.setRequestContext(requestContext); - requestContext.getActionIdentifiers().setVnfId(vnfID); - requestContext.setAction(action); - if (action != null) { - input.setRpcName(convertActionNameToUrl(action.name())); - } else{ - input.setRpcName(null); - } - requestContext.getCommonHeader().setRequestId(requestId); - requestContext.getCommonHeader().setSubRequestId(subRequestId); - requestContext.getCommonHeader().setOriginatorId(originatorId); - requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); - requestContext.getCommonHeader().getTimeStamp(); - requestContext.getCommonHeader().setApiVer(API_VERSION); - requestContext.getCommonHeader().setTimestamp(timeStamp); - return input; - } - - @Test - public void testNullVnfID() throws Exception { - logger.debug("=====================testNullVnfID============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput(null, VNFOperation.Configure, 30, - false, UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(InvalidInputException e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testNullVnfID============================="); - } - - @Test - public void testPositiveFlowWithConfigure() throws Exception { - logger.debug("=====================testPositiveFlowWithConfigure============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(workingStateManager.isVNFStable("1")).thenReturn(true); - RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNull(ex); - logger.debug("testPositiveFlowWithConfigure"); - logger.debug("=====================testPositiveFlowWithConfigure============================="); - } - - @Test - public void testVnfNotFound() throws Exception { - logger.debug("=====================testVnfNotFound============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("8", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testVnfNotFound============================="); - } - - @Test - public void testNullCommand() throws Exception { - logger.debug("=====================testNullCommand============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("7", null,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(InvalidInputException e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testNullCommand============================="); - } - - @Test - public void testNullVnfIDAndCommand() throws Exception { - logger.debug("=====================testNullVnfIDAndCommand============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput(null, null,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(InvalidInputException e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testNullVnfIDAndCommand============================="); - } - - @Test - public void testWorkflowNotFound() throws Exception { - logger.debug("=====================testWorkflowNotFound============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(false,false)); - RequestHandlerInput input = this.getRequestHandlerInput("10", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testWorkflowNotFound============================="); - } - - @Test - public void testUnstableVnfWithConfigure() throws Exception { - logger.debug("=====================testUnstableVnfWithConfigure============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("11", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithConfigure============================="); - } - - @Test - public void testUnstableVnfWithTest() throws Exception { - logger.debug("=====================testUnstableVnfWithTest============================="); - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - RequestHandlerInput input = this.getRequestHandlerInput("12", VNFOperation.Test,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithTest============================="); - } - - @Test - public void testUnstableVnfWithStart() throws Exception { - logger.debug("=====================testUnstableVnfWithStart============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("13", VNFOperation.Start,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithStart============================="); - } - - @Test - public void testUnstableVnfWithTerminate() throws Exception { - logger.debug("=====================testUnstableVnfWithTerminate============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - RequestHandlerInput input = this.getRequestHandlerInput("14", VNFOperation.Terminate,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithTerminate============================="); - } - - @Test - public void testUnstableVnfWithRestart() throws Exception { - logger.debug("=====================testUnstableVnfWithRestart============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("26", VNFOperation.Restart,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithRestart============================="); - } - - @Test - public void testUnstableVnfWithRebuild() throws Exception { - logger.debug("=====================testUnstableVnfWithRebuild============================="); - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(),anyString())) - .thenThrow( new NoTransitionDefinedException("","","")); - - RequestHandlerInput input = this.getRequestHandlerInput("27", VNFOperation.Rebuild,30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testUnstableVnfWithRebuild============================="); - } - - @Test - public void testAAIDown() throws Exception { - logger.debug("=====================testAAIDown============================="); - RequestHandlerInput input = this.getRequestHandlerInput("28", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), - Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("=====================testAAIDown============================="); - } - - @Test - public void testNegativeFlowWithTimeStamp() throws Exception { - logger.debug("=====================testNegativeFlowWithTimeStamp============================="); - Instant now = Instant.now(); - Instant past = now.minusMillis(1000000); - RequestHandlerInput input = this.getRequestHandlerInput("35", VNFOperation.Configure, 30, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(),past); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - logger.debug("testNegativeFlowWithTimeStamp"); - logger.debug("=====================testNegativeFlowWithTimeStamp============================="); - } - - @Test - public void rejectDuplicateRequest() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - Mockito.when(workflowManager.workflowExists(anyObject())) - .thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true); - RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false, - originatorID, requestID, subRequestID, Instant.now()); - - RequestHandlerInput input1 = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false, - originatorID, requestID, subRequestID, Instant.now()); - Exception ex =null; - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - RuntimeContext runtimeContext1 = putInputToRuntimeContext(input1); - - try { - requestValidator.validateRequest(runtimeContext); - }catch(Exception e ) { - ex = e; - } - assertNull(ex); - - try { - requestValidator.validateRequest(runtimeContext1); - }catch(Exception e ) { - ex = e; - } - assertNotNull(ex); - } - - @Test - public void testLockOperation() throws Exception { - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Lock); - } - - @Test - public void testUnlockOperation() throws Exception { - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Unlock); - } - - @Test - public void testCheckLockOperation() throws Exception { - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.CheckLock); - } - - @Test(expected = NoTransitionDefinedException.class) - public void testLockOperationNegative() throws Exception { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Lock.toString()))) - .thenThrow(new NoTransitionDefinedException("", "", "")); - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Lock); - } - - @Test(expected = NoTransitionDefinedException.class) - public void testUnlockOperationNegative() throws Exception { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.Unlock.toString()))) - .thenThrow(new NoTransitionDefinedException("", "", "")); - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.Unlock); - } - - @Test(expected = NoTransitionDefinedException.class) - public void testCheckLockOperationNegative() throws Exception { - Mockito.when(lifecyclemanager.getNextState(anyString(), anyString(), eq(VNFOperation.CheckLock.toString()))) - .thenThrow(new NoTransitionDefinedException("", "", "")); - Mockito.when(workingStateManager.isVNFStable("no-matter")).thenReturn(true); - testOperation("no-matter", VNFOperation.CheckLock); - } - - @Test(expected = LCMOperationsDisabledException.class) - public void testLCMOperationsDisabled() throws Exception { - Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(false); - testOperation("no-matter", VNFOperation.Configure); - } - private void testOperation(String resource, VNFOperation operation) throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0, false, originatorID, - requestID, subRequestID, Instant.now()); - RuntimeContext runtimeContext = putInputToRuntimeContext(input); - requestValidator.validateRequest(runtimeContext); - } - - private RuntimeContext createRuntimeContextWithSubObjects() { - RuntimeContext runtimeContext = new RuntimeContext(); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - ResponseContext responseContext = createResponseContextWithSuObjects(); - runtimeContext.setResponseContext(responseContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - return runtimeContext; - - } - - private ResponseContext createResponseContextWithSuObjects(){ - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - - private String convertActionNameToUrl(String action) { - String regex = "([a-z])([A-Z]+)"; - String replacement = "$1-$2"; - return action.replaceAll(regex, replacement) - .toLowerCase(); - } - - private RuntimeContext putInputToRuntimeContext(RequestHandlerInput input) { - RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); - runtimeContext.setRequestContext(input.getRequestContext()); - runtimeContext.setRpcName(input.getRpcName()); - runtimeContext.getVnfContext().setId(input.getRequestContext().getActionIdentifiers().getVnfId()); - return runtimeContext; - } -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java deleted file mode 100644 index a65af669b..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestConverter.java +++ /dev/null @@ -1,372 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Assert; -import org.junit.Test; -import org.onap.appc.domainmodel.lcm.*; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.requesthandler.conv.Converter; - -import java.text.ParseException; -import java.time.Instant; -import java.util.Date; -import java.util.HashMap; - - -public class TestConverter { - private String expectedJsonBodyStr ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; - private String expectedDmaapOutgoingMessageJsonStringTest ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"test\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringRollback ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"rollback\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringSnapshot ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"snapshot\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringAudit ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"audit\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringHealthCheck ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"health-check\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringLiveUpgrade ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"live-upgrade\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringLock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"lock\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringModifyConfig ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"config-modify\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringSoftwareUpload ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"software-upload\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringStop ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"stop\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringSync ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"sync\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringTerminate ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"terminate\",\"type\":\"response\"}"; - private String expectedDmaapOutgoingMessageJsonStringUnlock ="{\"body\":{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}},\"cambria.partition\":\"MSO\",\"correlation-id\":\"reqid\",\"rpc-name\":\"unlock\",\"type\":\"response\"}"; - private String expectedJsonBodyStrwithPayload ="{\"output\":{\"common-header\":{\"api-ver\":\"2.0.0\",\"flags\":{},\"originator-id\":\"oid\",\"request-id\":\"reqid\",\"timestamp\":\"1970-01-01T00:00:01.000Z\"},\"payload\":\"{}\",\"status\":{\"code\":400,\"message\":\"SUCCESS - request has been processed successfully\"}}}"; - - @Test - public void convDateToZuluStringTest(){ - String dateToZuluString = Converter.convDateToZuluString(new Date(0L)); - Assert.assertEquals("1970-01-01T00:00:00.000Z", dateToZuluString); - } - - @Test - public void convAsyncResponseToBuilderTestTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Test; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringTestTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Test; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTest,jsonStr); - } - - @Test - public void convPayloadObjectToJsonStringTest() throws JsonProcessingException, ParseException { - String jsonString = Converter.convPayloadObjectToJsonString("any valid JSON string value"); - Assert.assertEquals("any valid JSON string value", jsonString); - - HashMap hashMap = new HashMap<>(); - hashMap.put("key","value"); - jsonString = Converter.convPayloadObjectToJsonString(hashMap); - Assert.assertEquals("{\"key\":\"value\"}", jsonString); - } - - @Test - public void convAsyncResponseToBuilderRollbackTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Rollback; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringRollbackTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Rollback; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringRollback,jsonStr); - } - - @Test - public void convAsyncResponseToBuilderSnapshotTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Snapshot; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringSnapshotTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Snapshot; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSnapshot,jsonStr); - } - @Test - public void convAsyncResponseToBuilderAuditTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Audit; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringAuditTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Audit; - String rpcName = action.name().toLowerCase(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringAudit,jsonStr); - } - @Test - public void convAsyncResponseToBuilderHealthCheckTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.HealthCheck; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringHealthCheckTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.HealthCheck; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringHealthCheck,jsonStr); - } - @Test - public void convAsyncResponseToBuilderLiveUpgradeTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.LiveUpgrade; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringLiveUpgradeTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.LiveUpgrade; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLiveUpgrade,jsonStr); - } - @Test - public void convAsyncResponseToBuilderLockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Lock; - String rpcName = convertActionNameToUrl(action.name()); - - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringLockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Lock; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringLock,jsonStr); - } - @Test - public void convAsyncResponseToBuilderModifyConfigTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.ConfigModify; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringModifyConfigTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.ConfigModify; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringModifyConfig,jsonStr); - } - @Test - public void convAsyncResponseToBuilderSoftwareUploadTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.SoftwareUpload; - String rpcName = convertActionNameToUrl(action.name()); - - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringSoftwareUploadTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.SoftwareUpload; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSoftwareUpload,jsonStr); - } - @Test - public void convAsyncResponseToBuilderStopTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Stop; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringStopTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Stop; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringStop,jsonStr); - } - @Test - public void convAsyncResponseToBuilderSync() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Sync; - String rpcName = convertActionNameToUrl(action.name()); - - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringSync() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Sync; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringSync,jsonStr); - } - @Test - public void convAsyncResponseToBuilderTerminateTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponsewithPayload(); - VNFOperation action = VNFOperation.Sync; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStrwithPayload,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringTerminateTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Terminate; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringTerminate,jsonStr); - } - @Test - public void convAsyncResponseToBuilderUnlockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Unlock; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(action, rpcName, asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringUnlockTest() throws JsonProcessingException { - ResponseContext asyncResponse = buildAsyncResponse(); - VNFOperation action = VNFOperation.Unlock; - String rpcName = convertActionNameToUrl(action.name()); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(action, rpcName, asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonStringUnlock,jsonStr); - } - /*@Test - public void convAsyncResponseToBuilderTest() throws JsonProcessingException { - AsyncResponse asyncResponse = buildAsyncResponse(); - String jsonStr = Converter.convAsyncResponseToJsonStringBody(asyncResponse); - Assert.assertEquals(expectedJsonBodyStr,jsonStr); - } - - @Test - public void convAsyncResponseToDmaapOutgoingMessageJsonStringTest() throws JsonProcessingException { - AsyncResponse asyncResponse = buildAsyncResponse(); - String jsonStr = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(asyncResponse); - System.out.println("jsonStr = " + jsonStr); - Assert.assertEquals(expectedDmaapOutgoingMessageJsonString,jsonStr); - }*/ - - - private ResponseContext buildAsyncResponse() { - ResponseContext asyncResponse = createResponseContextWithSubObjects(); - asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); - asyncResponse.getCommonHeader().setOriginatorId("oid"); - asyncResponse.getCommonHeader().setApiVer("2.0.0"); - asyncResponse.getCommonHeader().setRequestId("reqid"); - asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); - asyncResponse.setPayload("any valid JSON string value. Json escape characters need to be added to make it a valid json string value"); - return asyncResponse; - } - - private ResponseContext buildAsyncResponsewithPayload() { - ResponseContext asyncResponse = createResponseContextWithSubObjects(); - asyncResponse.setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); - asyncResponse.getCommonHeader().setOriginatorId("oid"); - asyncResponse.getCommonHeader().setApiVer("2.0.0"); - asyncResponse.getCommonHeader().setRequestId("reqid"); - asyncResponse.getCommonHeader().setTimestamp(Instant.ofEpochMilli(1000L)); - asyncResponse.setPayload("{}"); - return asyncResponse; - } - - private ResponseContext createResponseContextWithSubObjects() { - - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - - private String convertActionNameToUrl(String action) { - String regex = "([a-z])([A-Z]+)"; - String replacement = "$1-$2"; - return action.replaceAll(regex, replacement) - .toLowerCase(); - } - - -} - - - diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java deleted file mode 100644 index dfb45389d..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java +++ /dev/null @@ -1,649 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.requesthandler; - -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.time.Instant; -import java.util.HashMap; -import java.util.UUID; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.onap.appc.adapter.factory.DmaapMessageAdapterFactoryImpl; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl; -import org.onap.appc.configuration.Configuration; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.domainmodel.lcm.*; -import org.onap.appc.domainmodel.lcm.Flags.Mode; -import org.onap.appc.domainmodel.lcm.ActionIdentifiers; -import org.onap.appc.domainmodel.lcm.CommonHeader; -import org.onap.appc.domainmodel.lcm.Flags; -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.VNFContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; -import org.onap.appc.executor.CommandExecutor; -import org.onap.appc.executor.UnstableVNFException; -import org.onap.appc.executor.objects.LCMCommandStatus; -import org.onap.appc.lifecyclemanager.LifecycleManager; -import org.onap.appc.lifecyclemanager.objects.LifecycleException; -import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; -import org.onap.appc.lockmanager.api.LockException; -import org.onap.appc.lockmanager.api.LockManager; -import org.onap.appc.messageadapter.MessageAdapter; -import org.onap.appc.messageadapter.impl.MessageAdapterImpl; -import org.onap.appc.requesthandler.exceptions.*; -import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; -import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; -import org.onap.appc.requesthandler.exceptions.InvalidInputException; -import org.onap.appc.requesthandler.exceptions.RequestExpiredException; -import org.onap.appc.requesthandler.exceptions.VNFNotFoundException; -import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; -import org.onap.appc.requesthandler.impl.RequestHandlerImpl; -import org.onap.appc.requesthandler.impl.RequestValidatorImpl; -import org.onap.appc.requesthandler.objects.RequestHandlerInput; -import org.onap.appc.requesthandler.objects.RequestHandlerOutput; -import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.onap.appc.transactionrecorder.objects.TransactionRecord; -import org.onap.appc.workflow.WorkFlowManager; -import org.onap.appc.workflow.objects.WorkflowExistsOutput; -import org.onap.appc.workflow.objects.WorkflowRequest; -import org.onap.appc.workingstatemanager.WorkingStateManager; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@Ignore -@RunWith(PowerMockRunner.class) -@PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class,RequestValidatorImpl.class, TransactionRecorder.class, MessageAdapterImpl.class}) -public class TestRequestHandler { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestRequestHandler.class); - - private RequestHandlerImpl requestHandler; - private RequestValidatorImpl requestValidator; - private WorkFlowManager workflowManager; - private WorkingStateManager workingStateManager ; - private LockManager lockManager; - private Configuration configuration; - - private final BundleContext bundleContext=Mockito.mock(BundleContext.class); - private final Bundle bundleService=Mockito.mock(Bundle.class); - private final ServiceReference sref=Mockito.mock(ServiceReference.class); - MessageAdapterFactory factory = new DmaapMessageAdapterFactoryImpl(); - - - @Before - public void init() throws Exception { - configuration = ConfigurationFactory.getConfiguration(); - - configuration.setProperty("appc.LCM.topic.write" , "TEST"); - configuration.setProperty("appc.LCM.client.key" , "TEST"); - configuration.setProperty("appc.LCM.client.secret" , "TEST"); - - PowerMockito.mockStatic(FrameworkUtil.class); - PowerMockito.when(FrameworkUtil.getBundle(MessageAdapterImpl.class)).thenReturn(bundleService); - PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); - PowerMockito.when(bundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(sref); - PowerMockito.when(bundleContext.getService(sref)).thenReturn(factory); - - - requestHandler = new RequestHandlerImpl(); - LifecycleManager lifecyclemanager= mock(LifecycleManager.class); - workflowManager= mock(WorkFlowManager.class); - CommandExecutor commandExecutor= mock(CommandExecutor.class); - MessageAdapter messageAdapter = mock(MessageAdapter.class); - workingStateManager = mock(WorkingStateManager.class); - lockManager = mock(LockManager.class); - TransactionRecorder transactionRecorder= mock(TransactionRecorder.class); - - requestHandler.setWorkingStateManager(workingStateManager); - requestHandler.setMessageAdapter(messageAdapter); - requestValidator = mock(RequestValidatorImpl.class); - requestValidator.setLifecyclemanager(lifecyclemanager); - requestValidator.setWorkingStateManager(workingStateManager); - requestValidator.setWorkflowManager(workflowManager); - requestValidator.setLifecyclemanager(lifecyclemanager); - requestHandler.setCommandExecutor(commandExecutor); - requestHandler.setRequestValidator(requestValidator); - requestHandler.setLockManager(lockManager); - requestHandler.setTransactionRecorder(transactionRecorder); - - doNothing().when(transactionRecorder).store((TransactionRecord) anyObject()); -// Mockito.when(commandExecutor.executeCommand((CommandExecutorInput)anyObject())).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); - for(Integer i=130; i<=140 ; i++) - { - Mockito.when(workingStateManager.isVNFStable(i.toString())).thenReturn(true); - } - Mockito.when(workingStateManager.isVNFStable("39")).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("40")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("38")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("201")).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("202")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("301")).thenReturn(true).thenReturn(false); - Mockito.when(workingStateManager.isVNFStable("302")).thenReturn(true).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("303")).thenReturn(true).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("309")).thenReturn(true).thenReturn(true); - Mockito.when(workingStateManager.isVNFStable("310")).thenReturn(true).thenReturn(true); - } - - private void threadSleep(){ - try { - Thread.sleep(5); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @Test - public void testNegativeFlowWithRequestingUsedVnfId() throws Exception { - logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("131", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); - RequestHandlerOutput output1 = requestHandler.handleRequest(input1); - threadSleep (); - Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); - logger.debug("testNegativeFlowWithRequestingUsedVnfId"); - logger.debug("=====================testNegativeFlowWithRequestingUsedVnfId============================="); - } - - @Test - public void testInvalidVNFExceptionRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testLifecycleException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new LifecycleException(new Exception(),"Configured","test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.INVALID_VNF_STATE.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - - @Test - public void testRequestExpiredException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new RequestExpiredException("")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.EXPIRED_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testMissingVNFdata() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID,Instant.now()); - PowerMockito.doThrow(new MissingVNFDataInAAIException("vnf-type")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testWorkflowNotFoundException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new WorkflowNotFoundException("Unable to find the DG","VNF-2.0.0.0", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode());} - - @Test - public void testDGWorkflowNotFoundException() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - Mockito.when(workflowManager.workflowExists((WorkflowRequest) anyObject())).thenReturn(new WorkflowExistsOutput(true, true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure, 0, false, originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new DGWorkflowNotFoundException("Unable to find the DG", "VNF-2.0.0.0", "temp", "Test")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testInvalidInputException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID1 = UUID.randomUUID().toString(); - String requestID1 = UUID.randomUUID().toString(); - String subRequestID1 = UUID.randomUUID().toString(); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID1, requestID1, subRequestID1, Instant.now()); - PowerMockito.doThrow(new InvalidInputException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output1 = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.INVALID_INPUT_PARAMETER.getResponseCode(), output1.getResponseContext().getStatus().getCode()); - } - - @Test - public void testNoTransitionDefinedException() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3010", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new NoTransitionDefinedException("Invalid VNF State","Unstable","Test event")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.NO_TRANSITION_DEFINE.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void rejectInvalidRequest() throws NoTransitionDefinedException, LifecycleException, InvalidInputException, RequestExpiredException, UnstableVNFException, DuplicateRequestException, VNFNotFoundException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("3009", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - PowerMockito.doThrow(new VNFNotFoundException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.VNF_NOT_FOUND.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void testUnstableWorkingState() throws Exception { - logger.debug("=====================testUnstableWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - Mockito.when(workingStateManager.isVNFStable("37")).thenReturn(true,false); - RequestHandlerInput input = this.getRequestHandlerInput("37", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - mockRuntimeContextAndVnfContext(input); - RequestHandlerOutput output = requestHandler.handleRequest(input); - - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - RequestHandlerInput input1 = this.getRequestHandlerInput("37", VNFOperation.Configure,1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); - mockRuntimeContextAndVnfContext(input1); - RequestHandlerOutput output1 = requestHandler.handleRequest(input1); - - Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(), output1.getResponseContext().getStatus().getCode()); - logger.debug("=====================testUnstableWorkingState============================="); - } - - @Test - public void testOnRequestExecutionEndSuccessForWorkingState() throws Exception { - logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"137", "", "", ""),true); - - input1 = this.getRequestHandlerInput("137", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testOnRequestExecutionEndSuccessForWorkingState============================="); - } - - private void mockRuntimeContextAndVnfContext(RequestHandlerInput input1) throws Exception { - RuntimeContext runtimeContext = PowerMockito.mock(RuntimeContext.class); - VNFContext vnfContext = new VNFContext(); - vnfContext.setType("SCP"); - vnfContext.setId("137"); - when(runtimeContext.getVnfContext()).thenReturn(vnfContext); - when(runtimeContext.getRequestContext()).thenReturn(input1.getRequestContext()); - when(runtimeContext.getRpcName()).thenReturn(input1.getRpcName()); - - - ResponseContext responseContext = new ResponseContext(); - responseContext.setStatus(new Status(0, null)); - responseContext.setAdditionalContext(new HashMap(4)); - responseContext.setCommonHeader(input1.getRequestContext().getCommonHeader()); - runtimeContext.setResponseContext(responseContext); - when(runtimeContext.getResponseContext()).thenReturn(responseContext); - responseContext.setStatus(new Status(0, null)); - runtimeContext.setResponseContext(responseContext); - PowerMockito.whenNew(RuntimeContext.class).withAnyArguments().thenReturn(runtimeContext); - - } - - @Test - public void testOnRequestExecutionEndFailureForWorkingState() throws Exception { - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - RequestHandlerInput input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.NO_TRANSITION_DEFINE,"38", "", "", ""),true); - - input1 = this.getRequestHandlerInput("38", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - mockRuntimeContextAndVnfContext(input1); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); - - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - } - - @Test - public void testOnRequestExecutionEndTTLExpiredForWorkingState() throws Exception { - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - - RequestHandlerInput input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - mockRuntimeContextAndVnfContext(input1); - - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - input1 = this.getRequestHandlerInput("39", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new LockException(" ")).when(lockManager).acquireLock(Matchers.anyString(), Matchers.anyString(), Matchers.anyByte()); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.LOCKING_FAILURE.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testOnRequestExecutionEndFailureForWorkingState============================="); - } - - @Test - public void testOnRequestTTLEndForWorkingState() throws Exception { - logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - RequestHandlerInput input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.EXPIRED_REQUEST_FAILURE,"40", "", "", ""); - requestHandler.onRequestTTLEnd(response,true); - input1 = this.getRequestHandlerInput("40", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - PowerMockito.doThrow(new UnstableVNFException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.UNSTABLE_VNF.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testOnRequestTTLEndForWorkingState============================="); - } - - @Test - public void testForceCommandExecution() throws Exception { - logger.debug("=====================testForceCommandExecution============================="); - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - mockRuntimeContextAndVnfContext(input1); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - RequestHandlerOutput output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - threadSleep(); - RuntimeContext response = this.getAsyncResponse(false,LCMCommandStatus.ACCEPTED,"138", "", "", ""); - requestHandler.onRequestTTLEnd(response,true); - input1 = this.getRequestHandlerInput("138", VNFOperation.Configure, 1200, - false,UUID.randomUUID().toString(),UUID.randomUUID().toString(),UUID.randomUUID().toString(), Instant.now()); - input1.getRequestContext().getCommonHeader().setFlags(new Flags(null, true, 1200)); - mockRuntimeContextAndVnfContext(input1); - output = requestHandler.handleRequest(input1); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(),output.getResponseContext().getStatus().getCode()); - logger.debug("=====================testForceCommandExecution============================="); - } - - @Test - public void testOnRequestExecutionEndSuccess() throws VNFNotFoundException { - logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Starts ============================="); - Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"201", "", "", ""),true); - logger.debug("=====================Positive TEST - On Request Execution End SUCCESS- Ends ============================="); - } - - @Test - public void testOnRequestExecutionEndFailure() throws VNFNotFoundException { - logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Starts ============================="); - Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); - requestHandler.onRequestExecutionEnd(this.getAsyncResponse(false,LCMCommandStatus.DG_FAILURE,"202", "", "", ""),true); - logger.debug("=====================Positive TEST - On Request Execution End FAILURE- Ends ============================="); - } - - private RequestHandlerInput getRequestHandlerInput(String vnfID, VNFOperation action, int ttl, boolean force,String originatorId, String requestId, String subRequestId, Instant timeStamp){ - String API_VERSION= "2.0.0"; - RequestHandlerInput input = new RequestHandlerInput(); - RuntimeContext runtimeContext = createRuntimeContextWithSubObjects(); - RequestContext requestContext = runtimeContext.getRequestContext(); - input.setRequestContext(requestContext); - requestContext.getActionIdentifiers().setVnfId(vnfID); - requestContext.setAction(action); - input.setRpcName(convertActionNameToUrl(action.name())); - requestContext.getCommonHeader().setRequestId(requestId); - requestContext.getCommonHeader().setSubRequestId(subRequestId); - requestContext.getCommonHeader().setOriginatorId(originatorId); - requestContext.getCommonHeader().setFlags(new Flags(null, force, ttl)); - requestContext.getCommonHeader().setTimestamp(timeStamp); - requestContext.getCommonHeader().setApiVer(API_VERSION); - return input; - } - - private RuntimeContext getAsyncResponse(boolean wfStatus, LCMCommandStatus commandStatus, String vnfId, String originatorId, String requestId, String subRequestId) - { - RuntimeContext output = createRuntimeContextWithSubObjects(); - - - output.getRequestContext().getActionIdentifiers().setVnfId(vnfId); - output.getVnfContext().setId(vnfId); - output.getResponseContext().getCommonHeader().setApiVer("2.0.0"); - output.getResponseContext().getCommonHeader().setTimestamp( Instant.now()); - output.getResponseContext().setStatus(LCMCommandStatus.SUCCESS.toStatus(null)); - output.setTimeStart( Instant.now()); - output.getResponseContext().getCommonHeader().setOriginatorId(originatorId); - output.getResponseContext().getCommonHeader().setRequestId(requestId); - output.getResponseContext().getCommonHeader().setSubRequestId(subRequestId); - - output.getVnfContext().setType("FIREWALL"); - output.getRequestContext().setAction(VNFOperation.Configure); - output.setRpcName("configure"); - output.getResponseContext().setPayload(""); - return output; - } - - @Test - public void rejectDuplicateRequest() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - input = this.getRequestHandlerInput("309", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - - PowerMockito.doThrow(new DuplicateRequestException(" ")).when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.DUPLICATE_REQUEST.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void removeRequestFromRegistryOnRequestCompletion() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("302", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.SUCCESS,"302",originatorID,requestID,subRequestID); - requestHandler.onRequestExecutionEnd(asyncResponse,true); - - input = this.getRequestHandlerInput("310", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - @Test - public void removeRequestFromRegistryOnTTLExpiration() throws Exception { - String originatorID = UUID.randomUUID().toString(); - String requestID = UUID.randomUUID().toString(); - String subRequestID = UUID.randomUUID().toString(); - - PowerMockito.doNothing().when(requestValidator).validateRequest(Matchers.any(RuntimeContext.class)); - - Mockito.when(workflowManager.workflowExists((WorkflowRequest)anyObject())).thenReturn(new WorkflowExistsOutput(true,true)); - RequestHandlerInput input = this.getRequestHandlerInput("303", VNFOperation.Configure,0,false,originatorID, requestID, subRequestID, Instant.now()); - mockRuntimeContextAndVnfContext(input); - RequestHandlerOutput output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - - RuntimeContext asyncResponse = this.getAsyncResponse(true,LCMCommandStatus.ACCEPTED,"303",originatorID,requestID,subRequestID); - requestHandler.onRequestTTLEnd(asyncResponse,false); - - output = requestHandler.handleRequest(input); - Assert.assertEquals(LCMCommandStatus.ACCEPTED.getResponseCode(), output.getResponseContext().getStatus().getCode()); - } - - /*@Test - public void getMetricserviceTest() throws Exception{ - Method method = RequestHandlerImpl.class.getDeclaredMethod("getMetricservice", null); - method.setAccessible(true); - method.invoke(null, null); - - }*/ - @Test - public void onRequestExecutionStartTest() throws Exception{ - Mockito.doReturn(true).when(workingStateManager).setWorkingState(anyString(),(VNFWorkingState) anyObject(), anyString(),anyBoolean()); - requestHandler.onRequestExecutionStart("303",false, null, true); - Assert.assertNotNull(requestHandler); - } - - - private RuntimeContext createRuntimeContextWithSubObjects() { - RuntimeContext runtimeContext = new RuntimeContext(); - RequestContext requestContext = new RequestContext(); - runtimeContext.setRequestContext(requestContext); - ResponseContext responseContext = createResponseContextWithSuObjects(); - runtimeContext.setResponseContext(responseContext); - CommonHeader commonHeader = new CommonHeader(); - requestContext.setCommonHeader(commonHeader); - commonHeader.setFlags(new Flags(null, false, 0)); - ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); - requestContext.setActionIdentifiers(actionIdentifiers); - VNFContext vnfContext = new VNFContext(); - runtimeContext.setVnfContext(vnfContext); - return runtimeContext; - - } - - private ResponseContext createResponseContextWithSuObjects(){ - ResponseContext responseContext = new ResponseContext(); - CommonHeader commonHeader = new CommonHeader(); - responseContext.setCommonHeader(commonHeader); - responseContext.setStatus(new Status(0, null)); - commonHeader.setFlags(new Flags(null, false, 0)); - return responseContext; - } - - private String convertActionNameToUrl(String action) { - String regex = "([a-z])([A-Z]+)"; - String replacement = "$1-$2"; - return action.replaceAll(regex, replacement) - .toLowerCase(); - } -} - diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java deleted file mode 100644 index fc14f2ac9..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/workingstatemanager/TestWorkingStateManager.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : APPC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= - * 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. - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * ============LICENSE_END========================================================= - */ - -package org.onap.appc.workingstatemanager; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.appc.configuration.ConfigurationFactory; -import org.onap.appc.dao.util.AppcJdbcConnectionFactory; -import org.onap.appc.workingstatemanager.impl.WorkingStateManagerImpl; -import org.onap.appc.workingstatemanager.objects.VNFWorkingState; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.UUID; - - - -public class TestWorkingStateManager { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestWorkingStateManager.class); - WorkingStateManagerImpl workingStateManager; - - @Before - public void init() throws Exception { - workingStateManager = new WorkingStateManagerImpl(); - AppcJdbcConnectionFactory appcJdbcConnectionFactory = new AppcJdbcConnectionFactory(); - String schema = "sdnctl"; - appcJdbcConnectionFactory.setSchema(schema); - workingStateManager.setConnectionFactory(appcJdbcConnectionFactory); - String property = ConfigurationFactory.getConfiguration().getProperty(String.format("org.onap.appc.db.url.%s", schema)); - logger.info(property+" will be used as connection URL to mySQL."); - logger.warn("you can set connection URL to other IP by adding -DmysqlIp= in VM Option"); -// System.getProperties().getProperty("mys") - } - - @Test - // this test run on mysql you need to uncomment Ignore and to add -DmysqlIp= in VM Option, to make that test pass successfully. - @Ignore - public void testUpdateWorkingState() { - String vnfId = UUID.randomUUID().toString(); - String myOwnerId = "myOwnerId"; - String otherOwnerId = "otherOwnerId"; - boolean vnfStable = workingStateManager.isVNFStable(vnfId); - logger.info("isVNFStable returns "+vnfStable+" for vnfId "+vnfId); - - //set to unstable with force true - boolean updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - - //negative test - try to set to any value by other ownerId when vnf state is UNSTABLE - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, otherOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, otherOwnerId, false); - Assert.assertFalse(updated); - - //positive test - set with same ownerId and force false - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); - Assert.assertTrue(updated); - Assert.assertTrue(workingStateManager.isVNFStable(vnfId)); - - //positive test - set with otherOwnerId and force false when VNF is stable - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, otherOwnerId, false); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - - //negative test - try to set to any value by myOwnerId when vnf state is UNKNOWN - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNKNOWN, myOwnerId, false); - Assert.assertFalse(updated); - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.STABLE, myOwnerId, false); - Assert.assertFalse(updated); - - //positive test - try to set to any value by myOwnerId when vnf state is UNKNOWN but with force - updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, myOwnerId, true); - Assert.assertTrue(updated); - Assert.assertFalse(workingStateManager.isVNFStable(vnfId)); - } - - -} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties new file mode 100644 index 000000000..80e77b261 --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/onap/appc/default.properties @@ -0,0 +1,98 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options +#org.onap.appc.bootstrap.file=executor-test.properties +org.onap.appc.bootstrap.file=appc.properties +org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +# +# Certificate keystore and truststore +# +#org.openecomp.sdnc.sli.aai.ssl.trust= +#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin +#org.openecomp.sdnc.sli.aai.ssl.key= +#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin +org.openecomp.sdnc.sli.aai.host.certificate.ignore=true +org.openecomp.sdnc.sli.aai.certificate.trust.all=true + +# +# Configuration file for A&AI Adapter +# + +# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT +org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 + +org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query + +# service instance +org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances +org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance + +# complex +org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes +org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} + +# vservers +org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers +org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} + +# generic-vnf +org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ +org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} + +# +# Formatting +# +org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s +org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type +org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id +org.openecomp.sdnc.sli.aai.param.service.type=service-type + + +org.onap.appc.logging.path=${user.home},etc,../etc,. +org.onap.appc.logging.file=logback.xml + +org.onap.appc.db.url.%s", schema), ""); +org.onap.appc.db.user.%s", schema), ""); +org.onap.appc.db.pass.%s", schema), ""); + + +#Property below provided by appc.properties +appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm +appc.LCM.poolMembers=:3904 +appc.LCM.service=dmaap +appc.LCM.topic.write=APPC-TEST2 +appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HDLR-TEST +appc.LCM.provider.user=test +appc.LCM.provider.pass=test + + + +mysqlIp=127.0.0.1 +org.onap.appc.db.url.sdnctl=jdbc:mysql://${mysqlIp}:3306/test +org.onap.appc.db.user.sdnctl=test +org.onap.appc.db.pass.sdnctl=123456 + +org.onap.appc.workingstatemanager.maxAttempts=2 diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties deleted file mode 100644 index 80e77b261..000000000 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/resources/org/openecomp/appc/default.properties +++ /dev/null @@ -1,98 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : APPC -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Copyright (C) 2017 Amdocs -# ============================================================================= -# 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. -# -# ECOMP is a trademark and service mark of AT&T Intellectual Property. -# ============LICENSE_END========================================================= -### - -# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded to supply configuration options -#org.onap.appc.bootstrap.file=executor-test.properties -org.onap.appc.bootstrap.file=appc.properties -org.onap.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. - -# -# Certificate keystore and truststore -# -#org.openecomp.sdnc.sli.aai.ssl.trust= -#org.openecomp.sdnc.sli.aai.ssl.trust.psswd=adminadmin -#org.openecomp.sdnc.sli.aai.ssl.key= -#org.openecomp.sdnc.sli.aai.ssl.key.psswd=adminadmin -org.openecomp.sdnc.sli.aai.host.certificate.ignore=true -org.openecomp.sdnc.sli.aai.certificate.trust.all=true - -# -# Configuration file for A&AI Adapter -# - -# OPEN SOURCE - EXTERNAL A&AI INSTANCE IN TEST ENVIRONMENT -org.openecomp.sdnc.sli.aai.uri=https://10.0.1.1:8443 - -org.openecomp.sdnc.sli.aai.path.query=/aai/v8/search/sdn-zone-query - -# service instance -org.openecomp.sdnc.sli.aai.path.svcinst=/aai/v8/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances -org.openecomp.sdnc.sli.aai.path.svcinst.query=/aai/v8/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance - -# complex -org.openecomp.sdnc.sli.aai.path.complexes=/aai/v8/cloud-infrastructure/complexes -org.openecomp.sdnc.sli.aai.path.complex=/aai/v8/cloud-infrastructure/complexes/complex/{physical-location-id} - -# vservers -org.openecomp.sdnc.sli.aai.path.vservers=/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers -org.openecomp.sdnc.sli.aai.path.vserver =/aai/v8/cloud-infrastructure/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id} - -# generic-vnf -org.openecomp.sdnc.sli.aai.path.generic.vnfs=/aai/v8/network/generic-vnfs/generic-vnf/ -org.openecomp.sdnc.sli.aai.path.generic.vnf=/aai/v8/network/generic-vnfs/generic-vnf/{vnf-id} - -# -# Formatting -# -org.openecomp.sdnc.sli.aai.param.format=filter=%s:%s -org.openecomp.sdnc.sli.aai.param.vnf_type=vnf-type -org.openecomp.sdnc.sli.aai.param.physical.location.id=physical-location-id -org.openecomp.sdnc.sli.aai.param.service.type=service-type - - -org.onap.appc.logging.path=${user.home},etc,../etc,. -org.onap.appc.logging.file=logback.xml - -org.onap.appc.db.url.%s", schema), ""); -org.onap.appc.db.user.%s", schema), ""); -org.onap.appc.db.pass.%s", schema), ""); - - -#Property below provided by appc.properties -appc.LCM.provider.url=https://localhost:8443/restconf/operations/appc-provider-lcm -appc.LCM.poolMembers=:3904 -appc.LCM.service=dmaap -appc.LCM.topic.write=APPC-TEST2 -appc.LCM.client.name=APPC-TEST-CLIENT-REQ-HDLR-TEST -appc.LCM.provider.user=test -appc.LCM.provider.pass=test - - - -mysqlIp=127.0.0.1 -org.onap.appc.db.url.sdnctl=jdbc:mysql://${mysqlIp}:3306/test -org.onap.appc.db.user.sdnctl=test -org.onap.appc.db.pass.sdnctl=123456 - -org.onap.appc.workingstatemanager.maxAttempts=2 -- cgit 1.2.3-korg