Null check for ClientResponse in PolicyUril.java
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / utils / EcompPortalUtils.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the “License”);
10  * you may not use this software 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  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.openecomp.portalapp.portal.utils;
39
40 import java.net.InetAddress;
41 import java.net.UnknownHostException;
42 import java.text.SimpleDateFormat;
43 import java.util.ArrayList;
44 import java.util.Date;
45 import java.util.List;
46
47 import javax.servlet.http.HttpServletResponse;
48 import javax.xml.bind.DatatypeConverter;
49
50 import org.hibernate.Session;
51 import org.hibernate.Transaction;
52 import org.openecomp.portalapp.portal.domain.EPUser;
53 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
54 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
55 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
56 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
57 import org.openecomp.portalsdk.core.util.SystemProperties;
58 import org.slf4j.MDC;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.MediaType;
61
62 import com.fasterxml.jackson.core.JsonProcessingException;
63 import com.fasterxml.jackson.databind.ObjectMapper;
64
65 public class EcompPortalUtils {
66
67         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
68
69         // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
70         // It should be defined in SystemProperties.
71         private static final String GLOBAL_LOGIN_URL = "global-login-url";
72
73         /**
74          * @param orgUserId
75          *            User ID to validate
76          * @return true if orgUserId is not empty and contains only alphanumeric, false
77          *         otherwise
78          */
79         public static boolean legitimateUserId(String orgUserId) {
80                 return orgUserId.matches("^[a-zA-Z0-9]+$");
81         }
82
83         /**
84          * Splits the string into a list of tokens using the specified regular
85          * expression
86          * 
87          * @param source
88          *            String to split
89          * @param regex
90          *            tokens
91          * @return List of tokens split from the source
92          */
93         public static List<String> parsingByRegularExpression(String source, String regex) {
94                 List<String> tokens = new ArrayList<String>();
95                 if (source != null && source.length() > 0) {
96                         String[] parsed = source.split(regex);
97                         for (String token : parsed) {
98                                 if (token.length() > 0) {
99                                         tokens.add(token);
100                                 }
101                         }
102                 }
103                 return tokens;
104         }
105
106         /**
107          * Builds a JSON object with error code and message information.
108          * 
109          * @param errorCode
110          *            error code
111          * @param errorMessage
112          *            message
113          * @return JSON object as a String
114          */
115         public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
116                 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
117         }
118
119         /**
120          * Builds a JSON object with the specified message
121          * 
122          * @param message
123          *            Message to embed
124          * @return JSON object as a String
125          */
126         public static String jsonMessageResponse(String message) {
127                 return String.format("{\"message\":\"%s\"}", message);
128         }
129
130         /**
131          * Serializes the specified object as JSON and writes the result to the debug
132          * log. If serialization fails, logs a message to the error logger.
133          * 
134          * @param logger
135          *            Logger for the class where the object was built; the logger
136          *            carries the class name.
137          * @param source
138          *            First portion of the log message
139          * @param msg
140          *            Second portion of the log message
141          * @param obj
142          *            Object to serialize as JSON
143          */
144         public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
145                 try {
146                         String objectAsJson = new ObjectMapper().writeValueAsString(obj);
147                         logger.debug(EELFLoggerDelegate.debugLogger,
148                                         String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
149                 } catch (JsonProcessingException e) {
150                         logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
151                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
152                 } catch (Exception e) {
153                         logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
154                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
155                 }
156         }
157
158         /**
159          * Serializes the specified object as JSON and writes the result to the debug
160          * log. If serialization fails, logs a message to the error logger.
161          * 
162          * @param source
163          *            First portion of the log message
164          * @param msg
165          *            Second portion of the log message
166          * @param obj
167          *            Object to serialize as JSON
168          */
169         public static void logAndSerializeObject(String source, String msg, Object obj) {
170                 logAndSerializeObject(logger, source, msg, obj);
171         }
172
173         public static void rollbackTransaction(Transaction transaction, String errorMessage) {
174                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
175                 try {
176                         if (transaction != null) {
177                                 transaction.rollback();
178                         }
179                 } catch (Exception e) {
180                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
181                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
182                                         e);
183                 }
184         }
185
186         public static void closeLocalSession(Session localSession, String errorMessage) {
187                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
188                 try {
189                         if (localSession != null) {
190                                 localSession.close();
191                         }
192                 } catch (Exception e) {
193                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
194                         logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
195                 }
196         }
197
198         /**
199          * Set response status to Unauthorized if user == null and to Forbidden in all
200          * (!) other cases. Logging is not performed if invocator == null
201          * 
202          * @param user
203          *            User object
204          * @param response
205          *            HttpServletResponse
206          * @param invocator
207          *            may be null
208          */
209         public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
210                 if (user == null) {
211                         String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
212                         response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
213                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
214                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
215                 } else {
216                         response.setStatus(HttpServletResponse.SC_FORBIDDEN);
217                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
218                 }
219                 if (invocator != null) {
220                         logger.warn(EELFLoggerDelegate.errorLogger,
221                                         invocator + ", permissions problem, response status = " + response.getStatus());
222                 }
223         }
224
225         public static int getExternalAppResponseCode() {
226                 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
227                 int responseCodeInt = 0;
228                 try {
229                         if (responseCode != null && responseCode != "") {
230                                 responseCodeInt = Integer.valueOf(responseCode);
231                         }
232                 } catch (Exception e) {
233                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
234                 }
235                 return responseCodeInt;
236         }
237
238         // This method might be just for testing purposes.
239         public static void setExternalAppResponseCode(int responseCode) {
240                 try {
241                         String responseCodeString = String.valueOf(responseCode);
242                         MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, responseCodeString);
243                 } catch (Exception e) {
244                         logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e);
245                 }
246         }
247
248         public static String getHTTPStatusString(int httpStatusCode) {
249                 String httpStatusString = "unknown_error";
250                 try {
251                         httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
252                         if (httpStatusString != null) {
253                                 httpStatusString = httpStatusString.toLowerCase();
254                         }
255                 } catch (Exception e) {
256                         logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
257                 }
258                 return httpStatusString;
259         }
260
261         public static String getFEErrorString(Boolean internal, int responseCode) {
262                 // Return a String like the following:
263                 // "Internal Ecomp Error: 500 internal_server_error" or
264                 // "External App Error: 404 not_found"
265                 // TODO: create our own Ecomp error codes, starting with 1000 and up.
266                 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
267                 String httpStatusString = "unknown_error";
268                 try {
269                         if (responseCode < 1000) {
270                                 httpStatusString = getHTTPStatusString(responseCode);
271                         }
272                 } catch (Exception e) {
273                         logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
274                 }
275                 String responseString = internalExternalString + responseCode + " " + httpStatusString;
276                 return responseString;
277         }
278
279         public static boolean isProductionBuild() {
280                 boolean productionBuild = true;
281                 String epVersion = EcompVersion.buildNumber;
282                 if (epVersion != null) {
283                         int buildNum = epVersion.lastIndexOf('.');
284                         if (buildNum > 0) {
285                                 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
286                                 if (buildNumber < 3000) // Production versions are 3000+, (ie
287                                                                                 // 1.0.3003)
288                                 {
289                                         productionBuild = false;
290                                 }
291                         }
292                 }
293                 return productionBuild;
294         }
295
296         public static String getMyIpAdddress() {
297                 InetAddress ip;
298                 String localIp;
299                 try {
300                         ip = InetAddress.getLocalHost();
301                         localIp = ip.getHostAddress();
302                 } catch (UnknownHostException e) {
303                         localIp = "unknown";
304                         logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
305                 }
306                 return localIp;
307         }
308
309         public static String getMyHostName() {
310                 InetAddress ip;
311                 String hostName;
312                 try {
313                         ip = InetAddress.getLocalHost();
314                         hostName = ip.getHostName();
315                 } catch (UnknownHostException e) {
316                         hostName = "unknown";
317                         logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
318                 }
319                 return hostName;
320         }
321
322         /**
323          * Returns a default property if the expected one is not available
324          * 
325          * @param property
326          *            Key
327          * @param defaultValue
328          *            default Value
329          * @return Default value if property is not defined or yields the empty string;
330          *         else the property value.
331          */
332         public static String getPropertyOrDefault(String property, String defaultValue) {
333                 if (!SystemProperties.containsProperty(property))
334                         return defaultValue;
335                 String value = SystemProperties.getProperty(property);
336                 if (value == null || "".equals(value))
337                         return defaultValue;
338                 return value;
339         }
340
341         /**
342          * Calculates the time duration of a function call for logging purpose. It
343          * stores the result by using "MDC.put(SystemProperties.MDC_TIMER,
344          * timeDifference);" It is important to call
345          * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up
346          * the record in MDC
347          *
348          * @param beginDateTime
349          *            the given begin time for the call
350          * @param endDateTime
351          *            the given end time for the call
352          * 
353          */
354         public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
355                 if (beginDateTime != null && endDateTime != null) {
356                         try {
357                                 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
358
359                                 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
360                                 Date endDate = ecompLogDateFormat.parse(endDateTime);
361                                 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
362                                 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
363                         } catch (Exception e) {
364                                 logger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifferenceForLog failed", e);
365                         }
366                 }
367         }
368
369         /**
370          * Answers the protocol to use.
371          * 
372          * @return Protocol name from property file; defaults to https.
373          */
374         public static String widgetMsProtocol() {
375                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
376         }
377
378         /**
379          * Answers the host to use.
380          * 
381          * @return Host name from property file; defaults to localhost.
382          */
383         public static String localOrDockerHost() {
384                 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
385         }
386
387         /**
388          * It returns headers where username and password of external central auth is
389          * encoded to base64
390          * 
391          * @return header which contains external central auth username and password
392          *         base64 encoded
393          * @throws Exception
394          *             if unable to decrypt the password
395          */
396         public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception {
397                 String userName = "";
398                 String decryptedPass = "";
399                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME)
400                                 && EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) {
401                         decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD);
402                         userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME);
403                 }
404                 String decPass = decrypted(decryptedPass);
405                 String usernamePass = userName + ":" + decPass;
406                 String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes())));
407                 HttpHeaders headers = new HttpHeaders();
408                 headers.add("Authorization", "Basic " + encToBase64);
409                 headers.setContentType(MediaType.APPLICATION_JSON);
410                 return headers;
411         }
412
413         private static String decrypted(String encrypted) throws Exception {
414                 String result = "";
415                 if (encrypted != null && encrypted.length() > 0) {
416                         try {
417                                 result = CipherUtil.decrypt(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
418                         } catch (Exception e) {
419                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
420                                 throw e;
421                         }
422                 }
423                 return result;
424         }
425
426         public static String truncateString(String originString, int size){
427                 if(originString.length()>=size){
428                         StringBuilder stringBuilder = new StringBuilder();
429                         stringBuilder.append(originString);
430                         stringBuilder.setLength(size);
431                         stringBuilder.append("...");
432                         return stringBuilder.toString();
433                 }
434                 return originString;
435         }
436 }