2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.openecomp.portalapp.portal.utils;
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;
47 import javax.servlet.http.HttpServletResponse;
48 import javax.xml.bind.DatatypeConverter;
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;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.MediaType;
62 import com.fasterxml.jackson.core.JsonProcessingException;
63 import com.fasterxml.jackson.databind.ObjectMapper;
65 public class EcompPortalUtils {
67 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
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";
76 * @return true if orgUserId is not empty and contains only alphanumeric, false
79 public static boolean legitimateUserId(String orgUserId) {
80 return orgUserId.matches("^[a-zA-Z0-9]+$");
84 * Splits the string into a list of tokens using the specified regular
91 * @return List of tokens split from the source
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) {
107 * Builds a JSON object with error code and message information.
111 * @param errorMessage
113 * @return JSON object as a String
115 public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
116 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
120 * Builds a JSON object with the specified message
124 * @return JSON object as a String
126 public static String jsonMessageResponse(String message) {
127 return String.format("{\"message\":\"%s\"}", message);
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.
135 * Logger for the class where the object was built; the logger
136 * carries the class name.
138 * First portion of the log message
140 * Second portion of the log message
142 * Object to serialize as JSON
144 public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
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);
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.
163 * First portion of the log message
165 * Second portion of the log message
167 * Object to serialize as JSON
169 public static void logAndSerializeObject(String source, String msg, Object obj) {
170 logAndSerializeObject(logger, source, msg, obj);
173 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
174 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
176 if (transaction != null) {
177 transaction.rollback();
179 } catch (Exception e) {
180 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
181 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
186 public static void closeLocalSession(Session localSession, String errorMessage) {
187 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
189 if (localSession != null) {
190 localSession.close();
192 } catch (Exception e) {
193 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
194 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
199 * Set response status to Unauthorized if user == null and to Forbidden in all
200 * (!) other cases. Logging is not performed if invocator == null
205 * HttpServletResponse
209 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
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));
216 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
217 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
219 if (invocator != null) {
220 logger.warn(EELFLoggerDelegate.errorLogger,
221 invocator + ", permissions problem, response status = " + response.getStatus());
225 public static int getExternalAppResponseCode() {
226 String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
227 int responseCodeInt = 0;
229 if (responseCode != null && responseCode != "") {
230 responseCodeInt = Integer.valueOf(responseCode);
232 } catch (Exception e) {
233 logger.error(EELFLoggerDelegate.errorLogger, "getExternalAppResponseCode failed", e);
235 return responseCodeInt;
238 // This method might be just for testing purposes.
239 public static void setExternalAppResponseCode(int responseCode) {
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);
248 public static String getHTTPStatusString(int httpStatusCode) {
249 String httpStatusString = "unknown_error";
251 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
252 if (httpStatusString != null) {
253 httpStatusString = httpStatusString.toLowerCase();
255 } catch (Exception e) {
256 logger.error(EELFLoggerDelegate.errorLogger, "getHTTPStatusString failed", e);
258 return httpStatusString;
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";
269 if (responseCode < 1000) {
270 httpStatusString = getHTTPStatusString(responseCode);
272 } catch (Exception e) {
273 logger.error(EELFLoggerDelegate.errorLogger, "getFEErrorString failed", e);
275 String responseString = internalExternalString + responseCode + " " + httpStatusString;
276 return responseString;
279 public static boolean isProductionBuild() {
280 boolean productionBuild = true;
281 String epVersion = EcompVersion.buildNumber;
282 if (epVersion != null) {
283 int buildNum = epVersion.lastIndexOf('.');
285 int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
286 if (buildNumber < 3000) // Production versions are 3000+, (ie
289 productionBuild = false;
293 return productionBuild;
296 public static String getMyIpAdddress() {
300 ip = InetAddress.getLocalHost();
301 localIp = ip.getHostAddress();
302 } catch (UnknownHostException e) {
304 logger.error(EELFLoggerDelegate.errorLogger, "getMyIpAdddress failed ", e);
309 public static String getMyHostName() {
313 ip = InetAddress.getLocalHost();
314 hostName = ip.getHostName();
315 } catch (UnknownHostException e) {
316 hostName = "unknown";
317 logger.error(EELFLoggerDelegate.errorLogger, "getMyHostName failed", e);
323 * Returns a default property if the expected one is not available
327 * @param defaultValue
329 * @return Default value if property is not defined or yields the empty string;
330 * else the property value.
332 public static String getPropertyOrDefault(String property, String defaultValue) {
333 if (!SystemProperties.containsProperty(property))
335 String value = SystemProperties.getProperty(property);
336 if (value == null || "".equals(value))
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
348 * @param beginDateTime
349 * the given begin time for the call
351 * the given end time for the call
354 public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
355 if (beginDateTime != null && endDateTime != null) {
357 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
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);
370 * Answers the protocol to use.
372 * @return Protocol name from property file; defaults to https.
374 public static String widgetMsProtocol() {
375 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
379 * Answers the host to use.
381 * @return Host name from property file; defaults to localhost.
383 public static String localOrDockerHost() {
384 return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
388 * It returns headers where username and password of external central auth is
391 * @return header which contains external central auth username and password
394 * if unable to decrypt the password
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);
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);
413 private static String decrypted(String encrypted) throws Exception {
415 if (encrypted != null && encrypted.length() > 0) {
417 result = CipherUtil.decrypt(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
418 } catch (Exception e) {
419 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
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();