added azure related 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 @Conditional(value= FilterCondition.class)\r
48 public class PostResultsToDMaaPDelegate implements JavaDelegate {\r
49 \r
50   private static Logger logger = LoggerFactory.getLogger(PostResultsToDMaaPDelegate.class);\r
51 \r
52   @Value("${otf.cadi.aaf-mech-id}")\r
53   private String AAF_APPID;\r
54 \r
55   @Value("${otf.cadi.aaf-mech-password}")\r
56   private String AAF_APPPASS;\r
57 \r
58   @Value("${otf.environment}")\r
59   private String env;\r
60 \r
61   @Autowired private WorkflowUtility utility;\r
62 \r
63   private final String template = "https://<hostname>:3905/events/<topic>";\r
64 \r
65   @Override\r
66   public void execute(DelegateExecution execution) throws Exception {\r
67     logger.info("[PostResultsToDMaaP] Starting to post test results to dmaap.");\r
68     final String logPrefix = Utility.getLoggerPrefix();\r
69 \r
70     // Get the current test execution object.\r
71     TestExecution testExecution = utility.getTestExecution(execution.getVariables(), logPrefix);\r
72 \r
73     List<Object> testDataActivity = null;\r
74     Object dataByActivity =\r
75         utility.getTestDataByActivity(\r
76             execution.getVariables(), execution.getCurrentActivityId(), logPrefix);\r
77     if (!(dataByActivity instanceof List)) {\r
78       logger.error(\r
79           execution.getActivityInstanceId()\r
80               + ": Failed to retrieve dmaap requests in test data as list");\r
81       throw new TestExecutionException(\r
82           execution.getActivityInstanceId()\r
83               + ": Missing data to post to dmaap. Failed to retrieve dmaap requests in test data as list");\r
84     }\r
85 \r
86     // convert data to map and grab dmaaprequest array\r
87     testDataActivity = (List) dataByActivity;\r
88     List<DMaaPRequest> dmaapRequests = null;\r
89     try {\r
90       dmaapRequests =\r
91           Convert.listToObjectList(testDataActivity, new TypeReference<List<DMaaPRequest>>() {});\r
92     } catch (Exception e) {\r
93       logger.error(\r
94           execution.getActivityInstanceId() + ": Failed to get dmaap requests from test data");\r
95       throw new TestExecutionException(\r
96           execution.getActivityInstanceId() + ": Missing data to post to dmaap. " + e.getMessage(),\r
97           e);\r
98     }\r
99     if (dmaapRequests == null || dmaapRequests.isEmpty()) {\r
100       logger.error(execution.getActivityInstanceId() + ": Failed to retrieve dmaap request list");\r
101       throw new TestExecutionException(\r
102           execution.getActivityInstanceId() + ": Missing dmaap request list");\r
103     }\r
104 \r
105     // Get the testDetails object\r
106     Map<String, Object> testDetails = utility.getTestDetails(execution.getVariables(), logPrefix);\r
107 \r
108     // Post results to Dmaap\r
109     Map<String, Object> results = postResultsToDmaap(testExecution, dmaapRequests, logPrefix);\r
110 \r
111     // Set test details to show results of each post to dmaap\r
112     testDetails.put(execution.getCurrentActivityId(), results);\r
113     execution.setVariable(ExecutionConstants.ExecutionVariable.TEST_DETAILS, testDetails);\r
114     logger.info("[PostResultsToDMaaP] Finished posting test results to dmaap.");\r
115   }\r
116 \r
117   private Map<String, Object> postResultsToDmaap(\r
118       TestExecution execution, List<DMaaPRequest> dmaapRequests, String logPrefix) {\r
119     String payload = execution.toString();\r
120     Map<String, Object> results = new HashMap<>();\r
121     Map<String, String> headers = new HashMap<>();\r
122     headers.put("Authorization", getAuthorizationHeader());\r
123     headers.put("Content-Type", MediaType.APPLICATION_JSON);\r
124 \r
125     for (DMaaPRequest request : dmaapRequests) {\r
126       String url = new String(template);\r
127       url = url.replace("<hostname>", request.getHostname());\r
128       url = url.replace("<topic>", request.getAsyncTopic());\r
129 \r
130       try {\r
131         results.put(url, getResponse(url, payload, headers, request.getRequiresProxy()));\r
132       } catch (Exception e) {\r
133         e.printStackTrace();\r
134         logger.info(logPrefix + "Error while posting to dmaap : " + e.getMessage());\r
135         results.put(url, e.getMessage());\r
136       }\r
137     }\r
138     return results;\r
139   }\r
140 \r
141   private Map<String, Object> getResponse(\r
142       String url, String payload, Map<String, String> headers, boolean proxy)\r
143       throws Exception {\r
144     HttpResponse response = RequestUtility.postSync(url, payload, headers, proxy);\r
145     String sRes = EntityUtils.toString(response.getEntity());\r
146     Map<String, Object> res;\r
147     try {\r
148       res = Convert.jsonToMap(sRes);\r
149     } catch (Exception e) {\r
150       res = new HashMap<>();\r
151       res.put("response", sRes);\r
152     }\r
153     return res;\r
154   }\r
155 \r
156   private String getAuthorizationHeader() {\r
157     return "Basic "\r
158         + new String(Base64.getEncoder().encode((AAF_APPID + ":" + AAF_APPPASS).getBytes()));\r
159   }\r
160 }\r