aboutsummaryrefslogtreecommitdiffstats
path: root/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonRequestHandler.java
blob: 243136d0e3300de97d4afea6c456f2b78574c992 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*-
 * ============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.simulator.client.impl;

import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider;
import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory;
import org.onap.appc.client.lcm.api.ApplicationContext;
import org.onap.appc.client.lcm.api.LifeCycleManagerStateful;
import org.onap.appc.client.lcm.api.ResponseHandler;

import org.onap.appc.client.lcm.exceptions.AppcClientException;
import org.onap.appc.simulator.client.RequestHandler;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Properties;

public class JsonRequestHandler implements RequestHandler {

     private enum modeT {
        SYNCH,
        ASYNCH
    }

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private String rpcName = null;
    private String inputClassName = null;
    private String actionName = null;
    private String methodName = null;
    String packageName = null;
    private LifeCycleManagerStateful service = null;
    private Properties properties;
    HashMap<String, String> exceptRpcMap = null;
    private final EELFLogger LOG = EELFManager.getInstance().getLogger(JsonRequestHandler.class);
    private AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory = null;


    public JsonRequestHandler(Properties prop) throws AppcClientException {
        properties = prop;
        packageName = properties.getProperty("ctx.model.package") + ".";
        try {
            service = createService();
        } catch (AppcClientException e) {
            e.printStackTrace();
        }
        exceptRpcMap = prepareExceptionsMap();
    }

    public  JsonRequestHandler(){

    }

    private HashMap<String,String> prepareExceptionsMap() {
        exceptRpcMap = new HashMap<>();

        try (BufferedReader reader = new BufferedReader(
                 new FileReader(properties.getProperty(
                      "client.rpc.exceptions.map.file")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(":", 2);
                if (parts.length >= 2) {
                    String key = parts[0];
                    String value = parts[1];
                    exceptRpcMap.put(key, value);
                } else {
                    System.out.println("ignoring line: " + line);
                }
            }
        } catch (FileNotFoundException e) {
            return exceptRpcMap;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return exceptRpcMap;
    }

    @Override
    public void proceedFile(File source, File log) throws IOException {
        final JsonNode inputNode = OBJECT_MAPPER.readTree(source);

        try {
            // proceed with inputNode and get some xxxInput object, depends on action
            prepareNames(inputNode);

            Object input = prepareObject(inputNode);

            JsonResponseHandler response = new JsonResponseHandler();
            response.setFile(source.getPath().toString());
            switch (isSyncMode(inputNode)) {
                case SYNCH: {
                    LOG.debug("Received input request will be processed in synchronously mode");
                    Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass());
                    response.onResponse(rpc.invoke(service, input));
                    break;
                }
                case ASYNCH: {
                    LOG.debug("Received input request will be processed in asynchronously mode");
                    Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass(), ResponseHandler.class);
                    rpc.invoke(service, input, response);
                    break;
                }
                default: {
                    throw new RuntimeException("Unrecognized request mode");
                }
            }
        }
        catch(Exception ex){
            //ex.printStackTrace();
        }

        LOG.debug("Action <" + actionName + "> from input file <" + source.getPath().toString() + "> processed");
    }

    private modeT isSyncMode(JsonNode inputNode) {
        // The following solution is for testing purposes only
        // the sync/async decision logic may change upon request
        try {
            int mode = Integer.parseInt(inputNode.findValue("input").findValue("common-header").findValue("sub-request-id").asText());
            if ((mode % 2) == 0) {
                return modeT.SYNCH;
            }
        }catch (Exception ex) {
            //use ASYNC as default, if value is not integer.
        }
        return modeT.ASYNCH;
    }

    private LifeCycleManagerStateful createService() throws AppcClientException {
        appcLifeCycleManagerServiceFactory = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class);
        return appcLifeCycleManagerServiceFactory.createLifeCycleManagerStateful(new ApplicationContext(), properties);
    }

    public void shutdown(boolean isForceShutdown){
        appcLifeCycleManagerServiceFactory.shutdownLifeCycleManager(isForceShutdown);
    }

    public Object prepareObject(JsonNode input) {
        try {
            Class cls = Class.forName(inputClassName);
            try {
                // since payload is not mandatory field and not all actions contains payload
                // so we have to check that during input parsing
                alignPayload(input);
            } catch (NoSuchFieldException e) {
                LOG.debug("In " + actionName + " no payload defined");
            }

            return OBJECT_MAPPER.treeToValue(input.get("input"), cls);
        }
        catch(Exception ex){
            //ex.printStackTrace();
        }
        return null;
    }

    private void prepareNames(JsonNode input) throws NoSuchFieldException {
        JsonNode inputNode = input.findValue("input");
        actionName = inputNode.findValue("action").asText();
        if (actionName.isEmpty()) {
            throw new NoSuchFieldException("Input doesn't contains field <action>");
        }

        rpcName = prepareRpcFromAction(actionName);
        inputClassName = packageName + actionName + "Input";
        methodName = prepareMethodName(rpcName);
    }

    private void alignPayload(JsonNode input) throws NoSuchFieldException {
        JsonNode inputNode = input.findValue("input");
        JsonNode payload = inputNode.findValue("payload");
        if (payload == null || payload.asText().isEmpty() || payload.toString().isEmpty())
            throw new NoSuchFieldException("Input doesn't contains field <payload>");

        String payloadData = payload.asText();
        if (payloadData.isEmpty())
            payloadData = payload.toString();
        ((ObjectNode)inputNode).put("payload", payloadData);
    }

    private String prepareRpcFromAction(String action) {
        String rpc = checkExceptionalRpcList(action);
        if (rpc!= null && !rpc.isEmpty()) {
            return rpc; // we found exceptional rpc, so no need to format it
        }

        rpc = "";
        boolean makeItLowerCase = true;
        for(int i = 0; i < action.length(); i++)
        {
            if(makeItLowerCase) // first character will make lower case
            {
                rpc+=Character.toLowerCase(action.charAt(i));
                makeItLowerCase = false;
            }
            else  if((i+1 < action.length()) && Character.isUpperCase(action.charAt(i+1)))
            {
                rpc+=action.charAt(i) + "-";
                makeItLowerCase = true;
            }
            else
            {
                rpc+=action.charAt(i);
                makeItLowerCase = false;
            }
        }
        return rpc;
    }

    private String checkExceptionalRpcList(String action) {
        if (exceptRpcMap.isEmpty()) {
            return null;
        }
        return exceptRpcMap.get(action);
    }

    private String prepareMethodName(String inputRpcName) {
        boolean makeItUpperCase = false;
        String method = "";

        for(int i = 0; i < inputRpcName.length(); i++)  //to check the characters of string..
        {
            if(Character.isLowerCase(inputRpcName.charAt(i)) && makeItUpperCase) // skip first character if it lower case
            {
                method+=Character.toUpperCase(inputRpcName.charAt(i));
                makeItUpperCase = false;
            }
            else  if(inputRpcName.charAt(i) == '-')
            {
                makeItUpperCase = true;
            }
            else
            {
                method+=inputRpcName.charAt(i);
                makeItUpperCase = false;
            }
        }
        return method;
    }

}