diff options
Diffstat (limited to 'catalog-fe/src')
20 files changed, 820 insertions, 813 deletions
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java index e42644466e..d3169426ed 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/Constants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,14 +22,18 @@ package org.openecomp.sdc.fe; public class Constants { - public static final String HTTP_IV_USER = "HTTP_IV_USER"; - public static final String USER_ID = "USER_ID"; - public static final String ECOMP_PORTAL_COOKIE = "UserId"; - public static final String HTTP_CSP_FIRSTNAME = "HTTP_CSP_FIRSTNAME"; - public static final String HTTP_CSP_LASTNAME = "HTTP_CSP_LASTNAME"; - public static final String HTTP_IV_REMOTE_ADDRESS = "HTTP_IV_REMOTE_ADDRESS"; - public static final String HTTP_CSP_WSTYPE = "HTTP_CSP_WSTYPE"; - public static final String HTTP_CSP_EMAIL = "HTTP_CSP_EMAIL"; - public static final String WEBSEAL_USER_ID_HEADER = "csp-attuid"; - + private Constants() { + + } + + public static final String HTTP_IV_USER = "HTTP_IV_USER"; + public static final String USER_ID = "USER_ID"; + public static final String ECOMP_PORTAL_COOKIE = "UserId"; + public static final String HTTP_CSP_FIRSTNAME = "HTTP_CSP_FIRSTNAME"; + public static final String HTTP_CSP_LASTNAME = "HTTP_CSP_LASTNAME"; + public static final String HTTP_IV_REMOTE_ADDRESS = "HTTP_IV_REMOTE_ADDRESS"; + public static final String HTTP_CSP_WSTYPE = "HTTP_CSP_WSTYPE"; + public static final String HTTP_CSP_EMAIL = "HTTP_CSP_EMAIL"; + public static final String WEBSEAL_USER_ID_HEADER = "csp-attuid"; + } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/GzipFilter.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/GzipFilter.java index d7280edd41..f45bf82b3a 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/GzipFilter.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/GzipFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +20,12 @@ package org.openecomp.sdc.fe; -import javax.servlet.*; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -31,7 +36,7 @@ public class GzipFilter implements Filter { throws IOException, ServletException { - + final HttpServletResponse httpResponse = (HttpServletResponse) response; @@ -40,15 +45,15 @@ public class GzipFilter implements Filter { chain.doFilter(request, response); } - @Override - public void init(FilterConfig filterConfig) throws ServletException { - // TODO Auto-generated method stub - - } - - @Override - public void destroy() { - // TODO Auto-generated method stub - - } + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // TODO Auto-generated method stub + + } + + @Override + public void destroy() { + // TODO Auto-generated method stub + + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/Audit.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/Audit.java index 6eef071eb4..4cdc7d6497 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/Audit.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/Audit.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,45 +28,45 @@ import java.util.Map; public class Audit { - private Audit() { - } + private Audit() { + } - public static void error(Logger log, HttpRequestInfo requestInfo, int status) { - String errorMsg = "Internal Error"; - if (requestInfo != null && requestInfo.getHeaders() != null) { - Map<String, String> requestHeaders = requestInfo.getHeaders(); - errorMsg = String.format(Constants.ERROR_LOG_FORMAT, requestHeaders.get(Constants.USER_ID_HEADER), - requestHeaders.get(Constants.FIRST_NAME_HEADER) + " " - + requestHeaders.get(Constants.LAST_NAME_HEADER), - requestHeaders.get(Constants.ORIGIN_HEADER), requestHeaders.get(Constants.ACCESS_HEADER), - requestInfo.getRequestURL(), status); - } - log.error(errorMsg); - } + public static void error(Logger log, HttpRequestInfo requestInfo, int status) { + String errorMsg = "Internal Error"; + if (requestInfo != null && requestInfo.getHeaders() != null) { + Map<String, String> requestHeaders = requestInfo.getHeaders(); + errorMsg = String.format(Constants.ERROR_LOG_FORMAT, requestHeaders.get(Constants.USER_ID_HEADER), + requestHeaders.get(Constants.FIRST_NAME_HEADER) + " " + + requestHeaders.get(Constants.LAST_NAME_HEADER), + requestHeaders.get(Constants.ORIGIN_HEADER), requestHeaders.get(Constants.ACCESS_HEADER), + requestInfo.getRequestURL(), status); + } + log.error(errorMsg); + } - public static void error(Logger log, HttpServletRequest request, int status) { - String errorMsg = "Internal Error"; - if (request != null) { + public static void error(Logger log, HttpServletRequest request, int status) { + String errorMsg = "Internal Error"; + if (request != null) { - errorMsg = String.format(Constants.ERROR_LOG_FORMAT, request.getHeader(Constants.USER_ID_HEADER), - request.getHeader(Constants.FIRST_NAME_HEADER) + " " - + request.getHeader(Constants.LAST_NAME_HEADER), - request.getHeader(Constants.ORIGIN_HEADER), request.getHeader(Constants.ACCESS_HEADER), - request.getRequestURL(), status); - } - log.error(errorMsg); - } + errorMsg = String.format(Constants.ERROR_LOG_FORMAT, request.getHeader(Constants.USER_ID_HEADER), + request.getHeader(Constants.FIRST_NAME_HEADER) + " " + + request.getHeader(Constants.LAST_NAME_HEADER), + request.getHeader(Constants.ORIGIN_HEADER), request.getHeader(Constants.ACCESS_HEADER), + request.getRequestURL(), status); + } + log.error(errorMsg); + } - public static void info(Logger log, HttpRequestInfo requestInfo, int status) { - String errorMsg = "Internal Error"; - if (requestInfo != null && requestInfo.getHeaders() != null) { - Map<String, String> requestHeaders = requestInfo.getHeaders(); - errorMsg = String.format(Constants.ERROR_LOG_FORMAT, requestHeaders.get(Constants.USER_ID_HEADER), - requestHeaders.get(Constants.FIRST_NAME_HEADER) + " " - + requestHeaders.get(Constants.LAST_NAME_HEADER), - requestHeaders.get(Constants.ORIGIN_HEADER), requestHeaders.get(Constants.ACCESS_HEADER), - requestInfo.getRequestURL(), status); - } - log.info(errorMsg); - } + public static void info(Logger log, HttpRequestInfo requestInfo, int status) { + String errorMsg = "Internal Error"; + if (requestInfo != null && requestInfo.getHeaders() != null) { + Map<String, String> requestHeaders = requestInfo.getHeaders(); + errorMsg = String.format(Constants.ERROR_LOG_FORMAT, requestHeaders.get(Constants.USER_ID_HEADER), + requestHeaders.get(Constants.FIRST_NAME_HEADER) + " " + + requestHeaders.get(Constants.LAST_NAME_HEADER), + requestHeaders.get(Constants.ORIGIN_HEADER), requestHeaders.get(Constants.ACCESS_HEADER), + requestInfo.getRequestURL(), status); + } + log.info(errorMsg); + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/CrudOperation.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/CrudOperation.java index 27fc02c00a..133e8813b3 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/CrudOperation.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/CrudOperation.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,5 +22,5 @@ package org.openecomp.sdc.fe.impl; public enum CrudOperation { - CREATE, RETRIEVE, UPDATE, DELETE + CREATE, RETRIEVE, UPDATE, DELETE } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HttpRequestInfo.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HttpRequestInfo.java index bf5165fe58..de8ebe384b 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HttpRequestInfo.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HttpRequestInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,47 +27,47 @@ import java.util.Map; public class HttpRequestInfo { - public HttpRequestInfo(HttpServletRequest request, Map<String, String> headersMap, String data) { - headers = headersMap; - requestURL = request.getRequestURI(); - requestData = new ByteArrayInputStream(data.getBytes()); - originServletContext = request.getContextPath(); - } + public HttpRequestInfo(HttpServletRequest request, Map<String, String> headersMap, String data) { + headers = headersMap; + requestURL = request.getRequestURI(); + requestData = new ByteArrayInputStream(data.getBytes()); + originServletContext = request.getContextPath(); + } - private Map<String, String> headers; - private String requestURL; - private InputStream requestData; - private String originServletContext; + private Map<String, String> headers; + private String requestURL; + private InputStream requestData; + private String originServletContext; - public Map<String, String> getHeaders() { - return headers; - } + public Map<String, String> getHeaders() { + return headers; + } - public void setHeaders(Map<String, String> headers) { - this.headers = headers; - } + public void setHeaders(Map<String, String> headers) { + this.headers = headers; + } - public String getRequestURL() { - return requestURL; - } + public String getRequestURL() { + return requestURL; + } - public void setRequestURL(String requestURL) { - this.requestURL = requestURL; - } + public void setRequestURL(String requestURL) { + this.requestURL = requestURL; + } - public InputStream getRequestData() { - return requestData; - } + public InputStream getRequestData() { + return requestData; + } - public void setRequestData(InputStream requestData) { - this.requestData = requestData; - } + public void setRequestData(InputStream requestData) { + this.requestData = requestData; + } - public String getOriginServletContext() { - return originServletContext; - } + public String getOriginServletContext() { + return originServletContext; + } - public void setOriginServletContext(String originServletContext) { - this.originServletContext = originServletContext; - } + public void setOriginServletContext(String originServletContext) { + this.originServletContext = originServletContext; + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/ImportMetadata.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/ImportMetadata.java index c74c510206..52c888fc01 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/ImportMetadata.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/ImportMetadata.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,9 +32,9 @@ import lombok.Setter; @Getter @Setter public class ImportMetadata { - private String name; - private long size; - private String mime; - private String creator; - private String md5Checksum; + private String name; + private long size; + private String mime; + private String creator; + private String md5Checksum; } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/MdcData.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/MdcData.java index e95f6b8073..8a996d5b19 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/MdcData.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/MdcData.java @@ -27,9 +27,9 @@ import lombok.Getter; @Getter @AllArgsConstructor public class MdcData { - private String serviceInstanceID; - private String userId; - private String remoteAddr; - private String localAddr; - private Long transactionStartTime; - }
\ No newline at end of file + private String serviceInstanceID; + private String userId; + private String remoteAddr; + private String localAddr; + private Long transactionStartTime; +} diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java index e439600d51..cdb9e0f9bf 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,7 @@ package org.openecomp.sdc.fe.impl; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpHead; @@ -35,90 +36,88 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; public class PluginStatusBL { - private static final Logger log = LoggerFactory.getLogger(PluginStatusBL.class.getName()); - private final Gson gson; - private final CloseableHttpClient client; - private final PluginsConfiguration pluginsConfiguration; - private RequestConfig requestConfig; - - public PluginStatusBL() { - this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration(); - this.client = HttpClients.createDefault(); - this.gson = new GsonBuilder().setPrettyPrinting().create(); - } - - public PluginStatusBL(CloseableHttpClient client) { - this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration(); - this.client = client; - - this.gson = new GsonBuilder().setPrettyPrinting().create(); - - } - - public String getPluginsList() { - String result = null; - - if (pluginsConfiguration == null || pluginsConfiguration.getPluginsList() == null) { - log.warn("Configuration of type {} was not found", PluginsConfiguration.class); - throw new InvalidArgumentException("the plugin configuration was not read successfully."); - - } else { - log.debug("The value returned from getConfig is {}", pluginsConfiguration); - - result = gson.toJson(pluginsConfiguration.getPluginsList()); - } - return result; - } - - public String getPluginAvailability(String pluginId) { - String result = null; - - if (pluginsConfiguration == null || pluginsConfiguration.getPluginsList() == null) { - log.warn("Configuration of type {} was not found", PluginsConfiguration.class); - throw new InvalidArgumentException("the plugin configuration was not read successfully."); - - } else { - log.debug("The value returned from getConfig is {}", pluginsConfiguration); - Integer connectionTimeout = pluginsConfiguration.getConnectionTimeout(); - this.requestConfig = RequestConfig.custom() - .setSocketTimeout(connectionTimeout) - .setConnectTimeout(connectionTimeout) - .setConnectionRequestTimeout(connectionTimeout).build(); - - - Plugin wantedPlugin = pluginsConfiguration.getPluginsList().stream() - .filter(plugin -> plugin.getPluginId().equals(pluginId)) - .findAny() - .orElse(null); - - if (wantedPlugin != null) { - result = gson.toJson(checkPluginAvailability(wantedPlugin)); - } - } - return result; - } - - private boolean checkPluginAvailability(Plugin plugin) { - boolean result = false; - log.debug("sending head request to id:{} url:{}",plugin.getPluginId(),plugin.getPluginDiscoveryUrl()); - HttpHead head = new HttpHead(plugin.getPluginDiscoveryUrl()); - - head.setConfig(this.requestConfig); - - try (CloseableHttpResponse response = this.client.execute(head)) { - result = response != null && response.getStatusLine().getStatusCode() == 200; - log.debug("The plugin {} is {} with result {}",plugin.getPluginId(),( result ? "online" : "offline" ), result); - } catch (IOException e) { - log.debug("The plugin {} is offline", plugin.getPluginId()); - log.debug("Exception:",e); - } - - return result; - } + private static final Logger LOGGER = LoggerFactory.getLogger(PluginStatusBL.class.getName()); + private final Gson gson; + private final CloseableHttpClient client; + private final PluginsConfiguration pluginsConfiguration; + private RequestConfig requestConfig; + + public PluginStatusBL() { + this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration(); + this.client = HttpClients.createDefault(); + this.gson = new GsonBuilder().setPrettyPrinting().create(); + } + + public PluginStatusBL(CloseableHttpClient client) { + this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration(); + this.client = client; + + this.gson = new GsonBuilder().setPrettyPrinting().create(); + + } + + public String getPluginsList() { + String result = null; + + if (pluginsConfiguration == null || pluginsConfiguration.getPluginsList() == null) { + LOGGER.warn("Configuration of type {} was not found", PluginsConfiguration.class); + throw new InvalidArgumentException("the plugin configuration was not read successfully."); + + } else { + LOGGER.debug("The value returned from getConfig is {}", pluginsConfiguration); + + result = gson.toJson(pluginsConfiguration.getPluginsList()); + } + return result; + } + + public String getPluginAvailability(String pluginId) { + String result = null; + + if (pluginsConfiguration == null || pluginsConfiguration.getPluginsList() == null) { + LOGGER.warn("Configuration of type {} was not found", PluginsConfiguration.class); + throw new InvalidArgumentException("the plugin configuration was not read successfully."); + + } else { + LOGGER.debug("The value returned from getConfig is {}", pluginsConfiguration); + Integer connectionTimeout = pluginsConfiguration.getConnectionTimeout(); + this.requestConfig = RequestConfig.custom() + .setSocketTimeout(connectionTimeout) + .setConnectTimeout(connectionTimeout) + .setConnectionRequestTimeout(connectionTimeout).build(); + + + Plugin wantedPlugin = pluginsConfiguration.getPluginsList().stream() + .filter(plugin -> plugin.getPluginId().equals(pluginId)) + .findAny() + .orElse(null); + + if (wantedPlugin != null) { + result = gson.toJson(checkPluginAvailability(wantedPlugin)); + } + } + return result; + } + + private boolean checkPluginAvailability(Plugin plugin) { + boolean result = false; + LOGGER.debug("sending head request to id:{} url:{}", plugin.getPluginId(), plugin.getPluginDiscoveryUrl()); + HttpHead head = new HttpHead(plugin.getPluginDiscoveryUrl()); + + head.setConfig(this.requestConfig); + + try (CloseableHttpResponse response = this.client.execute(head)) { + result = response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; + LOGGER.debug("The plugin {} is {} with result {}", plugin.getPluginId(), (result ? "online" : "offline"), result); + } catch (IOException e) { + LOGGER.debug("The plugin {} is offline", plugin.getPluginId()); + LOGGER.debug("Exception:", e); + } + + return result; + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java index 987b1fe82e..f087f55349 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -37,52 +37,54 @@ import java.util.concurrent.Executors; public class FEAppContextListener extends AppContextListener implements ServletContextListener { - private static Logger log = LoggerFactory.getLogger(FEAppContextListener.class.getName()); + private static final int HEALTH_CHECHK_INTERVALE = 5; + private static final int PROBE_INTERVALE = 15; + private static Logger log = LoggerFactory.getLogger(FEAppContextListener.class.getName()); - public void contextInitialized(ServletContextEvent context) { + public void contextInitialized(ServletContextEvent context) { - super.contextInitialized(context); + super.contextInitialized(context); - ConfigurationManager configurationManager = new ConfigurationManager( - ExternalConfiguration.getConfigurationSource()); - log.debug("loading configuration from configDir:{} appName:{}", ExternalConfiguration.getConfigDir(), - ExternalConfiguration.getAppName()); - context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager); - - PluginStatusBL pbl = new PluginStatusBL(); - context.getServletContext().setAttribute(Constants.PLUGIN_BL_COMPONENT, pbl); + ConfigurationManager configurationManager = new ConfigurationManager( + ExternalConfiguration.getConfigurationSource()); + log.debug("loading configuration from configDir:{} appName:{}", ExternalConfiguration.getConfigDir(), + ExternalConfiguration.getAppName()); + context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager); - // Health Check service - HealthCheckService hcs = new HealthCheckService(context.getServletContext()); - hcs.start(configurationManager.getConfiguration().getHealthCheckIntervalInSeconds(5)); - context.getServletContext().setAttribute(Constants.HEALTH_CHECK_SERVICE_ATTR, hcs); + PluginStatusBL pbl = new PluginStatusBL(); + context.getServletContext().setAttribute(Constants.PLUGIN_BL_COMPONENT, pbl); - // Monitoring service - FeMonitoringService fms = new FeMonitoringService(context.getServletContext()); - fms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); + // Health Check service + HealthCheckService hcs = new HealthCheckService(context.getServletContext()); + hcs.start(configurationManager.getConfiguration().getHealthCheckIntervalInSeconds(HEALTH_CHECHK_INTERVALE)); + context.getServletContext().setAttribute(Constants.HEALTH_CHECK_SERVICE_ATTR, hcs); - if (configurationManager.getConfiguration() == null) { - log.debug("ERROR: configuration was not properly loaded"); - return; - } + // Monitoring service + FeMonitoringService fms = new FeMonitoringService(context.getServletContext()); + fms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(PROBE_INTERVALE)); - ExecutorService executorPool = Executors - .newFixedThreadPool(configurationManager.getConfiguration().getThreadpoolSize()); - context.getServletContext().setAttribute(Constants.THREAD_EXECUTOR_ATTR, executorPool); + if (configurationManager.getConfiguration() == null) { + log.debug("ERROR: configuration was not properly loaded"); + return; + } - log.debug("After executing {}", this.getClass()); - } + ExecutorService executorPool = Executors + .newFixedThreadPool(configurationManager.getConfiguration().getThreadpoolSize()); + context.getServletContext().setAttribute(Constants.THREAD_EXECUTOR_ATTR, executorPool); - public void contextDestroyed(ServletContextEvent context) { + log.debug("After executing {}", this.getClass()); + } - ExecutorService executorPool = (ExecutorService) context.getServletContext() - .getAttribute(Constants.THREAD_EXECUTOR_ATTR); - if (executorPool != null) { - executorPool.shutdown(); - } + public void contextDestroyed(ServletContextEvent context) { - super.contextDestroyed(context); + ExecutorService executorPool = (ExecutorService) context.getServletContext() + .getAttribute(Constants.THREAD_EXECUTOR_ATTR); + if (executorPool != null) { + executorPool.shutdown(); + } - } + super.contextDestroyed(context); + + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/MyObjectMapperProvider.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/MyObjectMapperProvider.java index 74f60146da..b46ca4c699 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/MyObjectMapperProvider.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/MyObjectMapperProvider.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,22 +28,22 @@ import javax.ws.rs.ext.Provider; @Provider public class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { - final ObjectMapper defaultObjectMapper; + private final ObjectMapper defaultObjectMapper; - public MyObjectMapperProvider() { - defaultObjectMapper = createDefaultMapper(); - } + MyObjectMapperProvider() { + defaultObjectMapper = createDefaultMapper(); + } - @Override - public ObjectMapper getContext(Class<?> type) { - return defaultObjectMapper; - } + @Override + public ObjectMapper getContext(Class<?> type) { + return defaultObjectMapper; + } - private static ObjectMapper createDefaultMapper() { - final ObjectMapper result = new ObjectMapper(); - result.configure(SerializationFeature.INDENT_OUTPUT, true); + private static ObjectMapper createDefaultMapper() { + final ObjectMapper result = new ObjectMapper(); + result.configure(SerializationFeature.INDENT_OUTPUT, true); - return result; - } + return result; + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java index 547f8ac367..8608506694 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigMgrServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,46 +43,46 @@ import javax.ws.rs.core.MediaType; @Path("/configmgr") public class ConfigMgrServlet extends BasicServlet { - private static Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class.getName()); + private static Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class.getName()); - @GET - @Path("/get") - @Produces(MediaType.APPLICATION_JSON) - public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { + @GET + @Path("/get") + @Produces(MediaType.APPLICATION_JSON) + public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { - String result = null; + String result = null; - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - ConfigurationManager configurationManager = (ConfigurationManager) context - .getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); + ConfigurationManager configurationManager = (ConfigurationManager) context + .getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); - if (type == null || type.equals("configuration")) { + if (type == null || type.equals("configuration")) { - Configuration configuration = configurationManager.getConfiguration(); - if (configuration == null) { - log.warn("Configuration of type {} was not found", Configuration.class); - } else { - log.info("The value returned from getConfig is {}", configuration); + Configuration configuration = configurationManager.getConfiguration(); + if (configuration == null) { + log.warn("Configuration of type {} was not found", Configuration.class); + } else { + log.info("The value returned from getConfig is {}", configuration); - result = gson.toJson(configuration); + result = gson.toJson(configuration); - } - } else if (type.equals("rest")) { + } + } else if (type.equals("rest")) { - RestConfigurationInfo configuration = configurationManager.getRestClientConfiguration(); - if (configuration == null) { - log.warn("Configuration of type {} was not found", RestConfigurationInfo.class); - } else { - log.info("The value returned from getConfig is {}", configuration); + RestConfigurationInfo configuration = configurationManager.getRestClientConfiguration(); + if (configuration == null) { + log.warn("Configuration of type {} was not found", RestConfigurationInfo.class); + } else { + log.info("The value returned from getConfig is {}", configuration); - result = gson.toJson(configuration); + result = gson.toJson(configuration); - } + } - } - return result; + } + return result; - } + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java index 073c79e683..138318bb61 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/ConfigServlet.java @@ -43,7 +43,7 @@ import javax.ws.rs.core.Response.Status; @Path("/config") public class ConfigServlet extends LoggingServlet { - private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigServlet.class.getName()); @GET @@ -67,7 +67,7 @@ public class ConfigServlet extends LoggingServlet { return response; } catch (Exception e) { FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Response"); - log.error("Unexpected FE response logging error :", e); + LOGGER.error("Unexpected FE response logging error :", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("{}").build(); } @@ -88,7 +88,7 @@ public class ConfigServlet extends LoggingServlet { String result = pluginStatusBL.getPluginAvailability(pluginId); if (result == null) { - log.debug("Plugin with pluginId: {} was not found in the configuration", pluginId); + LOGGER.debug("Plugin with pluginId: {} was not found in the configuration", pluginId); return Response.status(Status.NOT_FOUND).entity("Plugin with pluginId:\"" + pluginId + "\" was not found in the configuration").build(); } @@ -99,13 +99,13 @@ public class ConfigServlet extends LoggingServlet { return response; } catch (Exception e) { FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Response"); - log.error("Unexpected FE response logging error :", e); + LOGGER.error("Unexpected FE response logging error :", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("{}").build(); } } protected void inHttpRequest(HttpServletRequest httpRequest) { - log.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol()); + LOGGER.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol()); } /** @@ -114,6 +114,6 @@ public class ConfigServlet extends LoggingServlet { * @param response http response */ protected void outHttpResponse(Response response) { - log.info("SC=\"{}\"", response.getStatus()); + LOGGER.info("SC=\"{}\"", response.getStatus()); } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java index 563af73ebe..fbf81b432e 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,10 +35,10 @@ import static org.openecomp.sdc.common.api.Constants.HEALTH_CHECK_SERVICE_ATTR; @Loggable(prepend = true, value = Loggable.TRACE, trim = false) @Path("/healthCheck") public class FeHealthCheckServlet extends BasicServlet { - @GET - public Response getFEandBeHealthCheck(@Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - HealthCheckService hcs = ((HealthCheckService) context.getAttribute(HEALTH_CHECK_SERVICE_ATTR)); - return hcs.getFeHealth(); - } + @GET + public Response getFEandBeHealthCheck(@Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + HealthCheckService hcs = ((HealthCheckService) context.getAttribute(HEALTH_CHECK_SERVICE_ATTR)); + return hcs.getFeHealth(); + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java index 122543dd0c..1c7b174c57 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -42,200 +42,196 @@ import java.net.URL; import java.util.concurrent.TimeUnit; public class FeProxyServlet extends SSLProxyServlet { - private static final long serialVersionUID = 1L; - private static final String URL = "%s://%s%s%s"; - private static final String ONBOARDING_CONTEXT = "/onboarding-api"; - private static final String DCAED_CONTEXT = "/dcae-api"; - private static final String WORKFLOW_CONTEXT = "/wf"; - private static final String SDC1_FE_PROXY = "/sdc1/feProxy"; - private static final String PLUGIN_ID_WORKFLOW = "WORKFLOW"; - - private static final Logger log = Logger.getLogger(FeProxyServlet.class); - private static Cache<String, MdcData> mdcDataCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build(); - - - @Override - protected String rewriteTarget(HttpServletRequest request) { - String originalUrl=""; - String redirectedUrl = ""; - - try { - logFeRequest(request); - - originalUrl = request.getRequestURL().toString(); - redirectedUrl = getModifiedUrl(request); - - } catch(MalformedURLException mue){ - FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Request"); - log.error(EcompLoggerErrorCode.DATA_ERROR,"FeProxyServlet rewriteTarget", "sdc-FE", "Malformed URL Exception: ", mue); - } - catch (Exception e) { - FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Request"); - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"FeProxyServlet rewriteTarget", "sdc-FE", "Unexpected FE request processing error: ", e); - } - - log.debug("FeProxyServlet Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); - - return redirectedUrl; - } - - @Override - protected void onProxyResponseSuccess(HttpServletRequest request, HttpServletResponse proxyResponse, Response response) { - try { - logFeResponse(request, response); - } catch (Exception e) { - FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Response"); - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"FeProxyServlet onProxyResponseSuccess", "sdc-FE", "Unexpected FE response logging error: ", e); - } - super.onProxyResponseSuccess(request, proxyResponse, response); - } - - private void logFeRequest(HttpServletRequest httpRequest) { - - MDC.clear(); - - Long transactionStartTime = System.currentTimeMillis(); - // UUID - In FE, we are supposed to get the below header from UI. - // We do not generate it if it's missing - BE does. - String uuid = httpRequest.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER); - String serviceInstanceID = httpRequest.getHeader(Constants.X_ECOMP_SERVICE_ID_HEADER); - - if (uuid != null && uuid.length() > 0) { - // UserId for logging - String userId = httpRequest.getHeader(Constants.USER_ID_HEADER); - - String remoteAddr = httpRequest.getRemoteAddr(); - String localAddr = httpRequest.getLocalAddr(); - - mdcDataCache.put(uuid, new MdcData(serviceInstanceID, userId, remoteAddr, localAddr, transactionStartTime)); - - updateMdc(uuid, serviceInstanceID, userId, remoteAddr, localAddr, null); - } - inHttpRequest(httpRequest); - } - - private void logFeResponse(HttpServletRequest request, Response proxyResponse) { - String uuid = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER); - String transactionRoundTime = null; - - if (uuid != null) { - MdcData mdcData = mdcDataCache.getIfPresent(uuid); - if (mdcData != null) { - Long transactionStartTime = mdcData.getTransactionStartTime(); - if (transactionStartTime != null) {// should'n ever be null, but - // just to be defensive - transactionRoundTime = Long.toString(System.currentTimeMillis() - transactionStartTime); - } - updateMdc(uuid, mdcData.getServiceInstanceID(), mdcData.getUserId(), mdcData.getRemoteAddr(), mdcData.getLocalAddr(), transactionRoundTime); - } - } - outHttpResponse(proxyResponse); - - MDC.clear(); - } - - // Extracted for purpose of clear method name, for logback %M parameter - private void inHttpRequest(HttpServletRequest httpRequest) { - log.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol()); - } - - // Extracted for purpose of clear method name, for logback %M parameter - private void outHttpResponse(Response proxyResponse) { - log.info("SC=\"{}\"", proxyResponse.getStatus()); - } - - private void updateMdc(String uuid, String serviceInstanceID, String userId, String remoteAddr, String localAddr, String transactionStartTime) { - MDC.put("uuid", uuid); - MDC.put("serviceInstanceID", serviceInstanceID); - MDC.put("userId", userId); - MDC.put("remoteAddr", remoteAddr); - MDC.put("localAddr", localAddr); - MDC.put("timer", transactionStartTime); - } - - - - private String getModifiedUrl(HttpServletRequest request) throws MalformedURLException { - Configuration config = getConfiguration(request); - if (config == null) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"FeProxyServlet getModifiedUrl", "sdc-FE", "failed to retrieve configuration."); - throw new RuntimeException("failed to read FE configuration"); - } - String uri = request.getRequestURI(); - String protocol; - String host; - String port; - if (uri.contains(ONBOARDING_CONTEXT)){ - uri = uri.replace(SDC1_FE_PROXY+ONBOARDING_CONTEXT,ONBOARDING_CONTEXT); - protocol = config.getOnboarding().getProtocolBe(); - host = config.getOnboarding().getHostBe(); - port = config.getOnboarding().getPortBe().toString(); - }else if(uri.contains(DCAED_CONTEXT)){ - uri = uri.replace(SDC1_FE_PROXY+DCAED_CONTEXT,DCAED_CONTEXT); - protocol = config.getBeProtocol(); - host = config.getBeHost(); - if (config.getBeProtocol().equals(BeProtocol.HTTP.getProtocolName())) { - port = config.getBeHttpPort().toString(); - } else { - port = config.getBeSslPort().toString(); - } - } - else if (uri.contains(WORKFLOW_CONTEXT)){ - String workflowPluginURL = getPluginConfiguration(request).getPluginsList() - .stream() - .filter(plugin -> plugin.getPluginId().equalsIgnoreCase(PLUGIN_ID_WORKFLOW)) - .map(Plugin::getPluginDiscoveryUrl) - .findFirst().orElse(null); - - java.net.URL workflowURL = new URL(workflowPluginURL); - protocol = workflowURL.getProtocol(); - host = workflowURL.getHost(); - port = String.valueOf(workflowURL.getPort()); - uri = uri.replace(SDC1_FE_PROXY + WORKFLOW_CONTEXT, workflowURL.getPath() + WORKFLOW_CONTEXT); - } - else{ - uri = uri.replace(SDC1_FE_PROXY,"/sdc2"); - protocol = config.getBeProtocol(); - host = config.getBeHost(); - if (config.getBeProtocol().equals(BeProtocol.HTTP.getProtocolName())) { - port = config.getBeHttpPort().toString(); - } else { - port = config.getBeSslPort().toString(); - } - } - - String authority = getAuthority(host, port); - String queryString = getQueryString(request); - return String.format(URL,protocol,authority,uri,queryString); - - } - - private PluginsConfiguration getPluginConfiguration(HttpServletRequest request) { - return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getPluginsConfiguration(); - } - private Configuration getConfiguration(HttpServletRequest request) { - return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration(); - } - - private String getAuthority(String host, String port) { - String authority; - if (port==null){ - authority=host; - } - else{ - authority=host+":"+port; - } - return authority; - } - - private String getQueryString(HttpServletRequest request) { - String queryString = request.getQueryString(); - if (queryString != null) { - queryString="?"+queryString; - } - else{ - queryString=""; - } - return queryString; - } + private static final long serialVersionUID = 1L; + private static final String URL = "%s://%s%s%s"; + private static final String ONBOARDING_CONTEXT = "/onboarding-api"; + private static final String DCAED_CONTEXT = "/dcae-api"; + private static final String WORKFLOW_CONTEXT = "/wf"; + private static final String SDC1_FE_PROXY = "/sdc1/feProxy"; + private static final String PLUGIN_ID_WORKFLOW = "WORKFLOW"; + + private static final Logger LOGGER = Logger.getLogger(FeProxyServlet.class); + private static final int EXPIRE_DURATION = 10; + private static Cache<String, MdcData> mdcDataCache = CacheBuilder.newBuilder().expireAfterWrite(EXPIRE_DURATION, TimeUnit.SECONDS).build(); + + + @Override + protected String rewriteTarget(HttpServletRequest request) { + String originalUrl = ""; + String redirectedUrl = ""; + + try { + logFeRequest(request); + + originalUrl = request.getRequestURL().toString(); + redirectedUrl = getModifiedUrl(request); + + } catch (MalformedURLException mue) { + FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Request"); + LOGGER.error(EcompLoggerErrorCode.DATA_ERROR, "FeProxyServlet rewriteTarget", "sdc-FE", "Malformed URL Exception: ", mue); + } catch (Exception e) { + FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Request"); + LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "FeProxyServlet rewriteTarget", "sdc-FE", "Unexpected FE request processing error: ", e); + } + + LOGGER.debug("FeProxyServlet Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); + + return redirectedUrl; + } + + @Override + protected void onProxyResponseSuccess(HttpServletRequest request, HttpServletResponse proxyResponse, Response response) { + try { + logFeResponse(request, response); + } catch (Exception e) { + FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Response"); + LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "FeProxyServlet onProxyResponseSuccess", "sdc-FE", "Unexpected FE response logging error: ", e); + } + super.onProxyResponseSuccess(request, proxyResponse, response); + } + + private void logFeRequest(HttpServletRequest httpRequest) { + + MDC.clear(); + + Long transactionStartTime = System.currentTimeMillis(); + // UUID - In FE, we are supposed to get the below header from UI. + // We do not generate it if it's missing - BE does. + String uuid = httpRequest.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER); + String serviceInstanceID = httpRequest.getHeader(Constants.X_ECOMP_SERVICE_ID_HEADER); + + if (uuid != null && uuid.length() > 0) { + // UserId for logging + String userId = httpRequest.getHeader(Constants.USER_ID_HEADER); + + String remoteAddr = httpRequest.getRemoteAddr(); + String localAddr = httpRequest.getLocalAddr(); + + mdcDataCache.put(uuid, new MdcData(serviceInstanceID, userId, remoteAddr, localAddr, transactionStartTime)); + + updateMdc(uuid, serviceInstanceID, userId, remoteAddr, localAddr, null); + } + inHttpRequest(httpRequest); + } + + private void logFeResponse(HttpServletRequest request, Response proxyResponse) { + String uuid = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER); + String transactionRoundTime = null; + + if (uuid != null) { + MdcData mdcData = mdcDataCache.getIfPresent(uuid); + if (mdcData != null) { + Long transactionStartTime = mdcData.getTransactionStartTime(); + if (transactionStartTime != null) { // should'n ever be null, but + // just to be defensive + transactionRoundTime = Long.toString(System.currentTimeMillis() - transactionStartTime); + } + updateMdc(uuid, mdcData.getServiceInstanceID(), mdcData.getUserId(), mdcData.getRemoteAddr(), mdcData.getLocalAddr(), transactionRoundTime); + } + } + outHttpResponse(proxyResponse); + + MDC.clear(); + } + + // Extracted for purpose of clear method name, for logback %M parameter + private void inHttpRequest(HttpServletRequest httpRequest) { + LOGGER.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol()); + } + + // Extracted for purpose of clear method name, for logback %M parameter + private void outHttpResponse(Response proxyResponse) { + LOGGER.info("SC=\"{}\"", proxyResponse.getStatus()); + } + + private void updateMdc(String uuid, String serviceInstanceID, String userId, String remoteAddr, String localAddr, String transactionStartTime) { + MDC.put("uuid", uuid); + MDC.put("serviceInstanceID", serviceInstanceID); + MDC.put("userId", userId); + MDC.put("remoteAddr", remoteAddr); + MDC.put("localAddr", localAddr); + MDC.put("timer", transactionStartTime); + } + + + private String getModifiedUrl(HttpServletRequest request) throws MalformedURLException { + Configuration config = getConfiguration(request); + if (config == null) { + LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "FeProxyServlet getModifiedUrl", "sdc-FE", "failed to retrieve configuration."); + throw new RuntimeException("failed to read FE configuration"); + } + String uri = request.getRequestURI(); + String protocol; + String host; + String port; + if (uri.contains(ONBOARDING_CONTEXT)) { + uri = uri.replace(SDC1_FE_PROXY + ONBOARDING_CONTEXT, ONBOARDING_CONTEXT); + protocol = config.getOnboarding().getProtocolBe(); + host = config.getOnboarding().getHostBe(); + port = config.getOnboarding().getPortBe().toString(); + } else if (uri.contains(DCAED_CONTEXT)) { + uri = uri.replace(SDC1_FE_PROXY + DCAED_CONTEXT, DCAED_CONTEXT); + protocol = config.getBeProtocol(); + host = config.getBeHost(); + if (config.getBeProtocol().equals(BeProtocol.HTTP.getProtocolName())) { + port = config.getBeHttpPort().toString(); + } else { + port = config.getBeSslPort().toString(); + } + } else if (uri.contains(WORKFLOW_CONTEXT)) { + String workflowPluginURL = getPluginConfiguration(request).getPluginsList() + .stream() + .filter(plugin -> plugin.getPluginId().equalsIgnoreCase(PLUGIN_ID_WORKFLOW)) + .map(Plugin::getPluginDiscoveryUrl) + .findFirst().orElse(null); + + java.net.URL workflowURL = new URL(workflowPluginURL); + protocol = workflowURL.getProtocol(); + host = workflowURL.getHost(); + port = String.valueOf(workflowURL.getPort()); + uri = uri.replace(SDC1_FE_PROXY + WORKFLOW_CONTEXT, workflowURL.getPath() + WORKFLOW_CONTEXT); + } else { + uri = uri.replace(SDC1_FE_PROXY, "/sdc2"); + protocol = config.getBeProtocol(); + host = config.getBeHost(); + if (config.getBeProtocol().equals(BeProtocol.HTTP.getProtocolName())) { + port = config.getBeHttpPort().toString(); + } else { + port = config.getBeSslPort().toString(); + } + } + + String authority = getAuthority(host, port); + String queryString = getQueryString(request); + return String.format(URL, protocol, authority, uri, queryString); + + } + + private PluginsConfiguration getPluginConfiguration(HttpServletRequest request) { + return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getPluginsConfiguration(); + } + + private Configuration getConfiguration(HttpServletRequest request) { + return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration(); + } + + private String getAuthority(String host, String port) { + String authority; + if (port == null) { + authority = host; + } else { + authority = host + ":" + port; + } + return authority; + } + + private String getQueryString(HttpServletRequest request) { + String queryString = request.getQueryString(); + if (queryString != null) { + queryString = "?" + queryString; + } else { + queryString = ""; + } + return queryString; + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java index d8b3295f51..6c312ceff7 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java @@ -52,8 +52,18 @@ import static java.util.Arrays.asList; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; import static org.apache.http.HttpStatus.SC_OK; -import static org.openecomp.sdc.common.api.Constants.*; -import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.*; +import static org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_BE; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CASSANDRA; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DCAE; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DISTRIBUTION_ENGINE; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_FE; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_JANUSGRAPH; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING; +import static org.openecomp.sdc.common.api.Constants.HTTPS; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UNKNOWN; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP; import static org.openecomp.sdc.common.http.client.api.HttpRequest.get; import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion; import static org.slf4j.LoggerFactory.getLogger; @@ -61,6 +71,7 @@ import static org.slf4j.LoggerFactory.getLogger; public class HealthCheckService { private static final String URL = "%s://%s:%s/sdc2/rest/healthCheck"; + private static final int HEALTH_STATUS_CODE = 500; private static Logger healthLogger = getLogger("asdc.fe.healthcheck"); private static Logger log = getLogger(HealthCheckService.class.getName()); private final List<String> healthCheckFeComponents = asList(HC_COMPONENT_ON_BOARDING, HC_COMPONENT_DCAE); @@ -69,14 +80,14 @@ public class HealthCheckService { /** * This executor will execute the health check task. */ - ScheduledExecutorService healthCheckExecutor = newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "FE-Health-Check-Thread")); + private ScheduledExecutorService healthCheckExecutor = newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "FE-Health-Check-Thread")); public void setTask(HealthCheckScheduledTask task) { this.task = task; } - private HealthCheckScheduledTask task ; - private HealthStatus lastHealthStatus = new HealthStatus(500, "{}"); + private HealthCheckScheduledTask task; + private HealthStatus lastHealthStatus = new HealthStatus(HEALTH_STATUS_CODE, "{}"); private ServletContext context; public HealthCheckService(ServletContext context) { @@ -85,7 +96,7 @@ public class HealthCheckService { } public void start(int interval) { - this.healthCheckExecutor.scheduleAtFixedRate( getTask() , 0, interval, TimeUnit.SECONDS); + this.healthCheckExecutor.scheduleAtFixedRate(getTask(), 0, interval, TimeUnit.SECONDS); } /** @@ -105,6 +116,7 @@ public class HealthCheckService { public HealthStatus getLastHealthStatus() { return lastHealthStatus; } + public HealthCheckScheduledTask getTask() { return task; } @@ -130,6 +142,10 @@ public class HealthCheckService { } protected class HealthCheckScheduledTask implements Runnable { + + public static final int READ_TIMEOUT_DEFAULT_VAL = 5000; + public static final int CONNECT_TIMEOUT_MS = 3000; + @Override public void run() { healthLogger.trace("Executing FE Health Check Task - Start"); @@ -163,8 +179,8 @@ public class HealthCheckService { } StringBuilder description = new StringBuilder(""); - int connectTimeoutMs = 3000; - int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(5000); + int connectTimeoutMs = CONNECT_TIMEOUT_MS; + int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(READ_TIMEOUT_DEFAULT_VAL); if (healthCheckUrl != null) { ObjectMapper mapper = new ObjectMapper(); @@ -191,11 +207,11 @@ public class HealthCheckService { private void logFeAlarm(int lastFeStatus) { switch (lastFeStatus) { - case 200: + case SC_OK: FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckRecovery, "FE Health Recovered"); FeEcompErrorManager.getInstance().logFeHealthCheckRecovery("FE Health Recovered"); break; - case 500: + case SC_INTERNAL_SERVER_ERROR: FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckError, "Connection with ASDC-BE is probably down"); FeEcompErrorManager.getInstance().logFeHealthCheckError("Connection with ASDC-BE is probably down"); break; @@ -212,8 +228,8 @@ public class HealthCheckService { String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(), HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); - int connectTimeoutMs = 3000; - int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(5000); + int connectTimeoutMs = CONNECT_TIMEOUT_MS; + int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(READ_TIMEOUT_DEFAULT_VAL); HealthCheckWrapper feAggHealthCheck; try { @@ -232,14 +248,14 @@ public class HealthCheckService { boolean aggregateFeStatus = (response != null && response.getStatusCode() == SC_INTERNAL_SERVER_ERROR) ? false : healthCheckUtil.getAggregateStatus(feAggHealthCheck.getComponentsInfo(), config.getHealthStatusExclude()); return new HealthStatus(aggregateFeStatus ? SC_OK : SC_INTERNAL_SERVER_ERROR, gson.toJson(feAggHealthCheck)); } catch (Exception e) { - FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT,EcompErrorEnum.FeHealthCheckGeneralError, "Unexpected FE Health check error"); + FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckGeneralError, "Unexpected FE Health check error"); FeEcompErrorManager.getInstance().logFeHealthCheckGeneralError("Unexpected FE Health check error"); log.error("Unexpected FE health check error {}", e.getMessage()); return new HealthStatus(SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } - protected Configuration getConfig(){ + protected Configuration getConfig() { return ((ConfigurationManager) context.getAttribute(CONFIGURATION_MANAGER_ATTR)) .getConfiguration(); } @@ -263,7 +279,7 @@ public class HealthCheckService { baseComponentHCInfo.setComponentsInfo(new ArrayList<>()); } baseComponentHCInfo.getComponentsInfo().addAll(feComponentsInfo); - boolean status = healthCheckUtil.getAggregateStatus(baseComponentHCInfo.getComponentsInfo() ,config.getHealthStatusExclude()); + boolean status = healthCheckUtil.getAggregateStatus(baseComponentHCInfo.getComponentsInfo(), config.getHealthStatusExclude()); baseComponentHCInfo.setHealthCheckStatus(status ? UP : DOWN); String componentsDesc = healthCheckUtil.getAggregateDescription(baseComponentHCInfo.getComponentsInfo(), baseComponentHCInfo.getDescription()); diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/KibanaServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/KibanaServlet.java index 844d87075d..1c6a575087 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/KibanaServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/KibanaServlet.java @@ -22,8 +22,6 @@ package org.openecomp.sdc.fe.servlets; -import javax.servlet.http.HttpServletRequest; - import org.eclipse.jetty.proxy.ProxyServlet; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.fe.config.Configuration; @@ -31,17 +29,19 @@ import org.openecomp.sdc.fe.config.ConfigurationManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.http.HttpServletRequest; + public class KibanaServlet extends ProxyServlet { private static final long serialVersionUID = 1L; - private static final Logger log = LoggerFactory.getLogger(KibanaServlet.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(KibanaServlet.class.getName()); @Override public String rewriteTarget(HttpServletRequest request) { String originalUrl = request.getRequestURI(); String redirectedUrl = getModifiedUrl(request); - log.debug("KibanaServlet Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); + LOGGER.debug("KibanaServlet Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); return redirectedUrl; } @@ -50,7 +50,7 @@ public class KibanaServlet extends ProxyServlet { Configuration config = getConfiguration(request); if (config == null) { - log.error("Failed to retrieve configuration."); + LOGGER.error("Failed to retrieve configuration."); throw new NullPointerException("Failed to retrieve configuration."); } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/LoggingServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/LoggingServlet.java index 574b2707f0..3cb601fc3c 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/LoggingServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/LoggingServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,11 +35,12 @@ import java.util.concurrent.TimeUnit; public abstract class LoggingServlet extends BasicServlet { - private static final Logger log = LoggerFactory.getLogger(BasicServlet.class.getName()); - private static final Cache<String, MdcData> mdcDataCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build(); + private static final int EXPIRE_DURATION = 10; + private static final Cache<String, MdcData> mdcDataCache = CacheBuilder.newBuilder().expireAfterWrite(EXPIRE_DURATION, TimeUnit.SECONDS).build(); /** * log incoming requests + * * @param httpRequest the http request */ protected void logFeRequest(HttpServletRequest httpRequest) { @@ -65,7 +66,8 @@ public abstract class LoggingServlet extends BasicServlet { /** * log response - * @param request orig request + * + * @param request orig request * @param response returned response */ protected void logFeResponse(HttpServletRequest request, Response response) { @@ -76,7 +78,7 @@ public abstract class LoggingServlet extends BasicServlet { MdcData mdcData = mdcDataCache.getIfPresent(uuid); if (mdcData != null) { Long transactionStartTime = mdcData.getTransactionStartTime(); - if (transactionStartTime != null) {// should'n ever be null, but + if (transactionStartTime != null) { // should'n ever be null, but // just to be defensive transactionRoundTime = Long.toString(System.currentTimeMillis() - transactionStartTime); } @@ -90,24 +92,27 @@ public abstract class LoggingServlet extends BasicServlet { /** * Extracted for purpose of clear method name, for logback %M parameter + * * @param httpRequest http request */ - protected abstract void inHttpRequest(HttpServletRequest httpRequest) ; + protected abstract void inHttpRequest(HttpServletRequest httpRequest); /** * Extracted for purpose of clear method name, for logback %M parameter + * * @param response http response */ protected abstract void outHttpResponse(Response response); /** * update mdc with values from the request - * @param uuid service uuid - * @param serviceInstanceID serviceInstanceID - * @param userId userId - * @param remoteAddr remoteAddr - * @param localAddr localAddr + * + * @param uuid service uuid + * @param serviceInstanceID serviceInstanceID + * @param userId userId + * @param remoteAddr remoteAddr + * @param localAddr localAddr * @param transactionStartTime transactionStartTime */ private void updateMdc(String uuid, String serviceInstanceID, String userId, String remoteAddr, String localAddr, String transactionStartTime) { diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java index 31467b7edc..84e0226e7a 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,8 +21,6 @@ package org.openecomp.sdc.fe.servlets; import org.onap.portalsdk.core.onboarding.util.CipherUtil; -import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; -import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; import org.openecomp.sdc.common.impl.MutableHttpServletRequest; import org.openecomp.sdc.fe.Constants; import org.openecomp.sdc.fe.config.Configuration; @@ -50,245 +48,246 @@ import java.util.List; @Path("/") public class PortalServlet extends HttpServlet { - private static Logger log = LoggerFactory.getLogger(PortalServlet.class.getName()); - private static final long serialVersionUID = 1L; - public static final String MISSING_HEADERS_MSG = "Missing Headers In Request"; - public static final String AUTHORIZATION_ERROR_MSG = "Autherization error"; - public static final String NEW_LINE = System.getProperty("line.separator"); + private static Logger log = LoggerFactory.getLogger(PortalServlet.class.getName()); + private static final long serialVersionUID = 1L; + public static final String MISSING_HEADERS_MSG = "Missing Headers In Request"; + private static final String AUTHORIZATION_ERROR_MSG = "Autherization error"; + private static final String NEW_LINE = System.getProperty("line.separator"); - /** - * Entry point from ECOMP portal - */ - @GET - @Path("/portal") - public void doGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) { - try { - addRequestHeadersUsingWebseal(request, response); - } catch (Exception e) { - FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet"); - log.error("Error during getting portal page", e); - } - } - - /** - * Building new HTTP request and setting headers for the request The request - * will dispatch to index.html - * - * @param request - * @param response - * @throws ServletException - * @throws IOException - */ - private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("text/html"); + /** + * Entry point from ECOMP portal + */ + @GET + @Path("/portal") + public void doGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) { + try { + addRequestHeadersUsingWebseal(request, response); + } catch (Exception e) { + FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet"); + log.error("Error during getting portal page", e); + } + } - // Create new request object to dispatch - MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request); + /** + * Building new HTTP request and setting headers for the request The request + * will dispatch to index.html + * + * @param request + * @param response + * @throws ServletException + * @throws IOException + */ + private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - // Get configuration object (reads data from configuration.yaml) - Configuration configuration = getConfiguration(request); + response.setContentType("text/html"); - // Check if we got header from webseal - String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER); - if (null == userId) { - // Authentication via ecomp portal - try { - String userIdFromCookie = getUserIdFromCookie(request); - if (("").equals(userIdFromCookie)) { - // This is probably a webseal request, so missing header in request should be printed. - response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG); - } - userId = userIdFromCookie; - } catch (Exception e) { - response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG); - } - } - - // Replace webseal header with open source header - mutableRequest.putHeader(Constants.USER_ID, userId); - - // Getting identification headers from configuration.yaml - // (identificationHeaderFields) and setting them to new request - // mutableRequest - List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields(); - for (List<String> possibleHeadersToRecieve : identificationHeaderFields) { - String allowedHeaderToPass = possibleHeadersToRecieve.get(0); - setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest); - } + // Create new request object to dispatch + MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request); - // Getting optional headers from configuration.yaml - // (optionalHeaderFields) and setting them to new request mutableRequest - List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields(); - for (List<String> possibleHeadersToRecieve : optionalHeaderFields) { - String allowedHeaderToPass = possibleHeadersToRecieve.get(0); - setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest); - } + // Get configuration object (reads data from configuration.yaml) + Configuration configuration = getConfiguration(request); - // Print headers from original request for debug purposes - printHeaders(request); + // Check if we got header from webseal + String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER); + if (null == userId) { + // Authentication via ecomp portal + try { + String userIdFromCookie = getUserIdFromCookie(request); + if (("").equals(userIdFromCookie)) { + // This is probably a webseal request, so missing header in request should be printed. + response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG); + } + userId = userIdFromCookie; + } catch (Exception e) { + response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG); + log.error("Error during adding request header", e); + } + } - // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest). - // Via ecomp portal do not need to check the headers. - boolean allHeadersExist = true; - if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) { - allHeadersExist = checkHeaders(mutableRequest); - } - - if (allHeadersExist) { - addCookies(response, mutableRequest, getMandatoryHeaders(request)); - addCookies(response, mutableRequest, getOptionalHeaders(request)); - RequestDispatcher rd = request.getRequestDispatcher("index.html"); - rd.forward(mutableRequest, response); - } else { - response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG); - } - } + // Replace webseal header with open source header + mutableRequest.putHeader(Constants.USER_ID, userId); - /** - * Print all request headers to the log - * - * @param request - */ - private void printHeaders(HttpServletRequest request) { + // Getting identification headers from configuration.yaml + // (identificationHeaderFields) and setting them to new request + // mutableRequest + List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields(); + for (List<String> possibleHeadersToRecieve : identificationHeaderFields) { + String allowedHeaderToPass = possibleHeadersToRecieve.get(0); + setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest); + } - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - String sessionId = ""; - if (request.getSession() != null) { - String id = request.getSession().getId(); - if (id != null) { - sessionId = id; - } - } + // Getting optional headers from configuration.yaml + // (optionalHeaderFields) and setting them to new request mutableRequest + List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields(); + for (List<String> possibleHeadersToRecieve : optionalHeaderFields) { + String allowedHeaderToPass = possibleHeadersToRecieve.get(0); + setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest); + } - builder.append("Receiving request with headers:" + NEW_LINE); - log.debug("{}", request.getHeaderNames()); - @SuppressWarnings("unchecked") - Enumeration<String> headerNames = request.getHeaderNames(); - if (headerNames != null) { - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - String headerValue = request.getHeader(headerName); - builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE); - } - } + // Print headers from original request for debug purposes + printHeaders(request); - log.debug(builder.toString()); - } + // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest). + // Via ecomp portal do not need to check the headers. + boolean allHeadersExist = true; + if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) { + allHeadersExist = checkHeaders(mutableRequest); + } - } + if (allHeadersExist) { + addCookies(response, mutableRequest, getMandatoryHeaders(request)); + addCookies(response, mutableRequest, getOptionalHeaders(request)); + RequestDispatcher rd = request.getRequestDispatcher("index.html"); + rd.forward(mutableRequest, response); + } else { + response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG); + } + } - /** - * Add cookies (that where set in the new request headers) in the response - * - * @param response - * @param request - * @param headers - */ - private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) { - for (int i = 0; i < headers.length; i++) { - String currHeader = headers[i]; - String headerValue = request.getHeader(currHeader); - if (headerValue != null) { - response.addCookie(new Cookie(currHeader, headerValue)); - } - } - } + /** + * Print all request headers to the log + * + * @param request + */ + private void printHeaders(HttpServletRequest request) { - /** - * Get mandatory headers (identificationHeaderFields) String array, and - * checks that each header exists in the new request - * - * @param request - * @return boolean - */ - private boolean checkHeaders(HttpServletRequest request) { - String[] mandatoryHeaders = getMandatoryHeaders(request); + if (log.isDebugEnabled()) { + StringBuilder builder = new StringBuilder(); + String sessionId = ""; + if (request.getSession() != null) { + String id = request.getSession().getId(); + if (id != null) { + sessionId = id; + } + } - boolean allHeadersExist = true; - for (int i = 0; i < mandatoryHeaders.length; i++) { - String headerValue = request.getHeader(mandatoryHeaders[i]); - if (headerValue == null) { - allHeadersExist = false; - break; - } - } - return allHeadersExist; - } + builder.append("Receiving request with headers:" + NEW_LINE); + log.debug("{}", request.getHeaderNames()); + @SuppressWarnings("unchecked") + Enumeration<String> headerNames = request.getHeaderNames(); + if (headerNames != null) { + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + String headerValue = request.getHeader(headerName); + builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE); + } + } - /** - * Get mandatory headers (identificationHeaderFields) from - * configuration.yaml file and return String[] - * - * @param request - * @return String[] - */ - private String[] getMandatoryHeaders(HttpServletRequest request) { - Configuration configuration = getConfiguration(request); - List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields(); - String[] mandatoryHeaders = new String[identificationHeaderFields.size()]; - for (int i = 0; i < identificationHeaderFields.size(); i++) { - mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0); - } - return mandatoryHeaders; - } + log.debug(builder.toString()); + } - /** - * Get optional headers (optionalHeaderFields) from configuration.yaml file - * and return String[] - * - * @param request - * @return String[] - */ - private String[] getOptionalHeaders(HttpServletRequest request) { - Configuration configuration = getConfiguration(request); - List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields(); - String[] optionalHeaders = new String[optionalHeaderFields.size()]; - for (int i = 0; i < optionalHeaderFields.size(); i++) { - optionalHeaders[i] = optionalHeaderFields.get(i).get(0); - } - return optionalHeaders; - } + } - /** - * Return Configuration object to read from configuration.yaml - * - * @param request - * @return Configuration - */ - private Configuration getConfiguration(HttpServletRequest request) { - ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR); - return configManager.getConfiguration(); - } + /** + * Add cookies (that where set in the new request headers) in the response + * + * @param response + * @param request + * @param headers + */ + private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) { + for (int i = 0; i < headers.length; i++) { + String currHeader = headers[i]; + String headerValue = request.getHeader(currHeader); + if (headerValue != null) { + response.addCookie(new Cookie(currHeader, headerValue)); + } + } + } - private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) { - boolean newHeaderIsSet = false; - for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) { - String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i)); - if (headerValue != null) { - newRequest.putHeader(newHeaderToSet, headerValue); - newHeaderIsSet = true; - } - } - return newHeaderIsSet; - } - - private static String getUserIdFromCookie(HttpServletRequest request) throws Exception { - String userId = ""; - Cookie[] cookies = request.getCookies(); - Cookie userIdcookie = null; - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) - userIdcookie = cookie; - if (userIdcookie != null) { - userId = CipherUtil.decrypt(userIdcookie.getValue()); - //Todo Remove after smoke test & review - /*userId = CipherUtil.decrypt(userIdcookie.getValue(), - PortalApiProperties.getProperty(PortalApiConstants.CSP_GATE_KEEPER_PROD_KEY));*/ - } - return userId; + /** + * Get mandatory headers (identificationHeaderFields) String array, and + * checks that each header exists in the new request + * + * @param request + * @return boolean + */ + private boolean checkHeaders(HttpServletRequest request) { + String[] mandatoryHeaders = getMandatoryHeaders(request); - } + boolean allHeadersExist = true; + for (int i = 0; i < mandatoryHeaders.length; i++) { + String headerValue = request.getHeader(mandatoryHeaders[i]); + if (headerValue == null) { + allHeadersExist = false; + break; + } + } + return allHeadersExist; + } + + /** + * Get mandatory headers (identificationHeaderFields) from + * configuration.yaml file and return String[] + * + * @param request + * @return String[] + */ + private String[] getMandatoryHeaders(HttpServletRequest request) { + Configuration configuration = getConfiguration(request); + List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields(); + String[] mandatoryHeaders = new String[identificationHeaderFields.size()]; + for (int i = 0; i < identificationHeaderFields.size(); i++) { + mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0); + } + return mandatoryHeaders; + } + + /** + * Get optional headers (optionalHeaderFields) from configuration.yaml file + * and return String[] + * + * @param request + * @return String[] + */ + private String[] getOptionalHeaders(HttpServletRequest request) { + Configuration configuration = getConfiguration(request); + List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields(); + String[] optionalHeaders = new String[optionalHeaderFields.size()]; + for (int i = 0; i < optionalHeaderFields.size(); i++) { + optionalHeaders[i] = optionalHeaderFields.get(i).get(0); + } + return optionalHeaders; + } + + /** + * Return Configuration object to read from configuration.yaml + * + * @param request + * @return Configuration + */ + private Configuration getConfiguration(HttpServletRequest request) { + ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR); + return configManager.getConfiguration(); + } + + private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) { + boolean newHeaderIsSet = false; + for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) { + String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i)); + if (headerValue != null) { + newRequest.putHeader(newHeaderToSet, headerValue); + newHeaderIsSet = true; + } + } + return newHeaderIsSet; + } + + private static String getUserIdFromCookie(HttpServletRequest request) throws Exception { + String userId = ""; + Cookie[] cookies = request.getCookies(); + Cookie userIdcookie = null; + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) { + userIdcookie = cookie; + } + } + } + if (userIdcookie != null) { + userId = CipherUtil.decrypt(userIdcookie.getValue()); + } + return userId; + + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java index 182d198013..25659ddd92 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,60 +34,41 @@ import javax.servlet.ServletException; public abstract class SSLProxyServlet extends ProxyServlet { - private static final long serialVersionUID = 1L; - private static Logger log = LoggerFactory.getLogger(SSLProxyServlet.class.getName()); + private static final long serialVersionUID = 1L; + private static final int TIMEOUT = 600000; + private static Logger log = LoggerFactory.getLogger(SSLProxyServlet.class.getName()); - //TODO If no problems will arise remove in next merge - /*@Override - protected void sendProxyRequest(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Request proxyRequest) { - // Add Missing Headers to proxy request - @SuppressWarnings("unchecked") - Enumeration<String> headerNames = clientRequest.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - if (!proxyRequest.getHeaders().containsKey(headerName)) { - String headerVal = clientRequest.getHeader(headerName); - log.debug("Adding missing header to request, header name: {} , header value: {}", headerName, - headerVal); - proxyRequest.header(headerName, headerVal); - } - } - proxyRequest.getHeaders().remove(HttpHeader.HOST); - - super.sendProxyRequest(clientRequest, proxyResponse, proxyRequest); - }*/ + @Override + protected HttpClient createHttpClient() throws ServletException { + Configuration config = ((ConfigurationManager) getServletConfig().getServletContext() + .getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration(); + boolean isSecureClient = !config.getBeProtocol().equals(BeProtocol.HTTP.getProtocolName()); + HttpClient client = (isSecureClient) ? getSecureHttpClient() : super.createHttpClient(); + setTimeout(TIMEOUT); + client.setIdleTimeout(TIMEOUT); + client.setStopTimeout(TIMEOUT); - @Override - protected HttpClient createHttpClient() throws ServletException { - Configuration config = ((ConfigurationManager) getServletConfig().getServletContext() - .getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration(); - boolean isSecureClient = !config.getBeProtocol().equals(BeProtocol.HTTP.getProtocolName()); - HttpClient client = (isSecureClient) ? getSecureHttpClient() : super.createHttpClient(); - setTimeout(600000); - client.setIdleTimeout(600000); - client.setStopTimeout(600000); + return client; + } - return client; - } + private HttpClient getSecureHttpClient() throws ServletException { + // Instantiate and configure the SslContextFactory + SslContextFactory sslContextFactory = new SslContextFactory(true); - private HttpClient getSecureHttpClient() throws ServletException { - // Instantiate and configure the SslContextFactory - SslContextFactory sslContextFactory = new SslContextFactory(true); + // Instantiate HttpClient with the SslContextFactory + HttpClient httpClient = new HttpClient(sslContextFactory); - // Instantiate HttpClient with the SslContextFactory - HttpClient httpClient = new HttpClient(sslContextFactory); + // Configure HttpClient, for example: + httpClient.setFollowRedirects(false); - // Configure HttpClient, for example: - httpClient.setFollowRedirects(false); - - // Start HttpClient - try { - httpClient.start(); - } catch (Exception x) { + // Start HttpClient + try { + httpClient.start(); + } catch (Exception x) { log.error("Exception thrown while starting httpClient {}", x); - throw new ServletException(x); - } + throw new ServletException(x); + } return httpClient; - } + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/BeProtocol.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/BeProtocol.java index 4575f307c5..9257bd40fe 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/BeProtocol.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/BeProtocol.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,14 +21,14 @@ package org.openecomp.sdc.fe.utils; public enum BeProtocol { - HTTP("http"), SSL("ssl"); - private String protocolName; + HTTP("http"), SSL("ssl"); + private String protocolName; - public String getProtocolName() { - return protocolName; - } + public String getProtocolName() { + return protocolName; + } - BeProtocol(String protocolName) { - this.protocolName = protocolName; - } - }; + BeProtocol(String protocolName) { + this.protocolName = protocolName; + } +}; |