summaryrefslogtreecommitdiffstats
path: root/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonRequestHandler.java
blob: 9791aa23f7ac33a96616d77fc5c9dbaab5f63568 (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
276
277
278
279
280
281
282
/*-
 * ============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 static java.lang.Character.toLowerCase;
import static java.lang.Character.toUpperCase;

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.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Properties;
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;

public class JsonRequestHandler implements RequestHandler {


    private final EELFLogger logger = EELFManager.getInstance().getLogger(JsonRequestHandler.class);
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static final String INPUT_PARAM = "input";

    private String inputClassName = null;
    private String actionName = null;
    private String methodName = null;
    private String packageName = null;
    private LifeCycleManagerStateful service = null;
    private Properties properties;
    private HashMap<String, String> exceptRpcMap = null;

    private AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory = null;

    public JsonRequestHandler() {/*default constructor*/}

    public JsonRequestHandler(Properties prop) throws AppcClientException {
        properties = prop;
        packageName = properties.getProperty("ctx.model.package") + ".";
        try {
            service = createService();
        } catch (AppcClientException e) {
            logger.error("An error occurred while instantiating JsonRequestHandler", e);
        }
        exceptRpcMap = prepareExceptionsMap();
    }

    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 {
                    logger.info("ignoring line: " + line);
                }
            }
        } catch (FileNotFoundException e) {
            logger.error("Map file not found", e);
            return exceptRpcMap;
        } catch (IOException e) {
            logger.error("An error occurred while preparing exceptions map", e);
        }

        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());
            switch (isSyncMode(inputNode)) {
                case SYNCH:
                    processSync(input, response);
                    break;
                case ASYNCH:
                    processAsync(input, response);
                    break;
                default:
                    throw new InvalidRequestException("Unrecognized request mode");
            }
        } catch (Exception e) {
            logger.error("An error occurred when proceeding file", e);
        }

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

    private void processAsync(Object input, JsonResponseHandler response)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        logger.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);
    }

    private void processSync(Object input, JsonResponseHandler response)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        logger.debug("Received input request will be processed in synchronously mode");
        Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass());
        response.onResponse(rpc.invoke(service, input));
    }

    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_PARAM).findValue("common-header").findValue("sub-request-id").asText());
            if ((mode % 2) == 0) {
                return modeT.SYNCH;
            }
        } catch (Exception e) {
            logger.error("Failed to parse sub-request-id", e);
            //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);
    }

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

    public Object prepareObject(JsonNode input) {
        try {
            Class cls = Class.forName(inputClassName);
            tryAlignPayload(input);
            return OBJECT_MAPPER.treeToValue(input.get(INPUT_PARAM), cls);
        } catch (Exception ex) {
            logger.error("Failed to prepare object", ex);
        }
        return null;
    }

    private void tryAlignPayload(JsonNode input) {
        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) {
            logger.debug("In " + actionName + " no payload defined", e);
        }
    }

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

    private void alignPayload(JsonNode input) throws NoSuchFieldException {
        JsonNode inputNode = input.findValue(INPUT_PARAM);
        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 exRpc = checkExceptionalRpcList(action);
        if (exRpc != null && !exRpc.isEmpty()) {
            return exRpc; // we found exceptional rpc, so no need to format it
        }

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

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

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

        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.append(toUpperCase(inputRpcName.charAt(i)));
                makeItUpperCase = false;
            } else if (inputRpcName.charAt(i) == '-') {
                makeItUpperCase = true;
            } else {
                method.append(inputRpcName.charAt(i));
                makeItUpperCase = false;
            }
        }
        return method.toString();
    }

    private enum modeT {
        SYNCH,
        ASYNCH
    }
}