added svcapi ui and camunda code
[it/otf.git] / otf-camunda / src / main / java / org / oran / otf / camunda / delegate / otf / common / PostResultsToDMaaPDelegate.java
1 /*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
2 #                                                                              #\r
3 #   Licensed under the Apache License, Version 2.0 (the "License");            #\r
4 #   you may not use this file except in compliance with the License.           #\r
5 #   You may obtain a copy of the License at                                    #\r
6 #                                                                              #\r
7 #       http://www.apache.org/licenses/LICENSE-2.0                             #\r
8 #                                                                              #\r
9 #   Unless required by applicable law or agreed to in writing, software        #\r
10 #   distributed under the License is distributed on an "AS IS" BASIS,          #\r
11 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
12 #   See the License for the specific language governing permissions and        #\r
13 #   limitations under the License.                                             #\r
14 ##############################################################################*/\r
15 \r
16 \r
17 package org.oran.otf.camunda.delegate.otf.common;\r
18 \r
19 import org.oran.otf.cadi.configuration.FilterCondition;\r
20 import org.oran.otf.camunda.exception.TestExecutionException;\r
21 import org.oran.otf.camunda.model.ExecutionConstants;\r
22 import org.oran.otf.camunda.workflow.utility.WorkflowUtility;\r
23 import org.oran.otf.common.model.TestExecution;\r
24 import org.oran.otf.common.model.local.DMaaPRequest;\r
25 import org.oran.otf.common.utility.Utility;\r
26 import org.oran.otf.common.utility.gson.Convert;\r
27 import org.oran.otf.common.utility.http.RequestUtility;\r
28 import com.fasterxml.jackson.core.type.TypeReference;\r
29 \r
30 import java.util.Base64;\r
31 import java.util.HashMap;\r
32 import java.util.List;\r
33 import java.util.Map;\r
34 import javax.ws.rs.core.MediaType;\r
35 import org.apache.http.HttpResponse;\r
36 import org.apache.http.util.EntityUtils;\r
37 import org.camunda.bpm.engine.delegate.DelegateExecution;\r
38 import org.camunda.bpm.engine.delegate.JavaDelegate;\r
39 import org.slf4j.Logger;\r
40 import org.slf4j.LoggerFactory;\r
41 import org.springframework.beans.factory.annotation.Autowired;\r
42 import org.springframework.beans.factory.annotation.Value;\r
43 import org.springframework.context.annotation.Conditional;\r
44 import org.springframework.stereotype.Component;\r
45 \r
46 @Component\r
47 public class PostResultsToDMaaPDelegate implements JavaDelegate {\r
48 \r
49   private static Logger logger = LoggerFactory.getLogger(PostResultsToDMaaPDelegate.class);\r
50 \r
51   @Value("${otf.cadi.aaf-mech-id}")\r
52   private String AAF_APPID;\r
53 \r
54   @Value("${otf.cadi.aaf-mech-password}")\r
55   private String AAF_APPPASS;\r
56 \r
57   @Value("${otf.environment}")\r
58   private String env;\r
59 \r
60   @Autowired private WorkflowUtility utility;\r
61 \r
62   private final String template = "https://<hostname>:3905/events/<topic>";\r
63 \r
64   @Override\r
65   public void execute(DelegateExecution execution) throws Exception {\r
66     logger.info("[PostResultsToDMaaP] Starting to post test results to dmaap.");\r
67     final String logPrefix = Utility.getLoggerPrefix();\r
68 \r
69     // Get the current test execution object.\r
70     TestExecution testExecution = utility.getTestExecution(execution.getVariables(), logPrefix);\r
71 \r
72     List<Object> testDataActivity = null;\r
73     Object dataByActivity =\r
74         utility.getTestDataByActivity(\r
75             execution.getVariables(), execution.getCurrentActivityId(), logPrefix);\r
76     if (!(dataByActivity instanceof List)) {\r
77       logger.error(\r
78           execution.getActivityInstanceId()\r
79               + ": Failed to retrieve dmaap requests in test data as list");\r
80       throw new TestExecutionException(\r
81           execution.getActivityInstanceId()\r
82               + ": Missing data to post to dmaap. Failed to retrieve dmaap requests in test data as list");\r
83     }\r
84 \r
85     // convert data to map and grab dmaaprequest array\r
86     testDataActivity = (List) dataByActivity;\r
87     List<DMaaPRequest> dmaapRequests = null;\r
88     try {\r
89       dmaapRequests =\r
90           Convert.listToObjectList(testDataActivity, new TypeReference<List<DMaaPRequest>>() {});\r
91     } catch (Exception e) {\r
92       logger.error(\r
93           execution.getActivityInstanceId() + ": Failed to get dmaap requests from test data");\r
94       throw new TestExecutionException(\r
95           execution.getActivityInstanceId() + ": Missing data to post to dmaap. " + e.getMessage(),\r
96           e);\r
97     }\r
98     if (dmaapRequests == null || dmaapRequests.isEmpty()) {\r
99       logger.error(execution.getActivityInstanceId() + ": Failed to retrieve dmaap request list");\r
100       throw new TestExecutionException(\r
101           execution.getActivityInstanceId() + ": Missing dmaap request list");\r
102     }\r
103 \r
104     // Get the testDetails object\r
105     Map<String, Object> testDetails = utility.getTestDetails(execution.getVariables(), logPrefix);\r
106 \r
107     // Post results to Dmaap\r
108     Map<String, Object> results = postResultsToDmaap(testExecution, dmaapRequests, logPrefix);\r
109 \r
110     // Set test details to show results of each post to dmaap\r
111     testDetails.put(execution.getCurrentActivityId(), results);\r
112     execution.setVariable(ExecutionConstants.ExecutionVariable.TEST_DETAILS, testDetails);\r
113     logger.info("[PostResultsToDMaaP] Finished posting test results to dmaap.");\r
114   }\r
115 \r
116   private Map<String, Object> postResultsToDmaap(\r
117       TestExecution execution, List<DMaaPRequest> dmaapRequests, String logPrefix) {\r
118     String payload = execution.toString();\r
119     Map<String, Object> results = new HashMap<>();\r
120     Map<String, String> headers = new HashMap<>();\r
121     headers.put("Authorization", getAuthorizationHeader());\r
122     headers.put("Content-Type", MediaType.APPLICATION_JSON);\r
123 \r
124     for (DMaaPRequest request : dmaapRequests) {\r
125       String url = new String(template);\r
126       url = url.replace("<hostname>", request.getHostname());\r
127       url = url.replace("<topic>", request.getAsyncTopic());\r
128 \r
129       try {\r
130         results.put(url, getResponse(url, payload, headers, request.getRequiresProxy()));\r
131       } catch (Exception e) {\r
132         e.printStackTrace();\r
133         logger.info(logPrefix + "Error while posting to dmaap : " + e.getMessage());\r
134         results.put(url, e.getMessage());\r
135       }\r
136     }\r
137     return results;\r
138   }\r
139 \r
140   private Map<String, Object> getResponse(\r
141       String url, String payload, Map<String, String> headers, boolean proxy)\r
142       throws Exception {\r
143     HttpResponse response = RequestUtility.postSync(url, payload, headers, proxy);\r
144     String sRes = EntityUtils.toString(response.getEntity());\r
145     Map<String, Object> res;\r
146     try {\r
147       res = Convert.jsonToMap(sRes);\r
148     } catch (Exception e) {\r
149       res = new HashMap<>();\r
150       res.put("response", sRes);\r
151     }\r
152     return res;\r
153   }\r
154 \r
155   private String getAuthorizationHeader() {\r
156     return "Basic "\r
157         + new String(Base64.getEncoder().encode((AAF_APPID + ":" + AAF_APPPASS).getBytes()));\r
158   }\r
159 }\r