Include impacted changes for APPC-346,APPC-348
[appc.git] / appc-provider / appc-provider-bundle / src / main / java / org / onap / appc / provider / lcm / service / RequestExecutor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.provider.lcm.service;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.att.eelf.i18n.EELFResourceManager;
30 import com.google.common.base.Strings;
31 import org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Payload;
32 import org.onap.appc.Constants;
33 import org.onap.appc.configuration.Configuration;
34 import org.onap.appc.configuration.ConfigurationFactory;
35 import org.onap.appc.domainmodel.lcm.ActionLevel;
36 import org.onap.appc.domainmodel.lcm.ResponseContext;
37 import org.onap.appc.exceptions.APPCException;
38 import org.onap.appc.executor.objects.LCMCommandStatus;
39 import org.onap.appc.executor.objects.Params;
40 import org.onap.appc.i18n.Msg;
41 import org.onap.appc.logging.LoggingConstants;
42 import org.onap.appc.logging.LoggingUtils;
43 import org.onap.appc.provider.AppcProviderLcm;
44 import org.onap.appc.provider.lcm.mock.MockRequestExecutor;
45 import org.onap.appc.requesthandler.RequestHandler;
46 import org.onap.appc.requesthandler.objects.RequestHandlerInput;
47 import org.onap.appc.requesthandler.objects.RequestHandlerOutput;
48 import org.osgi.framework.BundleContext;
49 import org.osgi.framework.FrameworkUtil;
50 import org.osgi.framework.InvalidSyntaxException;
51 import org.osgi.framework.ServiceReference;
52
53 import java.util.Collection;
54
55 /**
56  * Provider LCM request executor
57  */
58 public class RequestExecutor {
59     final String CANNOT_PROCESS = "LCM request cannot be processed at the moment because APPC isn't running";
60
61     private final Configuration configuration = ConfigurationFactory.getConfiguration();
62     private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcProviderLcm.class);
63
64     /**
65          * Execute the request.
66          * @param requestHandlerInput of the RequestHandlerInput
67          * @return RequestHandlerOutput
68          */
69     public RequestHandlerOutput executeRequest(RequestHandlerInput requestHandlerInput) {
70             // TODO mock backend should be removed when backend implementation is done
71             RequestHandlerOutput requestHandlerOutput = new MockRequestExecutor().executeRequest(requestHandlerInput);
72             if (requestHandlerOutput != null) {
73                 // mock support, return mock results
74                 return requestHandlerOutput;
75             }
76         
77             RequestHandler handler = getRequestHandler(requestHandlerInput.getRequestContext().getActionLevel());
78             if (handler == null) {
79                 logger.debug("execute while requesthandler is null");
80                 requestHandlerOutput = createRequestHandlerOutput(requestHandlerInput,
81                     LCMCommandStatus.REJECTED, Msg.REQUEST_HANDLER_UNAVAILABLE, new APPCException(CANNOT_PROCESS));
82             } else {
83                 try {
84                         logger.debug("execute while requesthandler is not null");
85                     requestHandlerOutput = handler.handleRequest(requestHandlerInput);
86                 } catch (Exception e) {
87                     logger.info(String.format("UNEXPECTED FAILURE while executing %s action",
88                         requestHandlerInput.getRequestContext().getAction().name()));
89                     requestHandlerOutput = createRequestHandlerOutput(requestHandlerInput,
90                         LCMCommandStatus.UNEXPECTED_ERROR, Msg.EXCEPTION_CALLING_DG, e);
91                 }
92             }
93             return requestHandlerOutput;
94         }
95
96     /**
97      * Get Request handler by ActionLevel
98      * @param actionLevel the ActionLevel
99      * @return RequestHandler if found, otherwise return null or throw RuntimeException
100      */
101     RequestHandler getRequestHandler(ActionLevel actionLevel) {
102         final BundleContext context = FrameworkUtil.getBundle(RequestHandler.class).getBundleContext();
103         if (context == null) {
104             return null;
105         }
106
107         String filter = null;
108         try {
109             filter = "(level=" + actionLevel.name() + ")";
110             Collection<ServiceReference<RequestHandler>> serviceReferences =
111                 context.getServiceReferences(RequestHandler.class, filter);
112             if (serviceReferences.size() == 1) {
113                 ServiceReference<RequestHandler> serviceReference = serviceReferences.iterator().next();
114                 return context.getService(serviceReference);
115             }
116
117             logger.error(String.format("Cannot find service reference for %s", RequestHandler.class.getName()));
118             throw new RuntimeException();
119
120         } catch (InvalidSyntaxException e) {
121             logger.error(String.format("Cannot find service reference for %s: Invalid Syntax %s",
122                 RequestHandler.class.getName(), filter), e);
123             throw new RuntimeException(e);
124         }
125     }
126
127     /**
128      * Create request handler output
129      * @param request of RequestHandlerInput
130      * @param cmdStatus of LCMCommandStatus
131      * @param msg of Msg for audit log
132      * @param e of the Exception
133      * @return generated RequestHandlerOutput based on the input
134      */
135     RequestHandlerOutput createRequestHandlerOutput(RequestHandlerInput request,
136                                                     LCMCommandStatus cmdStatus,
137                                                     Msg msg,
138                                                     Exception e) {
139         String errorMsg = e.getMessage() != null ? e.getMessage() : e.toString();
140         Params params = new Params().addParam("errorMsg", errorMsg);
141
142         final org.onap.appc.domainmodel.lcm.Status status = new org.onap.appc.domainmodel.lcm.Status();
143         status.setMessage(cmdStatus.getFormattedMessage(params));
144         status.setCode(cmdStatus.getResponseCode());
145
146         final ResponseContext responseContext = new ResponseContext();
147         responseContext.setCommonHeader(request.getRequestContext().getCommonHeader());
148         responseContext.setStatus(status);
149
150         RequestHandlerOutput requestHandlerOutput = new RequestHandlerOutput();
151         requestHandlerOutput.setResponseContext(responseContext);
152
153         final String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
154         final String reason = EELFResourceManager.format(
155             msg, e, appName, e.getClass().getSimpleName(), "", e.getMessage());
156         LoggingUtils.logErrorMessage(
157             LoggingConstants.TargetNames.APPC_PROVIDER,
158             reason,
159             this.getClass().getName());
160
161         return requestHandlerOutput;
162     }
163
164     /**
165      * Get payload from passed in RequestHandlerOutput
166      * @param output of the RequestHandlerOutput
167      * @return If the passed in RequestHandlerOutput contains payload, return a Payload object of the payload.
168      *         Otherwise, return null.
169      */
170     public Payload getPayload(RequestHandlerOutput output) {
171         if (output.getResponseContext() == null
172             || Strings.isNullOrEmpty(output.getResponseContext().getPayload())) {
173             return null;
174         }
175
176         return new Payload(output.getResponseContext().getPayload());
177     }
178 }