2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ================================================================================
20 package org.openecomp.portalapp.portal.utils;
23 import java.io.PrintWriter;
24 import java.io.StringWriter;
25 import java.net.InetAddress;
26 import java.net.UnknownHostException;
27 import java.util.ArrayList;
28 import java.util.List;
30 import javax.servlet.http.HttpServletResponse;
32 import org.hibernate.Session;
33 import org.hibernate.Transaction;
34 import org.openecomp.portalapp.portal.domain.EPUser;
35 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
36 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
37 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
38 import org.openecomp.portalsdk.core.util.SystemProperties;
41 import com.fasterxml.jackson.core.JsonProcessingException;
42 import com.fasterxml.jackson.databind.ObjectMapper;
44 public class EcompPortalUtils {
45 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
49 * @return true if orgUserId is not empty and contains only alphanumeric, false otherwise
51 public static boolean legitimateUserId(String orgUserId) {
52 return orgUserId.matches("^[a-zA-Z0-9]+$");
55 public static List<String> parsingByRegularExpression(String source, String regex) {
56 List<String> tokens = new ArrayList<String>();
57 if (source != null && source.length() > 0) {
58 String[] parsed = source.split(regex);
59 for (String token : parsed) {
60 if (token.length() > 0) {
68 public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
69 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
72 public static String jsonMessageResponse(String message) {
73 return String.format("{\"message\":\"%s\"}", message);
76 public static void logAndSerializeObject(String source, String msg, Object obj) {
78 String objectAsJson = new ObjectMapper().writeValueAsString(obj);
79 logger.debug(EELFLoggerDelegate.debugLogger, String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
80 } catch (JsonProcessingException e) {
81 logger.warn(EELFLoggerDelegate.errorLogger, "JsonProcessingException occurred while parsing the response, Details:" + EcompPortalUtils.getStackTrace(e));
82 EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
83 } catch(Exception e) {
84 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while parsing the response, Details:" + EcompPortalUtils.getStackTrace(e));
85 EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
89 public static void rollbackTransaction(Transaction transaction, String errorMessage) {
90 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
92 if(transaction != null) {
93 transaction.rollback();
95 } catch (Exception e) {
96 EPLogUtil.logEcompError(EPAppMessagesEnum.BeExecuteRollbackError);
97 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction, Details: " + EcompPortalUtils.getStackTrace(e));
101 public static void closeLocalSession(Session localSession, String errorMessage) {
102 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
104 if(localSession != null) {
105 localSession.close();
107 } catch (Exception e) {
108 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoCloseSessionError);
109 logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception: " + EcompPortalUtils.getStackTrace(e));
113 // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
114 // It should be defined in SystemProperties.
115 private static final String GLOBAL_LOGIN_URL = "global-login-url";
118 * Set response status to Unauthorized if user == null and to Forbidden in all (!) other cases.
119 * Logging is not performed if invocator == null
122 * @param invocator - may be null
124 public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
126 String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL);
127 response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
128 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
129 MDC.put(EPSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
131 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
132 MDC.put(EPSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
134 if (invocator != null) {
135 logger.warn(EELFLoggerDelegate.errorLogger, invocator + ", permissions problem, response status = " + response.getStatus());
139 public static int getExternalAppResponseCode() {
140 String responseCode = MDC.get(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE);
141 int responseCodeInt = 0;
143 if (responseCode != null && responseCode != "") {
144 responseCodeInt = Integer.valueOf(responseCode);
146 } catch (Exception e){
147 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getResponseCode(). Details: "+EcompPortalUtils.getStackTrace(e));
149 return responseCodeInt;
152 // This method might be just for testing purposes.
153 public static void setExternalAppResponseCode(int responseCode) {
155 String responseCodeString = String.valueOf(responseCode);
156 MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, responseCodeString);
157 } catch (Exception e) {
158 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in setResponseCode(). Details: "+EcompPortalUtils.getStackTrace(e));
162 public static String getHTTPStatusString(int httpStatusCode) {
163 String httpStatusString = "unknown_error";
165 httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
166 if (httpStatusString != null) {
167 httpStatusString = httpStatusString.toLowerCase();
169 } catch (Exception e) {
170 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getHTTPStatusString(). Details: "+EcompPortalUtils.getStackTrace(e));
172 return httpStatusString;
175 public static String getFEErrorString(Boolean internal, int responseCode) {
176 // Return a String like the following:
177 // "Internal Ecomp Error: 500 internal_server_error" or
178 // "External App Error: 404 not_found"
179 // TODO: create our own Ecomp error codes, starting with 1000 and up.
180 String responseString = "";
181 String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
182 String httpStatusString = "unknown_error";
184 if (responseCode < 1000) {
185 httpStatusString = getHTTPStatusString(responseCode);
187 } catch (Exception e) {
188 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getFEErrorString(). Details: "+EcompPortalUtils.getStackTrace(e));
190 responseString = internalExternalString + responseCode + " " + httpStatusString;
191 return responseString;
194 public static boolean isProductionBuild()
196 boolean productionBuild = true;
197 String epVersion = EcompVersion.buildNumber;
198 if (epVersion != null)
200 int buildNum = epVersion.lastIndexOf('.');
203 int buildNumber = Integer.parseInt(epVersion.substring(buildNum+1));
204 if (buildNumber < 3000) // Production versions are 3000+, (ie 1.0.3003)
206 productionBuild = false;
210 return productionBuild;
213 private static final Object stackTraceLock = new Object();
214 public static String getStackTrace(Throwable t) {
215 synchronized(stackTraceLock) {
216 StringWriter sw = new StringWriter ();
217 PrintWriter pw = new PrintWriter (sw);
218 t.printStackTrace (pw);
219 return sw.toString ();
223 public static String getMyIpAdddress() {
227 ip = InetAddress.getLocalHost();
228 localIp = ip.getHostAddress();
229 } catch (UnknownHostException e) {
231 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
236 public static String getMyHostName() {
240 ip = InetAddress.getLocalHost();
241 hostName = ip.getHostName();
242 } catch (UnknownHostException e) {
243 hostName = "unknown";
244 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));