nexus site path corrected
[portal.git] / ecomp-portal-BE / src / main / java / org / openecomp / portalapp / portal / utils / EcompPortalUtils.java
1 /*-
2  * ================================================================================
3  * eCOMP Portal
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.utils;
21
22
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;
29
30 import javax.servlet.http.HttpServletResponse;
31
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;
39 import org.slf4j.MDC;
40
41 import com.fasterxml.jackson.core.JsonProcessingException;
42 import com.fasterxml.jackson.databind.ObjectMapper;
43
44 public class EcompPortalUtils {
45         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
46
47         /**
48          * @param orgUserId
49          * @return true if orgUserId is not empty and contains only alphanumeric, false otherwise
50          */
51         public static boolean legitimateUserId(String orgUserId) {
52                 return orgUserId.matches("^[a-zA-Z0-9]+$");
53         }
54
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) {
61                                         tokens.add(token);
62                                 }
63                         }
64                 }
65                 return tokens;
66         }
67
68         public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
69                 return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
70         }
71
72         public static String jsonMessageResponse(String message) {
73                 return String.format("{\"message\":\"%s\"}", message);
74         }
75
76         public static void logAndSerializeObject(String source, String msg, Object obj) {
77                 try {
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);
86                 }
87         }
88
89         public static void rollbackTransaction(Transaction transaction, String errorMessage) {
90                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
91                 try {
92                         if(transaction != null) {
93                                 transaction.rollback();
94                         }
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));
98                 }
99         }
100         
101         public static void closeLocalSession(Session localSession, String errorMessage) {
102                 logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
103                 try {
104                         if(localSession != null) {
105                                 localSession.close();
106                         }
107                 } catch (Exception e) {
108                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoCloseSessionError);
109                         logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception: " + EcompPortalUtils.getStackTrace(e));
110                 }
111         }
112
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";
116
117         /**
118          * Set response status to Unauthorized if user == null and to Forbidden in all (!) other cases.
119          * Logging is not performed if invocator == null
120          * @param user
121          * @param response
122          * @param invocator - may be null
123          */
124         public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
125                 if (user == null) {
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));
130                 } else {
131                         response.setStatus(HttpServletResponse.SC_FORBIDDEN);
132                         MDC.put(EPSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
133                 }
134                 if (invocator != null) {
135                         logger.warn(EELFLoggerDelegate.errorLogger, invocator + ", permissions problem, response status = " + response.getStatus());
136                 }
137         }
138         
139         public static int getExternalAppResponseCode() {
140                 String responseCode = MDC.get(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE);
141                 int responseCodeInt = 0;
142                 try {
143                         if (responseCode != null && responseCode != "") {
144                                 responseCodeInt = Integer.valueOf(responseCode);
145                         }
146                 } catch (Exception e){
147                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getResponseCode(). Details: "+EcompPortalUtils.getStackTrace(e));
148                 }
149                 return responseCodeInt;
150         }
151         
152         // This method might be just for testing purposes.
153         public static void setExternalAppResponseCode(int responseCode) {
154                 try {
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));
159                 }
160         }
161         
162         public static String getHTTPStatusString(int httpStatusCode) {
163                 String httpStatusString = "unknown_error";
164                 try {
165                         httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
166                         if (httpStatusString != null) {
167                                 httpStatusString = httpStatusString.toLowerCase();
168                         }
169                 } catch (Exception e) {
170                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getHTTPStatusString(). Details: "+EcompPortalUtils.getStackTrace(e));                       
171                 }
172                 return httpStatusString;
173         }
174         
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";
183                 try {
184                         if (responseCode < 1000) {
185                                 httpStatusString = getHTTPStatusString(responseCode);
186                         }
187                 } catch (Exception e) {
188                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getFEErrorString(). Details: "+EcompPortalUtils.getStackTrace(e));  
189                 }
190                 responseString = internalExternalString + responseCode + " " + httpStatusString;
191                 return responseString;
192         }
193
194         public static boolean isProductionBuild()
195         {
196                 boolean productionBuild = true;
197                 String epVersion = EcompVersion.buildNumber;
198                 if (epVersion != null)
199                 {
200                         int buildNum = epVersion.lastIndexOf('.');
201                         if (buildNum > 0)
202                         {
203                                 int buildNumber = Integer.parseInt(epVersion.substring(buildNum+1));
204                                 if (buildNumber < 3000) // Production versions are 3000+,  (ie 1.0.3003)
205                                 {
206                                         productionBuild = false;
207                                 }
208                         }
209                 }
210             return productionBuild;
211         }
212         
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 ();
220                 }
221         }
222         
223         public static String getMyIpAdddress() {
224                 InetAddress ip;
225                 String localIp;
226                 try {
227                         ip = InetAddress.getLocalHost();
228                         localIp = ip.getHostAddress();
229                 } catch (UnknownHostException e) {
230                         localIp = "unknown";
231                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
232                 }
233                 return localIp;
234         }
235         
236         public static String getMyHostName() {
237                 InetAddress ip;
238                 String hostName;
239                 try {
240                         ip = InetAddress.getLocalHost();
241                         hostName = ip.getHostName();
242                 } catch (UnknownHostException e) {
243                         hostName = "unknown";
244                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
245                 }
246                 return hostName;
247         }
248 }