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