diff options
author | vasraz <vasyl.razinkov@est.tech> | 2021-03-27 23:06:34 +0000 |
---|---|---|
committer | Christophe Closset <christophe.closset@intl.att.com> | 2021-03-29 07:14:31 +0000 |
commit | 269abccbd334bb5bcfdb7d22c56ffcebc201d512 (patch) | |
tree | 0cab17661257d10bf5c1a01168292ecd1f2abd35 | |
parent | fb3e794d901205f16c3d92b519f85b1584847a29 (diff) |
Reformat catalog-fe
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Issue-ID: SDC-3449
Change-Id: Ic4c34262e5cb4e5851af493400ccc01af5684a18
23 files changed, 596 insertions, 826 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 d3169426ed..083f6703ae 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 @@ -17,15 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe; public class Constants { - 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"; @@ -35,5 +30,6 @@ public class Constants { 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() { + } } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/GzipFilter.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/GzipFilter.java index bb2207c422..641b55bce6 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/GzipFilter.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/GzipFilter.java @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.filters; +import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -27,33 +27,24 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class GzipFilter implements Filter { @Override - public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) - throws IOException, - ServletException { - - + public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletResponse httpResponse = (HttpServletResponse) response; - - httpResponse.setHeader("Content-Encoding", "gzip"); httpResponse.setHeader("Content-Type", "application/javascript"); chain.doFilter(request, response); } - @Override - public void init(FilterConfig filterConfig) throws ServletException { - // 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 - - } -}
\ No newline at end of file + @Override + public void destroy() { + // TODO Auto-generated method stub + } +} diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/SecurityFilter.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/SecurityFilter.java index c615e4a44d..cfcb55453c 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/SecurityFilter.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/filters/SecurityFilter.java @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.filters; - -import org.apache.commons.lang3.StringUtils; -import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; -import org.openecomp.sdc.common.log.wrappers.Logger; - +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -34,21 +32,18 @@ import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.NoSuchElementException; +import org.apache.commons.lang3.StringUtils; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.sdc.common.log.wrappers.Logger; public class SecurityFilter implements Filter { - private static final Logger log = Logger.getLogger(SecurityFilter.class.getName()); - - private static final String PORTAL_COOKIE_NAME_IS_NOT_SET = "Portal cookie name is not set in portal.properties file"; - - private List<String> excludedUrls; static final String PORTAL_COOKIE_NAME_KEY = "portal_cookie_name"; static final String PORTAL_REDIRECT_URL_KEY = "ecomp_redirect_url"; - static final String FILTER_EXLUDED_URLS_KEY ="excludedUrls"; + static final String FILTER_EXLUDED_URLS_KEY = "excludedUrls"; + private static final Logger log = Logger.getLogger(SecurityFilter.class.getName()); + private static final String PORTAL_COOKIE_NAME_IS_NOT_SET = "Portal cookie name is not set in portal.properties file"; + private List<String> excludedUrls; @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -56,26 +51,23 @@ public class SecurityFilter implements Filter { } @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; - log.debug("SecurityFilter received request with URL {}", httpRequest.getRequestURL()); //add redirecting to Portal if cookie is not provided if (!excludedUrls.contains(httpRequest.getServletPath()) && !isRequestFromPortal(httpRequest.getCookies())) { //redirect to portal app log.debug("Request {} is not from Portal, redirecting there", httpRequest.getServletPath()); httpResponse.sendRedirect(PortalApiProperties.getProperty(PORTAL_REDIRECT_URL_KEY)); - } - else { + } else { filterChain.doFilter(servletRequest, servletResponse); } } @Override public void destroy() { - } private boolean isRequestFromPortal(Cookie[] cookies) { @@ -84,7 +76,6 @@ public class SecurityFilter implements Filter { log.error(PORTAL_COOKIE_NAME_IS_NOT_SET); throw new NoSuchElementException(PORTAL_COOKIE_NAME_IS_NOT_SET); } - return cookies != null && Arrays.stream(cookies) - .anyMatch(c->StringUtils.equals(c.getName(), portalCookieValue)); + return cookies != null && Arrays.stream(cookies).anyMatch(c -> StringUtils.equals(c.getName(), portalCookieValue)); } } 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 4cdc7d6497..17a8e48769 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 @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.impl; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; import org.openecomp.sdc.common.api.Constants; import org.slf4j.Logger; -import javax.servlet.http.HttpServletRequest; -import java.util.Map; - public class Audit { private Audit() { @@ -36,10 +34,8 @@ public class Audit { 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); + 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); } @@ -47,12 +43,9 @@ public class Audit { 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); + 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); } @@ -62,10 +55,8 @@ public class Audit { 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); + 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 133e8813b3..5e84bc2d83 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 @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.impl; -public enum CrudOperation { - - CREATE, RETRIEVE, UPDATE, DELETE -} +public enum CrudOperation {CREATE, RETRIEVE, UPDATE, DELETE} diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckScheduledTask.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckScheduledTask.java index 5470fc8568..2d99f84b9a 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckScheduledTask.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckScheduledTask.java @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.impl; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CATALOG_FACADE_MS; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING; + import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; @@ -28,6 +30,13 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; @@ -48,18 +57,8 @@ import org.openecomp.sdc.common.util.HealthCheckUtil; import org.openecomp.sdc.fe.config.Configuration; import org.openecomp.sdc.fe.config.FeEcompErrorManager; -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CATALOG_FACADE_MS; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING; - public class HealthCheckScheduledTask implements Runnable { + private static final Logger healthLogger = Logger.getLogger("asdc.fe.healthcheck"); private static final Logger log = Logger.getLogger(HealthCheckScheduledTask.class.getName()); private static final String LOG_PARTNER_NAME = "SDC.FE"; @@ -68,18 +67,14 @@ public class HealthCheckScheduledTask implements Runnable { private static final String LOG_TARGET_SERVICE_NAME_OB = "getOnboardingConfig"; private static final String LOG_TARGET_SERVICE_NAME_FACADE = "getCatalogFacadeConfig"; private static final String LOG_SERVICE_NAME = "/rest/healthCheck"; - private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler(); - private static final String URL = "%s://%s:%s/sdc2/rest/healthCheck"; - - private final List<String> healthCheckFeComponents = - Arrays.asList(HC_COMPONENT_ON_BOARDING, HC_COMPONENT_CATALOG_FACADE_MS); private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil(); private static final String DEBUG_CONTEXT = "HEALTH_FE"; private static final String EXTERNAL_HC_URL = "%s://%s:%s%s"; + private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler(); private static String ONBOARDING_HC_URL; private static String CATALOG_FACADE_MS_HC_URL; - + private final List<String> healthCheckFeComponents = Arrays.asList(HC_COMPONENT_ON_BOARDING, HC_COMPONENT_CATALOG_FACADE_MS); private final HealthCheckService service; HealthCheckScheduledTask(HealthCheckService service) { @@ -94,7 +89,6 @@ public class HealthCheckScheduledTask implements Runnable { return CATALOG_FACADE_MS_HC_URL; } - @Override public void run() { mdcFieldsHandler.addInfoForErrorAndDebugLogging(LOG_PARTNER_NAME); @@ -102,7 +96,6 @@ public class HealthCheckScheduledTask implements Runnable { HealthCheckService.HealthStatus currentHealth = checkHealth(); int currentHealthStatus = currentHealth.getStatusCode(); healthLogger.trace("Executing FE Health Check Task - Status = {}", currentHealthStatus); - // In case health status was changed, issue alarm/recovery if (currentHealthStatus != service.getLastHealthStatus().getStatusCode()) { log.trace("FE Health State Changed to {}. Issuing alarm / recovery alarm...", currentHealthStatus); @@ -115,13 +108,11 @@ public class HealthCheckScheduledTask implements Runnable { private List<HealthCheckInfo> addHostedComponentsFeHealthCheck(String baseComponent, boolean requestedByBE) { String healthCheckUrl = getExternalComponentHcUrl(baseComponent); String serviceName = getExternalComponentHcUri(baseComponent); - ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(baseComponent) - .targetServiceName(serviceName).build(); - + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(baseComponent).targetServiceName(serviceName) + .build(); StringBuilder description = new StringBuilder(""); int connectTimeoutMs = 3000; int readTimeoutMs = service.getConfig().getHealthCheckSocketTimeoutInMs(5000); - if (healthCheckUrl != null) { ObjectMapper mapper = new ObjectMapper(); try { @@ -141,13 +132,8 @@ public class HealthCheckScheduledTask implements Runnable { } else { description.append(baseComponent + " health check Configuration is missing"); } - - String compName = requestedByBE ? Constants.HC_COMPONENT_FE : baseComponent; - return Collections.singletonList(new HealthCheckInfo( - compName, - HealthCheckInfo.HealthCheckStatus.DOWN, - null, - description.toString())); + String compName = requestedByBE ? Constants.HC_COMPONENT_FE : baseComponent; + return Collections.singletonList(new HealthCheckInfo(compName, HealthCheckInfo.HealthCheckStatus.DOWN, null, description.toString())); } private String getExternalComponentHcUri(String baseComponent) { @@ -166,7 +152,6 @@ public class HealthCheckScheduledTask implements Runnable { return healthCheckUri; } - @VisibleForTesting String getExternalComponentHcUrl(String baseComponent) { String healthCheckUrl = null; @@ -191,7 +176,8 @@ public class HealthCheckScheduledTask implements Runnable { FeEcompErrorManager.getInstance().logFeHealthCheckRecovery("FE Health Recovered"); break; case 500: - FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckError, "Connection with ASDC-BE is probably down"); + 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; default: @@ -202,16 +188,14 @@ public class HealthCheckScheduledTask implements Runnable { private HealthCheckService.HealthStatus checkHealth() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); Configuration config = service.getConfig(); - HealthCheckWrapper feAggHealthCheck; boolean aggregateFeStatus = false; String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(), - Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); + Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); int connectTimeoutMs = 3000; int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(5000); ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(LOG_TARGET_ENTITY_BE) - .targetServiceName(LOG_SERVICE_NAME).build(); - + .targetServiceName(LOG_SERVICE_NAME).build(); try { HttpResponse<String> response = HttpRequest.get(redirectedUrl, new HttpClientConfig(new Timeouts(connectTimeoutMs, readTimeoutMs))); log.debug("HC call to BE - status code is {}", response.getStatusCode()); @@ -221,14 +205,14 @@ public class HealthCheckScheduledTask implements Runnable { aggregateFeStatus = healthCheckUtil.getAggregateStatus(feAggHealthCheck.getComponentsInfo(), getExcludedComponentList()); } //Getting aggregate FE status - return new HealthCheckService.HealthStatus(aggregateFeStatus ? HttpStatus.SC_OK : HttpStatus.SC_INTERNAL_SERVER_ERROR, gson.toJson(feAggHealthCheck)); - - } - catch (Exception e) { + return new HealthCheckService.HealthStatus(aggregateFeStatus ? HttpStatus.SC_OK : HttpStatus.SC_INTERNAL_SERVER_ERROR, + gson.toJson(feAggHealthCheck)); + } catch (Exception e) { log.debug("Health Check error when trying to connect to BE or external FE. Error: {}", e); log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData, - "Health Check error when trying to connect to BE or external FE.", e.getMessage()); - FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT,EcompErrorEnum.FeHealthCheckGeneralError, "Unexpected FE Health check error"); + "Health Check error when trying to connect to BE or external FE.", e.getMessage()); + FeEcompErrorManager.getInstance() + .processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckGeneralError, "Unexpected FE Health check error"); FeEcompErrorManager.getInstance().logFeHealthCheckGeneralError("Unexpected FE Health check error"); return new HealthCheckService.HealthStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR, gson.toJson(getBeDownCheckInfos())); } @@ -236,7 +220,7 @@ public class HealthCheckScheduledTask implements Runnable { @VisibleForTesting List<String> getExcludedComponentList() { - List <String> excludedComponentList = Lists.newArrayList(service.getConfig().getHealthStatusExclude()); + List<String> excludedComponentList = Lists.newArrayList(service.getConfig().getHealthStatusExclude()); if (isCatalogFacadeMsExcluded()) { if (log.isInfoEnabled()) { log.info(HC_COMPONENT_CATALOG_FACADE_MS + " has been added to the Healthcheck exclude list"); @@ -256,9 +240,8 @@ public class HealthCheckScheduledTask implements Runnable { }.getType(); HealthCheckWrapper healthCheckWrapper = gson.fromJson(responseString, wrapperType); String description = "OK"; - healthCheckWrapper.getComponentsInfo() - .add(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckInfo.HealthCheckStatus.UP, ExternalConfiguration.getAppVersion(), description)); - + healthCheckWrapper.getComponentsInfo().add( + new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckInfo.HealthCheckStatus.UP, ExternalConfiguration.getAppVersion(), description)); //add FE hosted components for (String component : healthCheckFeComponents) { buildHealthCheckListForComponent(component, healthCheckWrapper); @@ -267,7 +250,6 @@ public class HealthCheckScheduledTask implements Runnable { } private void buildHealthCheckListForComponent(String component, HealthCheckWrapper healthCheckWrapper) { - HealthCheckInfo componentHCInfoFromBE = getComponentHcFromList(component, healthCheckWrapper.getComponentsInfo()); List<HealthCheckInfo> componentHCInfoList = addHostedComponentsFeHealthCheck(component, componentHCInfoFromBE != null); HealthCheckInfo calculateStatusFor; @@ -277,21 +259,16 @@ public class HealthCheckScheduledTask implements Runnable { } //update the subcomponents's HC if exist and recalculate the component status according to the subcomponets HC calculateStatusFor = updateSubComponentsInfoOfBeHc(componentHCInfoFromBE, componentHCInfoList); - } - else { - + } else { //this component is not in the BE HC response, need to add it and calculate the aggregated status if (log.isDebugEnabled()) { log.debug("{} component healthcheck info has been received from the component itself, it is not monitored by the BE", component); } //we assume that response from components which HC is not requested by BE have only one entry in the responded list calculateStatusFor = componentHCInfoList.get(0); - healthCheckWrapper.getComponentsInfo() - .add(calculateStatusFor); - + healthCheckWrapper.getComponentsInfo().add(calculateStatusFor); } calculateAggregatedStatus(calculateStatusFor); - } @VisibleForTesting @@ -306,16 +283,14 @@ public class HealthCheckScheduledTask implements Runnable { return componentHCInfoFromBE; } - private HealthCheckInfo getComponentHcFromList(String component, List<HealthCheckInfo> hcList) { + private HealthCheckInfo getComponentHcFromList(String component, List<HealthCheckInfo> hcList) { return hcList.stream().filter(c -> c.getHealthCheckComponent().equals(component)).findFirst().orElse(null); } private void calculateAggregatedStatus(HealthCheckInfo baseComponentHCInfo) { if (!CollectionUtils.isEmpty(baseComponentHCInfo.getComponentsInfo())) { boolean status = healthCheckUtil.getAggregateStatus(baseComponentHCInfo.getComponentsInfo(), getExcludedComponentList()); - baseComponentHCInfo.setHealthCheckStatus(status ? - HealthCheckInfo.HealthCheckStatus.UP : HealthCheckInfo.HealthCheckStatus.DOWN); - + baseComponentHCInfo.setHealthCheckStatus(status ? HealthCheckInfo.HealthCheckStatus.UP : HealthCheckInfo.HealthCheckStatus.DOWN); String componentsDesc = healthCheckUtil.getAggregateDescription(baseComponentHCInfo.getComponentsInfo()); if (!StringUtils.isEmpty(componentsDesc)) { //aggregated description contains all the internal components desc baseComponentHCInfo.setDescription(componentsDesc); @@ -325,8 +300,8 @@ public class HealthCheckScheduledTask implements Runnable { private HealthCheckWrapper getBeDownCheckInfos() { List<HealthCheckInfo> healthCheckInfos = new ArrayList<>(); - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckInfo.HealthCheckStatus.UP, - ExternalConfiguration.getAppVersion(), "OK")); + healthCheckInfos + .add(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckInfo.HealthCheckStatus.UP, ExternalConfiguration.getAppVersion(), "OK")); healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckInfo.HealthCheckStatus.DOWN, null, null)); healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_JANUSGRAPH, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, null)); healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, null)); @@ -343,17 +318,14 @@ public class HealthCheckScheduledTask implements Runnable { private String getOnboardingHealthCheckUrl() { Configuration.OnboardingConfig onboardingConfig = service.getConfig().getOnboarding(); ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(LOG_TARGET_ENTITY_CONFIG) - .targetServiceName(LOG_TARGET_SERVICE_NAME_OB).build(); - + .targetServiceName(LOG_TARGET_SERVICE_NAME_OB).build(); if (StringUtils.isEmpty(ONBOARDING_HC_URL)) { if (onboardingConfig != null) { - ONBOARDING_HC_URL = buildHealthCheckUrl( - onboardingConfig.getProtocolFe(), onboardingConfig.getHostFe(), - onboardingConfig.getPortFe(), onboardingConfig.getHealthCheckUriFe()); - } - else { + ONBOARDING_HC_URL = buildHealthCheckUrl(onboardingConfig.getProtocolFe(), onboardingConfig.getHostFe(), onboardingConfig.getPortFe(), + onboardingConfig.getHealthCheckUriFe()); + } else { log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData, - "Onboarding health check configuration is missing."); + "Onboarding health check configuration is missing."); } } return ONBOARDING_HC_URL; @@ -362,27 +334,23 @@ public class HealthCheckScheduledTask implements Runnable { private String getCatalogFacadeHealthCheckUrl() { Configuration.CatalogFacadeMsConfig catalogFacadeMsConfig = service.getConfig().getCatalogFacadeMs(); ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(LOG_TARGET_ENTITY_CONFIG) - .targetServiceName(LOG_TARGET_SERVICE_NAME_FACADE).build(); - + .targetServiceName(LOG_TARGET_SERVICE_NAME_FACADE).build(); if (StringUtils.isEmpty(CATALOG_FACADE_MS_HC_URL)) { if (catalogFacadeMsConfig != null) { - CATALOG_FACADE_MS_HC_URL = buildHealthCheckUrl( - catalogFacadeMsConfig.getProtocol(), catalogFacadeMsConfig.getHost(), - catalogFacadeMsConfig.getPort(), catalogFacadeMsConfig.getHealthCheckUri()); - } - else { + CATALOG_FACADE_MS_HC_URL = buildHealthCheckUrl(catalogFacadeMsConfig.getProtocol(), catalogFacadeMsConfig.getHost(), + catalogFacadeMsConfig.getPort(), catalogFacadeMsConfig.getHealthCheckUri()); + } else { log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData, - "Catalog Facade MS health check configuration is missing."); + "Catalog Facade MS health check configuration is missing."); } } return CATALOG_FACADE_MS_HC_URL; } - - private List<HealthCheckInfo> convertResponse(String beJsonResponse, ObjectMapper mapper, String baseComponent, StringBuilder description, int beStatus) { - ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(baseComponent) - .targetServiceName(LOG_SERVICE_NAME).build(); - + private List<HealthCheckInfo> convertResponse(String beJsonResponse, ObjectMapper mapper, String baseComponent, StringBuilder description, + int beStatus) { + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder().targetEntity(baseComponent).targetServiceName(LOG_SERVICE_NAME) + .build(); try { Map<String, Object> healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference<Map<String, Object>>() { }); @@ -394,11 +362,9 @@ public class HealthCheckScheduledTask implements Runnable { } } catch (JsonSyntaxException | IOException e) { log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LOG_SERVICE_NAME, errorLogOptionalData, - baseComponent + " Unexpected response body ", e); - description.append(baseComponent) - .append("Unexpected response body. Response code: ") - .append(beStatus); + baseComponent + " Unexpected response body ", e); + description.append(baseComponent).append("Unexpected response body. Response code: ").append(beStatus); } return new ArrayList<>(); } -}
\ No newline at end of file +} diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckService.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckService.java index d5cfaeca7e..f91e1e0a52 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckService.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/HealthCheckService.java @@ -17,52 +17,41 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.impl; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import javax.servlet.ServletContext; +import javax.ws.rs.core.Response; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.fe.config.Configuration; import org.openecomp.sdc.fe.config.ConfigurationManager; -import javax.servlet.ServletContext; -import javax.ws.rs.core.Response; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - - public class HealthCheckService { private static final Logger healthLogger = Logger.getLogger("asdc.fe.healthcheck"); + private final HealthCheckScheduledTask task; /** * This executor will execute the health check task. */ - private ScheduledExecutorService healthCheckExecutor = - Executors.newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "FE-Health-Check-Thread")); - - private final HealthCheckScheduledTask task ; - + private ScheduledExecutorService healthCheckExecutor = Executors + .newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "FE-Health-Check-Thread")); + private HealthStatus lastHealthStatus = new HealthStatus(500, "{}"); + private ServletContext context; public HealthCheckService(ServletContext context) { this.context = context; this.task = new HealthCheckScheduledTask(this); } - public Configuration getConfig(){ - return ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - } - - void setLastHealthStatus(HealthStatus lastHealthStatus) { - this.lastHealthStatus = lastHealthStatus; + public Configuration getConfig() { + return ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration(); } - private HealthStatus lastHealthStatus = new HealthStatus(500, "{}"); - private ServletContext context; - public void start(int interval) { - this.healthCheckExecutor.scheduleAtFixedRate( getTask() , 0, interval, TimeUnit.SECONDS); + this.healthCheckExecutor.scheduleAtFixedRate(getTask(), 0, interval, TimeUnit.SECONDS); } /** @@ -82,6 +71,11 @@ public class HealthCheckService { public HealthStatus getLastHealthStatus() { return lastHealthStatus; } + + void setLastHealthStatus(HealthStatus lastHealthStatus) { + this.lastHealthStatus = lastHealthStatus; + } + public HealthCheckScheduledTask getTask() { return task; } @@ -89,14 +83,6 @@ public class HealthCheckService { //immutable static class HealthStatus { - public void setBody(String body) { - this.body = body; - } - - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - private String body; private int statusCode; @@ -109,11 +95,16 @@ public class HealthCheckService { return statusCode; } + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + public String getBody() { return body; } - } - - + public void setBody(String body) { + this.body = body; + } + } } 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 717c7265ad..ccd5836b2d 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 @@ -17,22 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.impl; import com.google.common.annotations.VisibleForTesting; - -import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Map; +import javax.servlet.http.HttpServletRequest; public class HttpRequestInfo { + private Map<String, String> headers; + private String requestURL; + private InputStream requestData; + private String originServletContext; @VisibleForTesting HttpRequestInfo() { } - public HttpRequestInfo(HttpServletRequest request, Map<String, String> headersMap, String data) { headers = headersMap; requestURL = request.getRequestURI(); @@ -40,11 +41,6 @@ public class HttpRequestInfo { originServletContext = request.getContextPath(); } - private Map<String, String> headers; - private String requestURL; - private InputStream requestData; - private String originServletContext; - public Map<String, String> getHeaders() { return headers; } 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 52c888fc01..f571931237 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 @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.fe.impl; import lombok.AllArgsConstructor; @@ -32,6 +31,7 @@ import lombok.Setter; @Getter @Setter public class ImportMetadata { + private String name; private long size; private String mime; diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/LogHandler.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/LogHandler.java index b97379b399..be2381de0a 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/LogHandler.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/LogHandler.java @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.impl; +import javax.servlet.http.HttpServletRequest; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; import org.slf4j.MDC; -import javax.servlet.http.HttpServletRequest; - public class LogHandler { + public static final String UUID = "uuid"; public static final String TRANSACTION_START_TIME = "transactionStartTime"; @@ -36,37 +35,34 @@ public class LogHandler { Long transactionStartTime = System.currentTimeMillis(); String uuid = LogFieldsMdcHandler.getInstance().getKeyRequestId(); String serviceInstanceID = httpRequest.getHeader(Constants.X_ECOMP_SERVICE_ID_HEADER); - if (uuid != null && uuid.length() > 0) { String userId = httpRequest.getHeader(Constants.USER_ID_HEADER); String remoteAddr = httpRequest.getRemoteAddr(); String localAddr = httpRequest.getLocalAddr(); - - httpRequest.setAttribute(UUID,uuid); - httpRequest.setAttribute(TRANSACTION_START_TIME,transactionStartTime); - + httpRequest.setAttribute(UUID, uuid); + httpRequest.setAttribute(TRANSACTION_START_TIME, transactionStartTime); updateMdc(uuid, serviceInstanceID, userId, remoteAddr, localAddr, null); } } public static void logFeResponse(HttpServletRequest request) { - String uuid = (String)request.getAttribute(UUID); + String uuid = (String) request.getAttribute(UUID); String serviceInstanceID = request.getHeader(Constants.X_ECOMP_SERVICE_ID_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); String remoteAddr = request.getRemoteAddr(); String localAddr = request.getLocalAddr(); String transactionRoundTime = null; - if (uuid != null) { - Long transactionStartTime = (Long)request.getAttribute(TRANSACTION_START_TIME); - if(transactionStartTime != null){ + Long transactionStartTime = (Long) request.getAttribute(TRANSACTION_START_TIME); + if (transactionStartTime != null) { transactionRoundTime = Long.toString(System.currentTimeMillis() - transactionStartTime); } updateMdc(uuid, serviceInstanceID, userId, remoteAddr, localAddr, transactionRoundTime); } } - private static void updateMdc(String uuid, String serviceInstanceID, String userId, String remoteAddr, String localAddr, String transactionElapsedTime) { + private static void updateMdc(String uuid, String serviceInstanceID, String userId, String remoteAddr, String localAddr, + String transactionElapsedTime) { MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, uuid); MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, serviceInstanceID); MDC.put("userId", userId); 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 8a996d5b19..f9f7caa72a 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,6 +27,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public class MdcData { + private String serviceInstanceID; private String userId; private String remoteAddr; 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 13ff206ad8..080ab6809a 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 @@ -17,11 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.impl; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.io.IOException; +import java.security.GeneralSecurityException; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; @@ -35,7 +36,6 @@ import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; - import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.InvalidArgumentException; import org.openecomp.sdc.fe.config.ConfigurationManager; @@ -43,105 +43,81 @@ import org.openecomp.sdc.fe.config.PluginsConfiguration; import org.openecomp.sdc.fe.config.PluginsConfiguration.Plugin; import org.openecomp.sdc.fe.utils.JettySSLUtils; -import java.io.IOException; -import java.security.GeneralSecurityException; - public class PluginStatusBL { private static final Logger log = Logger.getLogger(PluginStatusBL.class.getName()); - private static final String MAX_CONNECTION_POOL = "maxOutgoingConnectionPoolTotal"; - private static final String MAX_ROUTE_POOL = "maxOutgoingPerRoute"; + private static final String MAX_CONNECTION_POOL = "maxOutgoingConnectionPoolTotal"; + private static final String MAX_ROUTE_POOL = "maxOutgoingPerRoute"; private final Gson gson; - private CloseableHttpClient client; private final PluginsConfiguration pluginsConfiguration; + private CloseableHttpClient client; private RequestConfig requestConfig; public PluginStatusBL() { this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration(); this.gson = new GsonBuilder().setPrettyPrinting().create(); - // check if we have secure connections in the plugin list, if not - we won't bother with it - try { - this.client = getPooledClient(this.hasSecuredPlugins()); - } catch (Exception e){ - log.error("Could not initialize the Https client: {}", e.getMessage()); - log.debug("Exception:",e); - } + // check if we have secure connections in the plugin list, if not - we won't bother with it + try { + this.client = getPooledClient(this.hasSecuredPlugins()); + } catch (Exception e) { + log.error("Could not initialize the Https client: {}", e.getMessage()); + log.debug("Exception:", e); + } } public PluginStatusBL(CloseableHttpClient client) { this.pluginsConfiguration = ConfigurationManager.getConfigurationManager().getPluginsConfiguration(); this.client = client; - this.gson = new GsonBuilder().setPrettyPrinting().create(); - } - private boolean hasSecuredPlugins() { - if (this.getPluginsList() != null) { + private boolean hasSecuredPlugins() { + if (this.getPluginsList() != null) { return pluginsConfiguration.getPluginsList().stream() - .anyMatch(plugin -> plugin.getPluginDiscoveryUrl().toLowerCase().startsWith("https")); - } - return false; - - } - - private CloseableHttpClient getPooledClient(boolean isSecured) throws GeneralSecurityException, IOException { - final PoolingHttpClientConnectionManager poolingConnManager; - if (!isSecured) { - poolingConnManager - = new PoolingHttpClientConnectionManager(); - } else { - SSLConnectionSocketFactory s = new SSLConnectionSocketFactory( - JettySSLUtils.getSslContext(), - new NoopHostnameVerifier()); + .anyMatch(plugin -> plugin.getPluginDiscoveryUrl().toLowerCase().startsWith("https")); + } + return false; + } - Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() - .register("http", new PlainConnectionSocketFactory()) - .register("https", s) - .build(); - poolingConnManager - = new PoolingHttpClientConnectionManager(registry); - } - int maxTotal = System.getProperties().containsKey(MAX_CONNECTION_POOL) ? Integer.parseInt(System.getProperty(MAX_CONNECTION_POOL)) : 5; - int routeMax = System.getProperties().containsKey(MAX_ROUTE_POOL) ? Integer.parseInt(System.getProperty(MAX_ROUTE_POOL)) : 20; - poolingConnManager.setMaxTotal(maxTotal); - poolingConnManager.setDefaultMaxPerRoute(routeMax); - return HttpClients.custom().setConnectionManager(poolingConnManager).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); - } + private CloseableHttpClient getPooledClient(boolean isSecured) throws GeneralSecurityException, IOException { + final PoolingHttpClientConnectionManager poolingConnManager; + if (!isSecured) { + poolingConnManager = new PoolingHttpClientConnectionManager(); + } else { + SSLConnectionSocketFactory s = new SSLConnectionSocketFactory(JettySSLUtils.getSslContext(), new NoopHostnameVerifier()); + Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() + .register("http", new PlainConnectionSocketFactory()).register("https", s).build(); + poolingConnManager = new PoolingHttpClientConnectionManager(registry); + } + int maxTotal = System.getProperties().containsKey(MAX_CONNECTION_POOL) ? Integer.parseInt(System.getProperty(MAX_CONNECTION_POOL)) : 5; + int routeMax = System.getProperties().containsKey(MAX_ROUTE_POOL) ? Integer.parseInt(System.getProperty(MAX_ROUTE_POOL)) : 20; + poolingConnManager.setMaxTotal(maxTotal); + poolingConnManager.setDefaultMaxPerRoute(routeMax); + return HttpClients.custom().setConnectionManager(poolingConnManager).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + } public String getPluginsList() { 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); - return gson.toJson(pluginsConfiguration.getPluginsList()); } } 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); - + 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)); } @@ -153,12 +129,11 @@ public class PluginStatusBL { 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); - if (this.client == null) { - log.debug("The plugin {} will not run because https is not configured on the FE server",plugin.getPluginId()); - return false; - } + if (this.client == null) { + log.debug("The plugin {} will not run because https is not configured on the FE server", plugin.getPluginId()); + return false; + } try (CloseableHttpResponse response = this.client.execute(head)) { result = response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; log.debug("The plugin {} is {} with result {}", plugin.getPluginId(), (result ? "online" : "offline"), result); @@ -166,8 +141,6 @@ public class PluginStatusBL { log.debug("The plugin {} is offline", plugin.getPluginId()); log.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 70cb27e93b..877d637a3e 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 @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.listen; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.listener.AppContextListener; @@ -29,61 +32,40 @@ import org.openecomp.sdc.fe.impl.HealthCheckService; import org.openecomp.sdc.fe.impl.PluginStatusBL; import org.openecomp.sdc.fe.monitoring.FeMonitoringService; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - public class FEAppContextListener extends AppContextListener implements ServletContextListener { - private static Logger log = Logger.getLogger(FEAppContextListener.class.getName()); private static final int HEALTH_CHECHK_INTERVALE = 5; private static final int PROBE_INTERVALE = 15; + private static Logger log = Logger.getLogger(FEAppContextListener.class.getName()); public void contextInitialized(ServletContextEvent context) { - super.contextInitialized(context); - - ConfigurationManager configurationManager = new ConfigurationManager( - ExternalConfiguration.getConfigurationSource()); - log.debug("loading configuration from configDir:{} appName:{}", ExternalConfiguration.getConfigDir(), - ExternalConfiguration.getAppName()); + 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); - // 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); - // Monitoring service FeMonitoringService fms = new FeMonitoringService(context.getServletContext()); fms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(PROBE_INTERVALE)); - if (configurationManager.getConfiguration() == null) { log.debug("ERROR: configuration was not properly loaded"); return; } - - ExecutorService executorPool = Executors - .newFixedThreadPool(configurationManager.getConfiguration().getThreadpoolSize()); + ExecutorService executorPool = Executors.newFixedThreadPool(configurationManager.getConfiguration().getThreadpoolSize()); context.getServletContext().setAttribute(Constants.THREAD_EXECUTOR_ATTR, executorPool); - log.debug("After executing {}", this.getClass()); } public void contextDestroyed(ServletContextEvent context) { - - ExecutorService executorPool = (ExecutorService) context.getServletContext() - .getAttribute(Constants.THREAD_EXECUTOR_ATTR); + 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 e7a09b4b6a..4f57070f24 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 @@ -17,32 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.listen; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; - import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; @Provider public class MyObjectMapperProvider implements ContextResolver<ObjectMapper> { + private final ObjectMapper defaultObjectMapper; MyObjectMapperProvider() { defaultObjectMapper = createDefaultMapper(); } - @Override - public ObjectMapper getContext(Class<?> type) { - return defaultObjectMapper; - } - private static ObjectMapper createDefaultMapper() { final ObjectMapper result = new ObjectMapper(); result.configure(SerializationFeature.INDENT_OUTPUT, true); return result; } + @Override + public ObjectMapper getContext(Class<?> type) { + return defaultObjectMapper; + } } 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 c2ea7250d2..7c75822164 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 @@ -17,16 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.servlets; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.rest.api.RestConfigurationInfo; -import org.openecomp.sdc.common.servlets.BasicServlet; -import org.openecomp.sdc.fe.config.Configuration; -import org.openecomp.sdc.fe.config.ConfigurationManager; - import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; @@ -35,6 +27,12 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.rest.api.RestConfigurationInfo; +import org.openecomp.sdc.common.servlets.BasicServlet; +import org.openecomp.sdc.fe.config.Configuration; +import org.openecomp.sdc.fe.config.ConfigurationManager; /** * Root resource (exposed at "/" path) @@ -42,46 +40,32 @@ import javax.ws.rs.core.MediaType; @Path("/configmgr") public class ConfigMgrServlet extends BasicServlet { - private static Logger log = Logger.getLogger(ConfigMgrServlet.class.getName()); + private static Logger log = Logger.getLogger(ConfigMgrServlet.class.getName()); @GET @Path("/get") @Produces(MediaType.APPLICATION_JSON) public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { - String result = null; - 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")) { - 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); - } } 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); - result = gson.toJson(configuration); - } - } 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 f5d1736074..bdc263f256 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 @@ -17,19 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.servlets; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.exception.NotFoundException; -import org.openecomp.sdc.fe.config.ConfigurationManager; -import org.openecomp.sdc.fe.config.FeEcompErrorManager; -import org.openecomp.sdc.fe.config.WorkspaceConfiguration; -import org.openecomp.sdc.fe.impl.PluginStatusBL; -import org.owasp.esapi.ESAPI; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; @@ -40,6 +29,15 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.NotFoundException; +import org.openecomp.sdc.fe.config.ConfigurationManager; +import org.openecomp.sdc.fe.config.FeEcompErrorManager; +import org.openecomp.sdc.fe.config.WorkspaceConfiguration; +import org.openecomp.sdc.fe.impl.PluginStatusBL; +import org.owasp.esapi.ESAPI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Root resource (exposed at "/" path) @@ -47,23 +45,18 @@ import javax.ws.rs.core.Response.Status; @Path("/config") public class ConfigServlet extends LoggingServlet { - private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName()); public static final String UNEXPECTED_FE_RESPONSE_LOGGING_ERROR = "Unexpected FE response logging error :"; public static final String ERROR_FE_RESPONSE = "FE Response"; + private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName()); @GET @Path("/ui/workspace") @Produces(MediaType.APPLICATION_JSON) public Response getUIWorkspaceConfiguration(@Context final HttpServletRequest request) { - try { logFeRequest(request); - ServletContext context = request.getSession().getServletContext(); - - ConfigurationManager configurationManager = (ConfigurationManager) context - .getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); - + ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); WorkspaceConfiguration configuration = configurationManager.getWorkspaceConfiguration(); if (configuration == null) { throw new NotFoundException(WorkspaceConfiguration.class.getSimpleName()); @@ -72,67 +65,50 @@ public class ConfigServlet extends LoggingServlet { String result = gson.toJson(configuration); Response response = Response.status(Status.OK).entity(result).build(); logFeResponse(request, response); - return response; } catch (Exception e) { FeEcompErrorManager.getInstance().logFeHttpLoggingError(ERROR_FE_RESPONSE); log.error(UNEXPECTED_FE_RESPONSE_LOGGING_ERROR, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("{}").build(); } - } - @GET @Path("/ui/plugins") @Produces(MediaType.APPLICATION_JSON) public Response getPluginsConfiguration(@Context final HttpServletRequest request) { - try { logFeRequest(request); - ServletContext context = request.getSession().getServletContext(); - PluginStatusBL pluginStatusBL = (PluginStatusBL) context.getAttribute(Constants.PLUGIN_BL_COMPONENT); - String result = pluginStatusBL.getPluginsList(); - Response response = Response.status(Status.OK).entity(result).build(); - logFeResponse(request, response); - return response; } catch (Exception e) { - FeEcompErrorManager.getInstance().logFeHttpLoggingError( ERROR_FE_RESPONSE); + FeEcompErrorManager.getInstance().logFeHttpLoggingError(ERROR_FE_RESPONSE); log.error(UNEXPECTED_FE_RESPONSE_LOGGING_ERROR, e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("{}").build(); } - } @GET @Path("/ui/plugins/{pluginId}/online") @Produces(MediaType.APPLICATION_JSON) public Response getPluginOnlineState(@PathParam("pluginId") String pluginId, @Context final HttpServletRequest request) { - try { logFeRequest(request); pluginId = ESAPI.encoder().encodeForHTML(pluginId); ServletContext context = request.getSession().getServletContext(); - PluginStatusBL pluginStatusBL = (PluginStatusBL) context.getAttribute(Constants.PLUGIN_BL_COMPONENT); - String result = pluginStatusBL.getPluginAvailability(pluginId); - if (result == null) { log.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(); + return Response.status(Status.NOT_FOUND).entity("Plugin with pluginId:\"" + pluginId + "\" was not found in the configuration") + .build(); } - Response response = Response.status(Status.OK).entity(result).build(); - logFeResponse(request, response); - return response; } catch (Exception e) { FeEcompErrorManager.getInstance().logFeHttpLoggingError(ERROR_FE_RESPONSE); 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 5243366e85..b23bb8b45f 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 @@ -17,25 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.servlets; -import com.jcabi.aspects.Loggable; -import org.openecomp.sdc.common.servlets.BasicServlet; -import org.openecomp.sdc.fe.impl.HealthCheckService; +import static org.openecomp.sdc.common.api.Constants.HEALTH_CHECK_SERVICE_ATTR; +import com.jcabi.aspects.Loggable; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; - -import static org.openecomp.sdc.common.api.Constants.HEALTH_CHECK_SERVICE_ATTR; +import org.openecomp.sdc.common.servlets.BasicServlet; +import org.openecomp.sdc.fe.impl.HealthCheckService; @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(); 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 5362b526be..0ef435311f 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. @@ -17,11 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.servlets; +import static org.apache.commons.lang3.StringUtils.isEmpty; + import com.google.common.annotations.VisibleForTesting; +import java.net.MalformedURLException; +import java.net.URL; import java.util.Base64; +import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.client.api.Request; @@ -40,286 +44,270 @@ import org.openecomp.sdc.fe.config.PluginsConfiguration.Plugin; import org.openecomp.sdc.fe.impl.LogHandler; import org.openecomp.sdc.fe.utils.BeProtocol; -import javax.servlet.http.HttpServletRequest; -import java.net.MalformedURLException; -import java.net.URL; - -import static org.apache.commons.lang3.StringUtils.isEmpty; - - public class FeProxyServlet extends SSLProxyServlet { - private static final long serialVersionUID = 1L; - private static final String URL = "%s://%s%s%s"; - private static final String MS_URL = "%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"; - public static final String UUID = "uuid"; - public static final String TRANSACTION_START_TIME = "transactionStartTime"; - private static Logger log = Logger.getLogger(FeProxyServlet.class.getName()); - - private static String msUrl; - private static final String FACADE_PATH_IDENTIFIER = "uicache"; - private static final String CATALOG_REQUEST_IDENTIFIER = "/v1/catalog"; - private static final String ARCHIVE_PATH_IDENTIFIER = String.format("%s/archive/", CATALOG_REQUEST_IDENTIFIER); - private static final String HOME_REQUEST_IDENTIFIER = "/v1/followed"; - @Override - protected String rewriteTarget(HttpServletRequest request) { - String originalUrl=""; - String redirectedUrl = ""; - - try { - logFeRequest(request); - originalUrl = request.getRequestURL().toString(); - Configuration config = getConfiguration(request); - if (config == null) { - log.error("failed to retrieve configuration."); - } - if (isMsRequest(request.getRequestURL().toString())) { - redirectedUrl = redirectMsRequestToMservice(request, config); - } else { - redirectedUrl = getModifiedUrl(config, getPluginConfiguration(request), request.getRequestURI(), getQueryString(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) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"FeProxyServlet rewriteTarget", "sdc-FE", "Unexpected FE request processing error: ", e); - } - if (log.isDebugEnabled()) { - log.debug("FeProxyServlet Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); - } + public static final String UUID = "uuid"; + public static final String TRANSACTION_START_TIME = "transactionStartTime"; + private static final long serialVersionUID = 1L; + private static final String URL = "%s://%s%s%s"; + private static final String MS_URL = "%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 String FACADE_PATH_IDENTIFIER = "uicache"; + private static final String CATALOG_REQUEST_IDENTIFIER = "/v1/catalog"; + private static final String ARCHIVE_PATH_IDENTIFIER = String.format("%s/archive/", CATALOG_REQUEST_IDENTIFIER); + private static final String HOME_REQUEST_IDENTIFIER = "/v1/followed"; + private static Logger log = Logger.getLogger(FeProxyServlet.class.getName()); + private static String msUrl; - return redirectedUrl; - } + @Override + protected String rewriteTarget(HttpServletRequest request) { + String originalUrl = ""; + String redirectedUrl = ""; + try { + logFeRequest(request); + originalUrl = request.getRequestURL().toString(); + Configuration config = getConfiguration(request); + if (config == null) { + log.error("failed to retrieve configuration."); + } + if (isMsRequest(request.getRequestURL().toString())) { + redirectedUrl = redirectMsRequestToMservice(request, config); + } else { + redirectedUrl = getModifiedUrl(config, getPluginConfiguration(request), request.getRequestURI(), getQueryString(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) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "FeProxyServlet rewriteTarget", "sdc-FE", "Unexpected FE request processing error: ", e); + } + if (log.isDebugEnabled()) { + log.debug("FeProxyServlet Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); + } + return redirectedUrl; + } - @Override - protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest) - { - Configuration config = getConfiguration(clientRequest); - if (config == null) { - log.error("Failed to retrieve configuration. Adding proxy header failed."); - return; - } - BasicAuthConfig basicAuth = config.getBasicAuth(); - if (basicAuth.isEnabled()) { - proxyRequest.header(HttpHeader.AUTHORIZATION, - "Basic " + Base64.getEncoder().encodeToString((basicAuth.getUserName() + ":" + basicAuth.getUserPass()).getBytes())); - } - super.addProxyHeaders(clientRequest, proxyRequest); - } + @Override + protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest) { + Configuration config = getConfiguration(clientRequest); + if (config == null) { + log.error("Failed to retrieve configuration. Adding proxy header failed."); + return; + } + BasicAuthConfig basicAuth = config.getBasicAuth(); + if (basicAuth.isEnabled()) { + proxyRequest.header(HttpHeader.AUTHORIZATION, + "Basic " + Base64.getEncoder().encodeToString((basicAuth.getUserName() + ":" + basicAuth.getUserPass()).getBytes())); + } + super.addProxyHeaders(clientRequest, proxyRequest); + } - private void logFeRequest(HttpServletRequest httpRequest){ - LogHandler.logFeRequest(httpRequest); - inHttpRequest(httpRequest); - } + private void logFeRequest(HttpServletRequest httpRequest) { + LogHandler.logFeRequest(httpRequest); + inHttpRequest(httpRequest); + } - private void logFeResponse(HttpServletRequest request, Response proxyResponse){ - LogHandler.logFeResponse(request); - outHttpResponse(proxyResponse); - } + private void logFeResponse(HttpServletRequest request, Response proxyResponse) { + LogHandler.logFeResponse(request); + outHttpResponse(proxyResponse); + } - // 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 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()); - } + // Extracted for purpose of clear method name, for logback %M parameter + private void outHttpResponse(Response proxyResponse) { + log.info("SC=\"{}\"", proxyResponse.getStatus()); + } - private String getModifiedUrl(Configuration config, PluginsConfiguration pluginConf, String uri, String queryString) throws MalformedURLException{ - 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 protocol; - String host; - String port; - String path = ""; - 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)){ - uri = uri.replace(SDC1_FE_PROXY +WORKFLOW_CONTEXT,WORKFLOW_CONTEXT); - String workflowPluginURL = pluginConf.getPluginsList() - .stream() - .filter(plugin -> plugin.getPluginId().equalsIgnoreCase(PLUGIN_ID_WORKFLOW)) - .map(Plugin::getPluginDiscoveryUrl) - .findFirst().orElse(null); + private String getModifiedUrl(Configuration config, PluginsConfiguration pluginConf, String uri, String queryString) + throws MalformedURLException { + 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 protocol; + String host; + String port; + String path = ""; + 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)) { + uri = uri.replace(SDC1_FE_PROXY + WORKFLOW_CONTEXT, WORKFLOW_CONTEXT); + String workflowPluginURL = pluginConf.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(); + path = workflowURL.getPath(); + port = String.valueOf(workflowURL.getPort()); + } 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(); + } + } + final String authority = getAuthority(host, port); + String modifiedUrl = String.format(URL, protocol, authority, path, uri); + if (StringUtils.isNotEmpty(queryString)) { + modifiedUrl += "?" + queryString; + } + return modifiedUrl; + } - java.net.URL workflowURL = new URL(workflowPluginURL); - protocol = workflowURL.getProtocol(); - host = workflowURL.getHost(); - path = workflowURL.getPath(); - port = String.valueOf(workflowURL.getPort()); - } - 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(); - } - } + @VisibleForTesting + String redirectMsRequestToMservice(HttpServletRequest request, Configuration config) throws MalformedURLException { + boolean isMsToggledOn = isMsToggleOn(config); + String redirectValue; + if (isMsToggledOn) { + redirectValue = handleMsToggleOnRedirect(request, config); + } else { + redirectValue = handleMsToggleOffRedirect(request, config); + } + return redirectValue; + } - final String authority = getAuthority(host, port); - String modifiedUrl = String.format(URL, protocol, authority, path, uri); - if (StringUtils.isNotEmpty(queryString)) { - modifiedUrl += "?" + queryString; - } - - return modifiedUrl; - } + private PluginsConfiguration getPluginConfiguration(HttpServletRequest request) { + return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getPluginsConfiguration(); + } - @VisibleForTesting - String redirectMsRequestToMservice(HttpServletRequest request, Configuration config) throws MalformedURLException { + private boolean isMsToggleOn(Configuration config) { + boolean toggleOn = true; + final CatalogFacadeMsConfig catalogFacadeMs = config.getCatalogFacadeMs(); + if (catalogFacadeMs == null) { + toggleOn = false; + ; + } else if (isEmpty(catalogFacadeMs.getHealthCheckUri())) { + toggleOn = false; + } else if (isEmpty(catalogFacadeMs.getHost())) { + toggleOn = false; + } else if (isEmpty(catalogFacadeMs.getPath())) { + toggleOn = false; + } else if (isEmpty(catalogFacadeMs.getProtocol())) { + toggleOn = false; + } else if (catalogFacadeMs.getPort() == null) { + toggleOn = false; + } + return toggleOn; + } - boolean isMsToggledOn = isMsToggleOn(config); - String redirectValue; - if (isMsToggledOn) { - redirectValue = handleMsToggleOnRedirect(request, config); - } else { - redirectValue = handleMsToggleOffRedirect(request, config); - } - return redirectValue; - } -private PluginsConfiguration getPluginConfiguration(HttpServletRequest request) { - return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getPluginsConfiguration(); - } - private boolean isMsToggleOn(Configuration config) { - boolean toggleOn = true; - final CatalogFacadeMsConfig catalogFacadeMs = config.getCatalogFacadeMs(); - if (catalogFacadeMs == null) { - toggleOn = false; - ; - } else if (isEmpty(catalogFacadeMs.getHealthCheckUri())) { - toggleOn = false; - } else if (isEmpty(catalogFacadeMs.getHost())) { - toggleOn = false; - } else if (isEmpty(catalogFacadeMs.getPath())) { - toggleOn = false; - } else if (isEmpty(catalogFacadeMs.getProtocol())) { - toggleOn = false; - } else if (catalogFacadeMs.getPort() == null) { - toggleOn = false; - } - return toggleOn; - } - private String handleMsToggleOffRedirect(HttpServletRequest request, Configuration config) throws MalformedURLException { - String redirectValue; - String currentURI = request.getRequestURI(); - if (isEmpty(request.getQueryString())) { - // Catalog - if (currentURI.endsWith(CATALOG_REQUEST_IDENTIFIER)) { - String facadeSuffix = String.format("%s%s", FACADE_PATH_IDENTIFIER, CATALOG_REQUEST_IDENTIFIER); - String nonFacadeUrl = currentURI.replace(facadeSuffix, "rest/v1/screen"); - redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, "excludeTypes=VFCMT&excludeTypes=Configuration"); - } - // Home - else if (currentURI.endsWith(HOME_REQUEST_IDENTIFIER)){ - redirectValue = getModifiedUrl(config, getPluginConfiguration(request), currentURI, getQueryString(request)); - } - // Archive - else if (currentURI.endsWith(ARCHIVE_PATH_IDENTIFIER)) { - redirectValue = getModifiedUrl(config, getPluginConfiguration(request), currentURI, getQueryString(request)); - } else { - String message = String.format("facade is toggled off, Could not rediret url %s", currentURI); - log.error(message); - throw new NotImplementedException(message); - } - } else { - // Left Pallet - if (currentURI.contains("/latestversion/notabstract/metadata")) { - String nonFacadeUrl = currentURI.replace(FACADE_PATH_IDENTIFIER, "rest"); - redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, getQueryString(request)); - } - // Catalog with Query Params - else if (currentURI.endsWith(CATALOG_REQUEST_IDENTIFIER)) { - String facadeSuffix = String.format("%s%s", FACADE_PATH_IDENTIFIER, CATALOG_REQUEST_IDENTIFIER); - String nonFacadeUrl = currentURI.replace(facadeSuffix, "rest/v1/screen"); - redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, "excludeTypes=VFCMT&excludeTypes=Configuration"); - } else { - String message = String.format("facade is toggled off, Could not rediret url %s with query params %s", - currentURI, getQueryString(request)); - log.error(message); - throw new NotImplementedException(message); - } - } + private String handleMsToggleOffRedirect(HttpServletRequest request, Configuration config) throws MalformedURLException { + String redirectValue; + String currentURI = request.getRequestURI(); + if (isEmpty(request.getQueryString())) { + // Catalog + if (currentURI.endsWith(CATALOG_REQUEST_IDENTIFIER)) { + String facadeSuffix = String.format("%s%s", FACADE_PATH_IDENTIFIER, CATALOG_REQUEST_IDENTIFIER); + String nonFacadeUrl = currentURI.replace(facadeSuffix, "rest/v1/screen"); + redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, + "excludeTypes=VFCMT&excludeTypes=Configuration"); + } + // Home + else if (currentURI.endsWith(HOME_REQUEST_IDENTIFIER)) { + redirectValue = getModifiedUrl(config, getPluginConfiguration(request), currentURI, getQueryString(request)); + } + // Archive + else if (currentURI.endsWith(ARCHIVE_PATH_IDENTIFIER)) { + redirectValue = getModifiedUrl(config, getPluginConfiguration(request), currentURI, getQueryString(request)); + } else { + String message = String.format("facade is toggled off, Could not rediret url %s", currentURI); + log.error(message); + throw new NotImplementedException(message); + } + } else { + // Left Pallet + if (currentURI.contains("/latestversion/notabstract/metadata")) { + String nonFacadeUrl = currentURI.replace(FACADE_PATH_IDENTIFIER, "rest"); + redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, getQueryString(request)); + } + // Catalog with Query Params + else if (currentURI.endsWith(CATALOG_REQUEST_IDENTIFIER)) { + String facadeSuffix = String.format("%s%s", FACADE_PATH_IDENTIFIER, CATALOG_REQUEST_IDENTIFIER); + String nonFacadeUrl = currentURI.replace(facadeSuffix, "rest/v1/screen"); + redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, + "excludeTypes=VFCMT&excludeTypes=Configuration"); + } else { + String message = String + .format("facade is toggled off, Could not rediret url %s with query params %s", currentURI, getQueryString(request)); + log.error(message); + throw new NotImplementedException(message); + } + } + return redirectValue; + } - return redirectValue; - } + private String handleMsToggleOnRedirect(HttpServletRequest request, Configuration config) { + String currentUrl = request.getRequestURL().toString(); + if (StringUtils.isEmpty(msUrl)) { + // do that only once + msUrl = String.format(MS_URL, config.getCatalogFacadeMs().getProtocol(), config.getCatalogFacadeMs().getHost(), + config.getCatalogFacadeMs().getPort()); + } + StringBuilder url; + String queryString; + String msPath = config.getCatalogFacadeMs().getPath(); + if (currentUrl.endsWith(ARCHIVE_PATH_IDENTIFIER)) { + url = new StringBuilder(msUrl + msPath + CATALOG_REQUEST_IDENTIFIER); + queryString = "arc=true"; + } else { + url = new StringBuilder(msUrl + currentUrl.substring(currentUrl.indexOf(msPath))); + queryString = request.getQueryString(); + } + if (queryString != null) { + url.append("?").append(queryString); + } + if (log.isDebugEnabled()) { + log.debug("Redirect catalog request to {}", url.toString()); + } + return url.toString(); + } - private String handleMsToggleOnRedirect(HttpServletRequest request, Configuration config) { - String currentUrl = request.getRequestURL() - .toString(); - if (StringUtils.isEmpty(msUrl)) { - // do that only once - msUrl = String.format(MS_URL, config.getCatalogFacadeMs() - .getProtocol(), - config.getCatalogFacadeMs().getHost(), - config.getCatalogFacadeMs().getPort()); - } - StringBuilder url; - String queryString; - String msPath = config.getCatalogFacadeMs().getPath(); - if (currentUrl.endsWith(ARCHIVE_PATH_IDENTIFIER)) { - url = new StringBuilder(msUrl + msPath + CATALOG_REQUEST_IDENTIFIER); - queryString = "arc=true"; - } else { - url = new StringBuilder(msUrl + currentUrl.substring(currentUrl.indexOf(msPath))); - queryString = request.getQueryString(); - } - if (queryString != null) { - url.append("?").append(queryString); - } - if (log.isDebugEnabled()) { - log.debug("Redirect catalog request to {}", url.toString()); - } - return url.toString(); - } + @VisibleForTesting + boolean isMsRequest(String currentUrl) { + return currentUrl.contains(FACADE_PATH_IDENTIFIER) || currentUrl.endsWith(ARCHIVE_PATH_IDENTIFIER); + } - @VisibleForTesting - boolean isMsRequest(String currentUrl) { - return currentUrl.contains(FACADE_PATH_IDENTIFIER) || currentUrl.endsWith(ARCHIVE_PATH_IDENTIFIER); - } - private Configuration getConfiguration(HttpServletRequest request) { - return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration(); - } + 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){ - final String queryString = request.getQueryString(); - return StringUtils.isEmpty(queryString) ? StringUtils.EMPTY : queryString; - } + 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) { + final String queryString = request.getQueryString(); + return StringUtils.isEmpty(queryString) ? StringUtils.EMPTY : queryString; + } } 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 4bcbaa531b..8e0702ae35 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 @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.servlets; -import org.openecomp.sdc.common.servlets.BasicServlet; -import org.openecomp.sdc.fe.impl.LogHandler; - import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; +import org.openecomp.sdc.common.servlets.BasicServlet; +import org.openecomp.sdc.fe.impl.LogHandler; public abstract class LoggingServlet extends BasicServlet { @@ -33,16 +31,18 @@ public abstract class LoggingServlet extends BasicServlet { /** * log incoming requests + * * @param httpRequest the http request */ - void logFeRequest(HttpServletRequest httpRequest){ + void logFeRequest(HttpServletRequest httpRequest) { LogHandler.logFeRequest(httpRequest); inHttpRequest(httpRequest); } /** * log response - * @param request orig request + * + * @param request orig request * @param response returned response */ void logFeResponse(HttpServletRequest request, Response response) { @@ -52,13 +52,14 @@ 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); 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 18c6a645c4..64b8cb1e69 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 @@ -17,9 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.servlets; +import java.io.IOException; +import java.util.Enumeration; +import java.util.List; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.sdc.security.AuthenticationCookie; @@ -31,32 +42,51 @@ import org.openecomp.sdc.fe.config.Configuration; import org.openecomp.sdc.fe.config.ConfigurationManager; import org.openecomp.sdc.fe.config.FeEcompErrorManager; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.core.Context; -import java.io.IOException; -import java.util.Enumeration; -import java.util.List; - /** * Root resource (exposed at "/" path) */ @Path("/") public class PortalServlet extends HttpServlet { - private static Logger log = Logger.getLogger(PortalServlet.class.getName()); - private static final long serialVersionUID = 1L; - public static final String MISSING_HEADERS_MSG = "Missing Headers In Request"; + private static final long serialVersionUID = 1L; private static final String AUTHORIZATION_ERROR_MSG = "Autherization error"; private static final String NEW_LINE = System.getProperty("line.separator"); + private static Logger log = Logger.getLogger(PortalServlet.class.getName()); + + private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException { + 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; + } + private static String getValueFromCookie(HttpServletRequest request, String cookieName) { + String value = ""; + Cookie[] cookies = request.getCookies(); + Cookie valueFromCookie = null; + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookie.getName().endsWith(cookieName)) { + valueFromCookie = cookie; + } + } + } + if (valueFromCookie != null) { + value = valueFromCookie.getValue(); + } + return value; + } /** * Entry point from ECOMP portal @@ -74,24 +104,20 @@ public class PortalServlet extends HttpServlet { } /** - * Building new HTTP request and setting headers for the request The request - * will dispatch to index.html + * 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 { - + private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) + throws ServletException, IOException { response.setContentType("text/html"); - // Create new request object to dispatch MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request); - // Get configuration object (reads data from configuration.yaml) Configuration configuration = getConfiguration(request); - // Check if we got header from webseal String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER); if (null == userId) { @@ -108,49 +134,43 @@ public class PortalServlet extends HttpServlet { log.error("Error during adding request header", e); } } - // 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); } - // 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); } - // Print headers from original request for debug purposes printHeaders(request); - // 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)); - getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME ); - getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME); + getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME); + getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME); + //To be fixed - //To be fixed - //addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie); + //addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie); RequestDispatcher rd = request.getRequestDispatcher("index.html"); rd.forward(mutableRequest, response); } else { @@ -158,37 +178,32 @@ public class PortalServlet extends HttpServlet { } } - boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException { - boolean isBuildCookieCompleted = true; - Cookie authCookie = null; - Configuration.CookieConfig confCookie = - ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie(); - - //create authentication and send it to encryption - - String encryptedCookie = ""; - try { + boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException { + boolean isBuildCookieCompleted = true; + Cookie authCookie = null; + Configuration.CookieConfig confCookie = ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie(); + //create authentication and send it to encryption + String encryptedCookie = ""; + try { AuthenticationCookie authenticationCookie = new AuthenticationCookie(userId, firstName, lastName); - String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie); - encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey()); - } catch (Exception e) { - isBuildCookieCompleted=false; - log.error(" Cookie Encryption failed ", e); - } - - authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie); - authCookie.setPath(confCookie.getPath()); - authCookie.setDomain(confCookie.getDomain()); - authCookie.setHttpOnly(true); - - // add generated cookie to response - if (isBuildCookieCompleted) { - response.addCookie(authCookie); - return true; - } - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG); - return false; - } + String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie); + encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey()); + } catch (Exception e) { + isBuildCookieCompleted = false; + log.error(" Cookie Encryption failed ", e); + } + authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie); + authCookie.setPath(confCookie.getPath()); + authCookie.setDomain(confCookie.getDomain()); + authCookie.setHttpOnly(true); + // add generated cookie to response + if (isBuildCookieCompleted) { + response.addCookie(authCookie); + return true; + } + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG); + return false; + } /** * Print all request headers to the log @@ -196,7 +211,6 @@ public class PortalServlet extends HttpServlet { * @param request */ private void printHeaders(HttpServletRequest request) { - if (log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(); String sessionId = ""; @@ -206,11 +220,9 @@ public class PortalServlet extends HttpServlet { sessionId = id; } } - builder.append("Receiving request with headers:" + NEW_LINE); log.debug("{}", request.getHeaderNames()); - @SuppressWarnings("unchecked") - Enumeration<String> headerNames = request.getHeaderNames(); + @SuppressWarnings("unchecked") Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); @@ -218,15 +230,13 @@ public class PortalServlet extends HttpServlet { builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE); } } - log.debug(builder.toString()); } - } /** - * Add cookies (that where set in the new request headers) in the response - * Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP headers. + * Add cookies (that where set in the new request headers) in the response Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP + * headers. * * @param response * @param request @@ -245,15 +255,13 @@ public class PortalServlet extends HttpServlet { } /** - * Get mandatory headers (identificationHeaderFields) String array, and - * checks that each header exists in the new 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); - boolean allHeadersExist = true; for (int i = 0; i < mandatoryHeaders.length; i++) { String headerValue = request.getHeader(mandatoryHeaders[i]); @@ -266,8 +274,7 @@ public class PortalServlet extends HttpServlet { } /** - * Get mandatory headers (identificationHeaderFields) from - * configuration.yaml file and return String[] + * Get mandatory headers (identificationHeaderFields) from configuration.yaml file and return String[] * * @param request * @return String[] @@ -283,8 +290,7 @@ public class PortalServlet extends HttpServlet { } /** - * Get optional headers (optionalHeaderFields) from configuration.yaml file - * and return String[] + * Get optional headers (optionalHeaderFields) from configuration.yaml file and return String[] * * @param request * @return String[] @@ -306,11 +312,13 @@ public class PortalServlet extends HttpServlet { * @return Configuration */ private Configuration getConfiguration(HttpServletRequest request) { - ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR); + 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) { + 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)); @@ -321,38 +329,4 @@ public class PortalServlet extends HttpServlet { } return newHeaderIsSet; } - - private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException { - 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; - } - - private static String getValueFromCookie(HttpServletRequest request, String cookieName) { - String value = ""; - Cookie[] cookies = request.getCookies(); - Cookie valueFromCookie = null; - if (cookies != null) - for (Cookie cookie : cookies) { - if (cookie.getName().endsWith(cookieName)) { - valueFromCookie = cookie; - } - } - if (valueFromCookie != null) { - value = valueFromCookie.getValue(); - } - - return value; - } } 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 5f5bcd62c2..e74893f714 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. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.servlets; +import javax.servlet.ServletException; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.proxy.ProxyServlet; import org.eclipse.jetty.util.ssl.SslContextFactory; @@ -30,8 +30,6 @@ import org.openecomp.sdc.fe.utils.BeProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; - public abstract class SSLProxyServlet extends ProxyServlet { private static final long serialVersionUID = 1L; @@ -40,27 +38,23 @@ public abstract class SSLProxyServlet extends ProxyServlet { @Override protected HttpClient createHttpClient() throws ServletException { - Configuration config = ((ConfigurationManager) getServletConfig().getServletContext() - .getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration(); + 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); - return client; } 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); - // Configure HttpClient, for example: httpClient.setFollowRedirects(false); - // Start HttpClient try { httpClient.start(); @@ -68,7 +62,6 @@ public abstract class SSLProxyServlet extends ProxyServlet { log.error("Exception thrown while starting httpClient", 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 9257bd40fe..59d5606fc8 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 @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.utils; public enum BeProtocol { HTTP("http"), SSL("ssl"); private String protocolName; - public String getProtocolName() { - return protocolName; - } - BeProtocol(String protocolName) { this.protocolName = protocolName; } + + public String getProtocolName() { + return protocolName; + } }; diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/JettySSLUtils.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/JettySSLUtils.java index 51fa1d1bee..a9badde06b 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/JettySSLUtils.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/utils/JettySSLUtils.java @@ -17,65 +17,55 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.utils; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.ssl.SSLContexts; - -import javax.net.ssl.SSLContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.util.Properties; +import javax.net.ssl.SSLContext; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.ssl.SSLContexts; public class JettySSLUtils { + private JettySSLUtils() { } public static JettySslConfig getSSLConfig() throws IOException { Properties sslProperties = new Properties(); - String sslPropsPath = System.getenv("JETTY_BASE") + File.separator + "/start.d/ssl.ini"; File sslPropsFile = new File(sslPropsPath); try (FileInputStream fis = new FileInputStream(sslPropsFile)) { sslProperties.load(fis); } - return new JettySslConfig(sslProperties); } - public static SSLContext getSslContext() throws GeneralSecurityException, IOException { JettySSLUtils.JettySslConfig sslProperties = JettySSLUtils.getSSLConfig(); - - KeyStore trustStore = KeyStore.getInstance(sslProperties.getTruststoreType()); - try (FileInputStream instream = new FileInputStream(new File(sslProperties.getTruststorePath())); - ){ + KeyStore trustStore = KeyStore.getInstance(sslProperties.getTruststoreType()); + try (FileInputStream instream = new FileInputStream(new File(sslProperties.getTruststorePath()));) { trustStore.load(instream, (sslProperties.getTruststorePass()).toCharArray()); } - - KeyStore keystore = KeyStore.getInstance(sslProperties.getKeystoreType()); - try (FileInputStream instream = new FileInputStream(new File(sslProperties.getKeystorePath())); - ){ + KeyStore keystore = KeyStore.getInstance(sslProperties.getKeystoreType()); + try (FileInputStream instream = new FileInputStream(new File(sslProperties.getKeystorePath()));) { keystore.load(instream, sslProperties.getKeystorePass().toCharArray()); } - // Trust own CA and all self-signed certs - return SSLContexts.custom() - .loadKeyMaterial(keystore, sslProperties.getKeystorePass().toCharArray()) - .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) - .build(); + return SSLContexts.custom().loadKeyMaterial(keystore, sslProperties.getKeystorePass().toCharArray()) + .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); } - public static class JettySslConfig { - Properties sslProperties; + static final String JETTY_BASE = System.getenv("JETTY_BASE"); - static final String KEY_STORE_TYPE_PROPERTY_NAME="jetty.sslContext.keyStoreType"; - static final String TRUST_STORE_TYPE_PROPERTY_NAME="jetty.sslContext.trustStoreType"; + static final String KEY_STORE_TYPE_PROPERTY_NAME = "jetty.sslContext.keyStoreType"; + static final String TRUST_STORE_TYPE_PROPERTY_NAME = "jetty.sslContext.trustStoreType"; + Properties sslProperties; + JettySslConfig(Properties sslProperties) { this.sslProperties = sslProperties; } @@ -123,7 +113,5 @@ public class JettySSLUtils { public String getProperty(String key) { return sslProperties.getProperty(key); } - } - } |