First part of onap rename
[appc.git] / appc-client / client-simulator / src / main / java / org / openecomp / appc / simulator / client / impl / JsonRequestHandler.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.simulator.client.impl;
26
27 import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider;
28 import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory;
29 import org.onap.appc.client.lcm.api.ApplicationContext;
30 import org.onap.appc.client.lcm.api.LifeCycleManagerStateful;
31 import org.onap.appc.client.lcm.api.ResponseHandler;
32
33 import org.onap.appc.client.lcm.exceptions.AppcClientException;
34 import org.onap.appc.simulator.client.RequestHandler;
35
36 import com.att.eelf.configuration.EELFLogger;
37 import com.att.eelf.configuration.EELFManager;
38 import com.fasterxml.jackson.databind.JsonNode;
39 import com.fasterxml.jackson.databind.ObjectMapper;
40 import com.fasterxml.jackson.databind.node.ObjectNode;
41
42 import java.io.BufferedReader;
43 import java.io.File;
44 import java.io.FileNotFoundException;
45 import java.io.FileReader;
46 import java.io.IOException;
47 import java.lang.reflect.Method;
48 import java.util.HashMap;
49 import java.util.Properties;
50
51 public class JsonRequestHandler implements RequestHandler {
52
53      private enum modeT {
54         SYNCH,
55         ASYNCH
56     }
57
58     public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
59     private String rpcName = null;
60     private String inputClassName = null;
61     private String actionName = null;
62     private String methodName = null;
63     String packageName = null;
64     private LifeCycleManagerStateful service = null;
65     private Properties properties;
66     HashMap<String, String> exceptRpcMap = null;
67     private final EELFLogger LOG = EELFManager.getInstance().getLogger(JsonRequestHandler.class);
68     private AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory = null;
69
70
71     public JsonRequestHandler(Properties prop) throws AppcClientException {
72         properties = prop;
73         packageName = properties.getProperty("ctx.model.package") + ".";
74         try {
75             service = createService();
76         } catch (AppcClientException e) {
77             e.printStackTrace();
78         }
79         exceptRpcMap = prepareExceptionsMap();
80     }
81
82     public  JsonRequestHandler(){
83
84     }
85
86     private HashMap<String,String> prepareExceptionsMap() {
87         exceptRpcMap = new HashMap<>();
88
89         try (BufferedReader reader = new BufferedReader(
90                  new FileReader(properties.getProperty(
91                       "client.rpc.exceptions.map.file")))) {
92             String line;
93             while ((line = reader.readLine()) != null) {
94                 String[] parts = line.split(":", 2);
95                 if (parts.length >= 2) {
96                     String key = parts[0];
97                     String value = parts[1];
98                     exceptRpcMap.put(key, value);
99                 } else {
100                     System.out.println("ignoring line: " + line);
101                 }
102             }
103         } catch (FileNotFoundException e) {
104             return exceptRpcMap;
105         } catch (IOException e) {
106             e.printStackTrace();
107         }
108
109         return exceptRpcMap;
110     }
111
112     @Override
113     public void proceedFile(File source, File log) throws IOException {
114         final JsonNode inputNode = OBJECT_MAPPER.readTree(source);
115
116         try {
117             // proceed with inputNode and get some xxxInput object, depends on action
118             prepareNames(inputNode);
119
120             Object input = prepareObject(inputNode);
121
122             JsonResponseHandler response = new JsonResponseHandler();
123             response.setFile(source.getPath().toString());
124             switch (isSyncMode(inputNode)) {
125                 case SYNCH: {
126                     LOG.debug("Received input request will be processed in synchronously mode");
127                     Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass());
128                     response.onResponse(rpc.invoke(service, input));
129                     break;
130                 }
131                 case ASYNCH: {
132                     LOG.debug("Received input request will be processed in asynchronously mode");
133                     Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass(), ResponseHandler.class);
134                     rpc.invoke(service, input, response);
135                     break;
136                 }
137                 default: {
138                     throw new RuntimeException("Unrecognized request mode");
139                 }
140             }
141         }
142         catch(Exception ex){
143             //ex.printStackTrace();
144         }
145
146         LOG.debug("Action <" + actionName + "> from input file <" + source.getPath().toString() + "> processed");
147     }
148
149     private modeT isSyncMode(JsonNode inputNode) {
150         // The following solution is for testing purposes only
151         // the sync/async decision logic may change upon request
152         try {
153             int mode = Integer.parseInt(inputNode.findValue("input").findValue("common-header").findValue("sub-request-id").asText());
154             if ((mode % 2) == 0) {
155                 return modeT.SYNCH;
156             }
157         }catch (Exception ex) {
158             //use ASYNC as default, if value is not integer.
159         }
160         return modeT.ASYNCH;
161     }
162
163     private LifeCycleManagerStateful createService() throws AppcClientException {
164         appcLifeCycleManagerServiceFactory = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class);
165         return appcLifeCycleManagerServiceFactory.createLifeCycleManagerStateful(new ApplicationContext(), properties);
166     }
167
168     public void shutdown(boolean isForceShutdown){
169         appcLifeCycleManagerServiceFactory.shutdownLifeCycleManager(isForceShutdown);
170     }
171
172     public Object prepareObject(JsonNode input) {
173         try {
174             Class cls = Class.forName(inputClassName);
175             try {
176                 // since payload is not mandatory field and not all actions contains payload
177                 // so we have to check that during input parsing
178                 alignPayload(input);
179             } catch (NoSuchFieldException e) {
180                 LOG.debug("In " + actionName + " no payload defined");
181             }
182
183             return OBJECT_MAPPER.treeToValue(input.get("input"), cls);
184         }
185         catch(Exception ex){
186             //ex.printStackTrace();
187         }
188         return null;
189     }
190
191     private void prepareNames(JsonNode input) throws NoSuchFieldException {
192         JsonNode inputNode = input.findValue("input");
193         actionName = inputNode.findValue("action").asText();
194         if (actionName.isEmpty()) {
195             throw new NoSuchFieldException("Input doesn't contains field <action>");
196         }
197
198         rpcName = prepareRpcFromAction(actionName);
199         inputClassName = packageName + actionName + "Input";
200         methodName = prepareMethodName(rpcName);
201     }
202
203     private void alignPayload(JsonNode input) throws NoSuchFieldException {
204         JsonNode inputNode = input.findValue("input");
205         JsonNode payload = inputNode.findValue("payload");
206         if (payload == null || payload.asText().isEmpty() || payload.toString().isEmpty())
207             throw new NoSuchFieldException("Input doesn't contains field <payload>");
208
209         String payloadData = payload.asText();
210         if (payloadData.isEmpty())
211             payloadData = payload.toString();
212         ((ObjectNode)inputNode).put("payload", payloadData);
213     }
214
215     private String prepareRpcFromAction(String action) {
216         String rpc = checkExceptionalRpcList(action);
217         if (rpc!= null && !rpc.isEmpty()) {
218             return rpc; // we found exceptional rpc, so no need to format it
219         }
220
221         rpc = "";
222         boolean makeItLowerCase = true;
223         for(int i = 0; i < action.length(); i++)
224         {
225             if(makeItLowerCase) // first character will make lower case
226             {
227                 rpc+=Character.toLowerCase(action.charAt(i));
228                 makeItLowerCase = false;
229             }
230             else  if((i+1 < action.length()) && Character.isUpperCase(action.charAt(i+1)))
231             {
232                 rpc+=action.charAt(i) + "-";
233                 makeItLowerCase = true;
234             }
235             else
236             {
237                 rpc+=action.charAt(i);
238                 makeItLowerCase = false;
239             }
240         }
241         return rpc;
242     }
243
244     private String checkExceptionalRpcList(String action) {
245         if (exceptRpcMap.isEmpty()) {
246             return null;
247         }
248         return exceptRpcMap.get(action);
249     }
250
251     private String prepareMethodName(String inputRpcName) {
252         boolean makeItUpperCase = false;
253         String method = "";
254
255         for(int i = 0; i < inputRpcName.length(); i++)  //to check the characters of string..
256         {
257             if(Character.isLowerCase(inputRpcName.charAt(i)) && makeItUpperCase) // skip first character if it lower case
258             {
259                 method+=Character.toUpperCase(inputRpcName.charAt(i));
260                 makeItUpperCase = false;
261             }
262             else  if(inputRpcName.charAt(i) == '-')
263             {
264                 makeItUpperCase = true;
265             }
266             else
267             {
268                 method+=inputRpcName.charAt(i);
269                 makeItUpperCase = false;
270             }
271         }
272         return method;
273     }
274
275 }