Replaced all tabs with spaces in java and pom.xml
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / onap / so / client / appc / ApplicationControllerClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.client.appc;
22
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.time.Instant;
26 import java.util.Properties;
27 import java.util.UUID;
28 import java.util.concurrent.ConcurrentHashMap;
29 import org.onap.so.bpmn.core.UrnPropertiesReader;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider;
33 import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory;
34 import org.onap.appc.client.lcm.api.ApplicationContext;
35 import org.onap.appc.client.lcm.api.LifeCycleManagerStateful;
36 import org.onap.appc.client.lcm.exceptions.AppcClientException;
37 import org.onap.appc.client.lcm.model.Action;
38 import org.onap.appc.client.lcm.model.ActionIdentifiers;
39 import org.onap.appc.client.lcm.model.CommonHeader;
40 import org.onap.appc.client.lcm.model.Flags;
41 import org.onap.appc.client.lcm.model.Flags.Force;
42 import org.onap.appc.client.lcm.model.Flags.Mode;
43 import org.onap.appc.client.lcm.model.Payload;
44 import org.onap.appc.client.lcm.model.Status;
45 import org.onap.appc.client.lcm.model.ZULU;
46
47 public class ApplicationControllerClient {
48
49     public static final String DEFAULT_CONTROLLER_TYPE = "APPC";
50
51     private static final String CLIENT_NAME = "MSO";
52
53     private static final String API_VER = "2.00";
54     private static final String ORIGINATOR_ID = "MSO";
55     private static final int FLAGS_TTL = 65000;
56     private static Logger logger = LoggerFactory.getLogger(ApplicationControllerClient.class);
57
58     private ApplicationControllerSupport appCSupport;
59
60     // APPC gave us an API where the controllerType is configured in the
61     // client object, which is not what we asked for. We asked for an API
62     // in which the client would have additional methods that could take
63     // the controllerType as a parameter, so that we would not need to
64     // maintain multiple client objects. This map should be removed when
65     // the (hopefully short-term) controllerType becomes obsolete.
66
67     private final String controllerType;
68
69     private static ConcurrentHashMap<String, LifeCycleManagerStateful> appCClients = new ConcurrentHashMap<>();
70
71     /**
72      * Creates an ApplicationControllerClient for communication with APP-C.
73      */
74     public ApplicationControllerClient() {
75         this(DEFAULT_CONTROLLER_TYPE);
76     }
77
78     /**
79      * Creates an ApplicationControllerClient for the specified controller type.
80      * 
81      * @param controllerType the controller type: "appc" or "sdnc".
82      */
83     public ApplicationControllerClient(String controllerType) {
84         if (controllerType == null) {
85             controllerType = DEFAULT_CONTROLLER_TYPE;
86         }
87         this.controllerType = controllerType.toUpperCase();
88         appCSupport = new ApplicationControllerSupport();
89     }
90
91     /**
92      * Gets the controller type.
93      * 
94      * @return the controllertype
95      */
96     public String getControllerType() {
97         return controllerType;
98     }
99
100     /**
101      * Returns the AppC client object associated with this ApplicationControllerClient. AppC client objects are shared
102      * objects. One is created if it does not exist.
103      * 
104      * @return the client object, or null if creation failed
105      */
106     public LifeCycleManagerStateful getAppCClient() {
107         return appCClients.computeIfAbsent(controllerType, k -> createAppCClient(k));
108     }
109
110     protected LifeCycleManagerStateful createAppCClient(String controllerType) {
111         try {
112             if (controllerType == null) {
113                 controllerType = DEFAULT_CONTROLLER_TYPE;
114             }
115             controllerType = controllerType.toUpperCase();
116             return AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class)
117                     .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties(controllerType));
118         } catch (AppcClientException e) {
119             logger.error("Error in getting LifeCycleManagerStateful: {}", e.getMessage(), e);
120             // This null value will cause NullPointerException when used later.
121             // Error handling could certainly be improved here.
122             return null;
123         }
124     }
125
126     public Status runCommand(Action action, org.onap.appc.client.lcm.model.ActionIdentifiers actionIdentifiers,
127             org.onap.appc.client.lcm.model.Payload payload, String requestID)
128             throws ApplicationControllerOrchestratorException {
129         Object requestObject;
130         requestObject = createRequest(action, actionIdentifiers, payload, requestID);
131         appCSupport.logLCMMessage(requestObject);
132         LifeCycleManagerStateful client = getAppCClient();
133         Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false);
134         try {
135             Object response = lcmMethod.invoke(client, requestObject);
136             return appCSupport.getStatusFromGenericResponse(response);
137         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
138             throw new RuntimeException(String.format("%s : %s", "Unable to invoke action", action.toString()), e);
139         }
140     }
141
142     protected Properties getLCMProperties() {
143         return getLCMProperties("appc");
144     }
145
146     protected Properties getLCMProperties(String controllerType) {
147         Properties properties = new Properties();
148
149         properties.put("topic.read", UrnPropertiesReader.getVariable("appc.client.topic.read.name"));
150         properties.put("topic.write", UrnPropertiesReader.getVariable("appc.client.topic.write"));
151         properties.put("SDNC-topic.read", UrnPropertiesReader.getVariable("appc.client.topic.sdnc.read"));
152         properties.put("SDNC-topic.write", UrnPropertiesReader.getVariable("appc.client.topic.sdnc.write"));
153         properties.put("topic.read.timeout", UrnPropertiesReader.getVariable("appc.client.topic.read.timeout"));
154         properties.put("client.response.timeout", UrnPropertiesReader.getVariable("appc.client.response.timeout"));
155         properties.put("poolMembers", UrnPropertiesReader.getVariable("appc.client.poolMembers"));
156         properties.put("controllerType", controllerType);
157         properties.put("client.key", UrnPropertiesReader.getVariable("appc.client.key"));
158         properties.put("client.secret", UrnPropertiesReader.getVariable("appc.client.secret"));
159         properties.put("client.name", CLIENT_NAME);
160         properties.put("service", UrnPropertiesReader.getVariable("appc.client.service"));
161         return properties;
162     }
163
164     public Object createRequest(Action action, ActionIdentifiers identifier, Payload payload, String requestId) {
165         Object requestObject = appCSupport.getInput(action.name());
166         try {
167             CommonHeader commonHeader = buildCommonHeader(requestId);
168             requestObject.getClass().getDeclaredMethod("setCommonHeader", CommonHeader.class).invoke(requestObject,
169                     commonHeader);
170             requestObject.getClass().getDeclaredMethod("setAction", Action.class).invoke(requestObject, action);
171             requestObject.getClass().getDeclaredMethod("setActionIdentifiers", ActionIdentifiers.class)
172                     .invoke(requestObject, identifier);
173             if (payload != null) {
174                 requestObject.getClass().getDeclaredMethod("setPayload", Payload.class).invoke(requestObject, payload);
175             }
176         } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
177             logger.error("Error building Appc request", e);
178         }
179         return requestObject;
180     }
181
182     private CommonHeader buildCommonHeader(String requestId) {
183         CommonHeader commonHeader = new CommonHeader();
184         commonHeader.setApiVer(API_VER);
185         commonHeader.setOriginatorId(ORIGINATOR_ID);
186         commonHeader.setRequestId(requestId == null ? UUID.randomUUID().toString() : requestId);
187         commonHeader.setSubRequestId(UUID.randomUUID().toString());
188         Flags flags = new Flags();
189         String flagsMode = "NORMAL";
190         Mode mode = Mode.valueOf(flagsMode);
191         flags.setMode(mode);
192         String flagsForce = "FALSE";
193         Force force = Force.valueOf(flagsForce);
194         flags.setForce(force);
195         flags.setTtl(FLAGS_TTL);
196         commonHeader.setFlags(flags);
197         Instant timestamp = Instant.now();
198         ZULU zulu = new ZULU(timestamp.toString());
199         commonHeader.setTimestamp(zulu);
200         return commonHeader;
201     }
202
203     public Flags createRequestFlags() {
204         Flags flags = new Flags();
205         flags.setTtl(6000);
206         return flags;
207     }
208 }