Initial commit for AAI-UI(sparky-backend)
[aai/sparky-be.git] / src / main / java / org / openecomp / sparky / 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
26 package org.openecomp.sparky.util;
27
28 import java.io.IOException;
29 import java.io.PrintWriter;
30
31 import javax.servlet.http.HttpServletResponse;
32
33 import org.openecomp.cl.api.Logger;
34 import org.openecomp.sparky.logging.AaiUiMsgs;
35 import org.openecomp.sparky.dal.elasticsearch.SearchAdapter;
36 import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
37 import org.openecomp.sparky.dal.rest.OperationResult;
38
39 /**
40  * The Class ServletUtils.
41  */
42 public class ServletUtils {
43
44   /**
45    * Execute get query.
46    *
47    * @param logger the logger
48    * @param search the search
49    * @param response the response
50    * @param requestUrl the request url
51    * @return the operation result
52    * @throws Exception the exception
53    */
54   public static OperationResult executeGetQuery(Logger logger, SearchAdapter search,
55       HttpServletResponse response, String requestUrl) throws Exception {
56
57     OperationResult opResult = search.doGet(requestUrl, "application/json");
58
59     if (opResult.getResultCode() > 300) {
60       setServletResponse(logger, true, opResult.getResultCode(), response, opResult.getResult());
61     } else {
62       response.setStatus(opResult.getResultCode());
63     }
64
65     return opResult;
66
67   }
68
69   /**
70    * Execute post query.
71    *
72    * @param logger the logger
73    * @param search the search
74    * @param response the response
75    * @param requestUrl the request url
76    * @param requestJsonPayload the request json payload
77    * @return the operation result
78    * @throws Exception the exception
79    */
80   public static OperationResult executePostQuery(Logger logger, SearchAdapter search,
81       HttpServletResponse response, String requestUrl, String requestJsonPayload) throws Exception {
82
83     OperationResult opResult = search.doPost(requestUrl, requestJsonPayload, "application/json");
84
85     if (opResult.getResultCode() > 300) {
86       setServletResponse(logger, true, opResult.getResultCode(), response, opResult.getResult());
87
88     } else {
89       response.setStatus(opResult.getResultCode());
90     }
91
92     return opResult;
93   }
94
95   /**
96    * Handle search servlet errors.
97    *
98    * @param logger the logger
99    * @param errorMsg the error msg
100    * @param exc the exc
101    * @param response the response
102    * @throws IOException Signals that an I/O exception has occurred.
103    */
104   public static void handleSearchServletErrors(Logger logger, String errorMsg, Exception exc,
105       HttpServletResponse response) throws IOException {
106     String errorLogMsg = (exc == null ? errorMsg : errorMsg + ". Error:" 
107         + exc.getLocalizedMessage());
108     logger.error(AaiUiMsgs.ERROR_GENERIC, errorLogMsg);
109     response.setContentType("application/json");
110     PrintWriter out = response.getWriter();
111     out.println(generateJsonErrorResponse(errorMsg));
112     out.close();
113   }
114
115   /**
116    * Generate json error response.
117    *
118    * @param message the message
119    * @return the string
120    */
121   public static String generateJsonErrorResponse(String message) {
122     return String.format("{ \"errorMessage\" : %s }", message);
123   }
124
125   /**
126    * Sets the servlet response.
127    *
128    * @param logger the logger
129    * @param isError the is error
130    * @param responseCode the response code
131    * @param response the response
132    * @param postPayload the post payload
133    * @throws IOException Signals that an I/O exception has occurred.
134    */
135   public static void setServletResponse(Logger logger, boolean isError, int responseCode,
136       HttpServletResponse response, String postPayload) throws IOException {
137
138     if (isError) {
139       logger.error(AaiUiMsgs.ERROR_GENERIC, postPayload);
140     }
141
142     response.setStatus(responseCode);
143
144     if (postPayload != null) {
145       response.setContentType("application/json");
146       PrintWriter out = response.getWriter();
147       out.println(postPayload);
148       out.close();
149     }
150   }
151
152   /**
153    * Gets the full url.
154    *
155    * @param elasticConfig the elastic config
156    * @param resourceUrl the resource url
157    * @return the full url
158    */
159   public static String getFullUrl(ElasticSearchConfig elasticConfig, String resourceUrl) {
160     final String host = elasticConfig.getIpAddress();
161     final String port = elasticConfig.getHttpPort();
162     return String.format("http://%s:%s%s", host, port, resourceUrl);
163   }
164 }