ES to SDS conversion
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / logging / util / ServletUtils.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sparky.logging.util;
22
23 import java.io.IOException;
24 import java.io.PrintWriter;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.servlet.http.HttpServletRequest;
31 import javax.servlet.http.HttpServletResponse;
32
33 import org.apache.camel.Exchange;
34 import org.onap.aai.cl.api.Logger;
35 import org.onap.aai.cl.mdc.MdcContext;
36 import org.onap.aai.restclient.client.OperationResult;
37 import org.onap.aai.sparky.logging.AaiUiMsgs;
38 import org.onap.aai.sparky.search.SearchServiceAdapter;
39 import org.onap.aai.sparky.util.NodeUtils;
40 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
41 import org.slf4j.MDC;
42
43 /**
44  * The Class ServletUtils.
45  */
46 public class ServletUtils {
47
48   /**
49    * Execute get query.
50    *
51    * @param logger the logger
52    * @param search the search
53    * @param response the response
54    * @param requestUrl the request url
55    * @return the operation result
56    * @throws Exception the exception
57    */
58   public static OperationResult executeGetQuery(Logger logger, SearchServiceAdapter search,
59       HttpServletResponse response, String requestUrl) throws Exception {
60
61     OperationResult opResult = search.doGet(requestUrl, "application/json");
62
63     if (opResult.getResultCode() > 300) {
64       setServletResponse(logger, true, opResult.getResultCode(), response, opResult.getResult());
65     } else {
66       response.setStatus(opResult.getResultCode());
67     }
68
69     return opResult;
70
71   }
72
73   /**
74    * Execute post query.
75    *
76    * @param logger the logger
77    * @param search the search
78    * @param response the response
79    * @param requestUrl the request url
80    * @param requestJsonPayload the request json payload
81    * @return the operation result
82    * @throws Exception the exception
83    */
84   public static OperationResult executePostQuery(Logger logger, SearchServiceAdapter search,
85       HttpServletResponse response, String requestUrl, String requestJsonPayload) throws Exception {
86
87     OperationResult opResult = search.doPost(requestUrl, requestJsonPayload);
88
89     if (opResult.getResultCode() > 300) {
90       setServletResponse(logger, true, opResult.getResultCode(), response, opResult.getResult());
91
92     } else {
93       response.setStatus(opResult.getResultCode());
94     }
95
96     return opResult;
97   }
98
99   /**
100    * Handle search servlet errors.
101    *
102    * @param logger the logger
103    * @param errorMsg the error msg
104    * @param exc the exc
105    * @param response the response
106    * @throws IOException Signals that an I/O exception has occurred.
107    */
108   public static void handleSearchServletErrors(Logger logger, String errorMsg, Exception exc,
109       HttpServletResponse response) throws IOException {
110     String errorLogMsg = (exc == null ? errorMsg : errorMsg + ". Error:" 
111         + exc.getLocalizedMessage());
112     logger.error(AaiUiMsgs.ERROR_GENERIC, errorLogMsg);
113     response.setContentType("application/json");
114     PrintWriter out = response.getWriter();
115     out.println(generateJsonErrorResponse(errorMsg));
116     out.close();
117   }
118
119   /**
120    * Generate json error response.
121    *
122    * @param message the message
123    * @return the string
124    */
125   public static String generateJsonErrorResponse(String message) {
126     return String.format("{ \"errorMessage\" : %s }", message);
127   }
128
129   /**
130    * Sets the servlet response.
131    *
132    * @param logger the logger
133    * @param isError the is error
134    * @param responseCode the response code
135    * @param response the response
136    * @param postPayload the post payload
137    * @throws IOException Signals that an I/O exception has occurred.
138    */
139   public static void setServletResponse(Logger logger, boolean isError, int responseCode,
140       HttpServletResponse response, String postPayload) throws IOException {
141
142     if (isError) {
143       logger.error(AaiUiMsgs.ERROR_GENERIC, postPayload);
144     }
145
146     response.setStatus(responseCode);
147
148     if (postPayload != null) {
149       response.setContentType("application/json");
150       PrintWriter out = response.getWriter();
151       out.println(postPayload);
152       out.close();
153     }
154   }
155
156   /**
157    * Gets the full url.
158    *
159    * @param elasticConfig the elastic config
160    * @param resourceUrl the resource url
161    * @return the full url
162    */
163   public static String getFullUrl(String eHost,String ePort, String resourceUrl) {
164     final String host = eHost;
165     final String port = ePort;
166     return String.format("http://%s:%s%s", host, port, resourceUrl);
167   }
168   
169   public static void setUpMdcContext(final Exchange exchange, final HttpServletRequest request) {
170
171     String txnId;
172
173     Object xTransactionId = exchange.getIn().getHeader("X-TransactionId");
174     if (xTransactionId == null) {
175       txnId = NodeUtils.getRandomTxnId();
176     } else {
177       txnId = (String) xTransactionId;
178     }
179
180     String fromAppId;
181
182     Object partnerName = exchange.getIn().getHeader("X-FromAppId");
183     if (partnerName == null) {
184       fromAppId = SparkyConstants.APP_NAME;
185     } else {
186       fromAppId = (String) partnerName;
187     }
188
189     MdcContext.initialize(txnId, "AAI-UI", "", fromAppId,
190         request.getRequestURI() + ":" + request.getLocalPort());
191   }
192   
193   public static Map<String, List<String>> getTxnHeaders() {
194     Map<String, List<String>> headers = new HashMap<String, List<String>>();
195     headers.put("X-TransactionId", Arrays.asList(MDC.get(MdcContext.MDC_REQUEST_ID)));
196     headers.put("X-FromAppId", Arrays.asList(MDC.get(MdcContext.MDC_PARTNER_NAME)));
197     return headers;
198   }
199   
200 }