diff options
Diffstat (limited to 'common-app-api/src/main/java')
70 files changed, 4169 insertions, 1560 deletions
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java index d2675ac0c0..3cb7974c06 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java @@ -42,8 +42,10 @@ public class BeEcompErrorManager extends AbsEcompErrorManager { public static BeEcompErrorManager getInstance() { if (instance == null) { - - instance = init(); + synchronized (BeEcompErrorManager.class){ + if (instance == null) + instance = init(); + } } return instance; } @@ -81,6 +83,14 @@ public class BeEcompErrorManager extends AbsEcompErrorManager { processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterRecovery); } + public void logDmaapHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.DmaapHealthCheckError); + } + + public void logDmaapHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.DmaapHealthCheckRecovery); + } + public void logFeHealthCheckRecovery(String context) { processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java index 0a0d6e505e..14b02b4ff9 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java @@ -20,16 +20,15 @@ package org.openecomp.sdc.be.config; -import static java.lang.String.format; +import org.openecomp.sdc.common.api.BasicConfiguration; import java.util.Date; -import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; +import static java.lang.String.format; -import org.openecomp.sdc.common.api.BasicConfiguration; - +import static java.util.Collections.emptyMap; public class Configuration extends BasicConfiguration { private List<String> identificationHeaderFields; @@ -74,15 +73,19 @@ public class Configuration extends BasicConfiguration { private int startMigrationFrom; private Long titanLockTimeout; private Long titanReconnectIntervalInSeconds; + private List<String> healthStatusExclude; private Long titanHealthCheckReadTimeout; private Long esReconnectIntervalInSeconds; private Long uebHealthCheckReconnectIntervalInSeconds; private Long uebHealthCheckReadTimeout; - private LinkedList<Map<String, Map<String, String>>> defaultImports; + private List<Map<String, Map<String, String>>> defaultImports; private List<String> resourceTypes; private List<String> excludeResourceCategory; private List<String> excludeResourceType; + private Map<String, Set<String>> excludedPolicyTypesMapping; + + private Map<String, Set<String>> excludedGroupTypesMapping; private Map<String, Object> deploymentResourceArtifacts; private Map<String, Object> deploymentResourceInstanceArtifacts; private Map<String, Object> toscaArtifacts; @@ -147,16 +150,28 @@ public class Configuration extends BasicConfiguration { } private String autoHealingOwner; - - private Map<String, List<String>> resourcesForUpgrade; - private boolean skipUpgradeFailedVfs; - - private boolean skipUpgradeVSPs; + private Map<String, List<String>> resourcesForUpgrade; + private DmaapConsumerConfiguration dmaapConsumerConfiguration; + private boolean skipUpgradeFailedVfs; + private boolean skipUpgradeVSPs; + private DmeConfiguration dmeConfiguration; + public DmaapConsumerConfiguration getDmaapConsumerConfiguration() { + return dmaapConsumerConfiguration; + } + public void setDmaapConsumerConfiguration(DmaapConsumerConfiguration dmaapConsumerConfiguration) { + this.dmaapConsumerConfiguration = dmaapConsumerConfiguration; + } + public DmeConfiguration getDmeConfiguration() { + return dmeConfiguration; + } + public void setDmeConfiguration(DmeConfiguration dmeConfiguration) { + this.dmeConfiguration = dmeConfiguration; + } public void setSkipUpgradeVSPs(boolean skipUpgradeVSPs) { this.skipUpgradeVSPs = skipUpgradeVSPs; } public boolean getSkipUpgradeVSPsFlag() { return skipUpgradeVSPs; } @@ -427,6 +442,21 @@ public class Configuration extends BasicConfiguration { this.excludeResourceType = excludeResourceType; } + public Map<String, Set<String>> getExcludedPolicyTypesMapping() { + return safeGetMap(excludedPolicyTypesMapping); + } + + public void setExcludedPolicyTypesMapping(Map<String, Set<String>> excludedPolicyTypesMapping) { + this.excludedPolicyTypesMapping = excludedPolicyTypesMapping; + } + + public Map<String, Set<String>> getExcludedGroupTypesMapping() { + return safeGetMap(excludedGroupTypesMapping); + } + + public void setExcludedGroupTypesMapping(Map<String, Set<String>> excludedGroupTypesMapping) { + this.excludedGroupTypesMapping = excludedGroupTypesMapping; + } public Map<String, Object> getToscaArtifacts() { return toscaArtifacts; @@ -1282,31 +1312,31 @@ public class Configuration extends BasicConfiguration { @Override public String toString() { - return new StringBuilder().append(format("backend host: %s\n", beFqdn)) - .append(format("backend http port: %s\n", beHttpPort)) - .append(format("backend ssl port: %s\n", beSslPort)).append(format("backend context: %s\n", beContext)) - .append(format("backend protocol: %s\n", beProtocol)).append(format("Version: %s\n", version)) - .append(format("Released: %s\n", released)).append(format("Supported protocols: %s\n", protocols)) - .append(format("Users: %s\n", users)).append(format("Neo4j: %s\n", neo4j)) - .append(format("ElasticSearch: %s\n", elasticSearch)) - .append(format("Titan Cfg File: %s\n", titanCfgFile)) - .append(format("Titan In memory: %s\n", titanInMemoryGraph)) - .append(format("Titan lock timeout: %s\n", titanLockTimeout)) - .append(format("Titan reconnect interval seconds: %s\n", titanReconnectIntervalInSeconds)) - .append(format("excludeResourceCategory: %s\n", excludeResourceCategory)) - .append(format("informationalResourceArtifacts: %s\n", informationalResourceArtifacts)) - .append(format("deploymentResourceArtifacts: %s\n", deploymentResourceArtifacts)) - .append(format("informationalServiceArtifacts: %s\n", informationalServiceArtifacts)) - .append(format("Supported artifacts types: %s\n", artifactTypes)) - .append(format("Supported license types: %s\n", licenseTypes)) - .append(format("Additional information Maximum number of preoperties: %s\n", + return new StringBuilder().append(format("backend host: %s%n", beFqdn)) + .append(format("backend http port: %s%n", beHttpPort)) + .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext)) + .append(format("backend protocol: %s%n", beProtocol)).append(format("Version: %s%n", version)) + .append(format("Released: %s%n", released)).append(format("Supported protocols: %s%n", protocols)) + .append(format("Users: %s%n", users)).append(format("Neo4j: %s%n", neo4j)) + .append(format("ElasticSearch: %s%n", elasticSearch)) + .append(format("Titan Cfg File: %s%n", titanCfgFile)) + .append(format("Titan In memory: %s%n", titanInMemoryGraph)) + .append(format("Titan lock timeout: %s%n", titanLockTimeout)) + .append(format("Titan reconnect interval seconds: %s%n", titanReconnectIntervalInSeconds)) + .append(format("excludeResourceCategory: %s%n", excludeResourceCategory)) + .append(format("informationalResourceArtifacts: %s%n", informationalResourceArtifacts)) + .append(format("deploymentResourceArtifacts: %s%n", deploymentResourceArtifacts)) + .append(format("informationalServiceArtifacts: %s%n", informationalServiceArtifacts)) + .append(format("Supported artifacts types: %s%n", artifactTypes)) + .append(format("Supported license types: %s%n", licenseTypes)) + .append(format("Additional information Maximum number of preoperties: %s%n", additionalInformationMaxNumberOfKeys)) - .append(format("Default Heat Artifact Timeout in Minutes: %s\n", defaultHeatArtifactTimeoutMinutes)) - .append(format("URLs For HTTP Requests that will not be automatically logged : %s\n", unLoggedUrls)) - .append(format("Service Api Artifacts: %s\n", serviceApiArtifacts)) - .append(format("heat env artifact header: %s\n", heatEnvArtifactHeader)) - .append(format("heat env artifact footer: %s\n", heatEnvArtifactFooter)) - .append(format("onboarding: %s\n", onboarding)).toString(); + .append(format("Default Heat Artifact Timeout in Minutes: %s%n", defaultHeatArtifactTimeoutMinutes)) + .append(format("URLs For HTTP Requests that will not be automatically logged : %s%n", unLoggedUrls)) + .append(format("Service Api Artifacts: %s%n", serviceApiArtifacts)) + .append(format("heat env artifact header: %s%n", heatEnvArtifactHeader)) + .append(format("heat env artifact footer: %s%n", heatEnvArtifactFooter)) + .append(format("onboarding: %s%n", onboarding)).toString(); } public List<String> getUnLoggedUrls() { @@ -1487,11 +1517,11 @@ public class Configuration extends BasicConfiguration { } } - public LinkedList<Map<String, Map<String, String>>> getDefaultImports() { + public List<Map<String, Map<String, String>>> getDefaultImports() { return defaultImports; } - public void setDefaultImports(LinkedList<Map<String, Map<String, String>>> defaultImports) { + public void setDefaultImports(List<Map<String, Map<String, String>>> defaultImports) { this.defaultImports = defaultImports; } @@ -1502,5 +1532,18 @@ public class Configuration extends BasicConfiguration { public void setResourcesForUpgrade(Map<String, List<String>> resourcesForUpgrade) { this.resourcesForUpgrade = resourcesForUpgrade; } - + + private <K,V> Map<K,V> safeGetMap(Map<K,V> map) { + return map == null ? emptyMap() : map; + } + + + public List<String> getHealthStatusExclude() { + return healthStatusExclude; + } + + public void setHealthStatusExclude(List<String> healthStatusExclude) { + this.healthStatusExclude = healthStatusExclude; + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java index 1bef188d0d..eeeca5b9bb 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java @@ -27,6 +27,7 @@ import java.util.Map; import java.util.Set; import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.http.config.ExternalServiceConfig; public class DistributionEngineConfiguration extends BasicConfiguration { @@ -44,10 +45,6 @@ public class DistributionEngineConfiguration extends BasicConfiguration { private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes; - // private List<String> distribNotifServiceInfoArtifactTypes; - - // private List<String> distribNotifResourceLifecycleArtifactTypes; - private String uebPublicKey; private String uebSecretKey; @@ -63,13 +60,25 @@ public class DistributionEngineConfiguration extends BasicConfiguration { private DistributionNotificationTopicConfig distributionNotificationTopic; private Integer defaultArtifactInstallationTimeout = 60; + + private Integer currentArtifactInstallationTimeout = 120; private boolean useHttpsWithDmaap; + private ExternalServiceConfig aaiConfig; + + private ExternalServiceConfig msoConfig; + + private Integer opEnvRecoveryIntervalSec; + + private Integer allowedTimeBeforeStaleSec; + public static class DistribNotifServiceArtifacts { Map<String, Object> service; Map<String, Object> resource; + + public Map<String, Object> getService() { return service; @@ -118,7 +127,7 @@ public class DistributionEngineConfiguration extends BasicConfiguration { } - public static enum ArtifcatTypeEnum { + public enum ArtifcatTypeEnum { MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML"); @@ -204,10 +213,10 @@ public class DistributionEngineConfiguration extends BasicConfiguration { public void setEnvironments(List<String> environments) { - Set<String> set = new HashSet<String>(); + Set<String> set = new HashSet<>(); if (environments != null) { set.addAll(environments); - this.environments = new ArrayList<String>(set); + this.environments = new ArrayList<>(set); } else { this.environments = null; } @@ -261,6 +270,14 @@ public class DistributionEngineConfiguration extends BasicConfiguration { public void setDefaultArtifactInstallationTimeout(int defaultArtifactInstallationTimeout) { this.defaultArtifactInstallationTimeout = defaultArtifactInstallationTimeout; } + + public int getCurrentArtifactInstallationTimeout() { + return currentArtifactInstallationTimeout; + } + + public void setCurrentArtifactInstallationTimeout(int currentArtifactInstallationTimeout) { + this.currentArtifactInstallationTimeout = currentArtifactInstallationTimeout; + } public boolean isUseHttpsWithDmaap() { return useHttpsWithDmaap; @@ -440,4 +457,35 @@ public class DistributionEngineConfiguration extends BasicConfiguration { } + public Integer getOpEnvRecoveryIntervalSec() { + return opEnvRecoveryIntervalSec; + } + + public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) { + this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec; + } + + public Integer getAllowedTimeBeforeStaleSec() { + return allowedTimeBeforeStaleSec; + } + + public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) { + this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec; + } + + public ExternalServiceConfig getAaiConfig() { + return aaiConfig; + } + + public void setAaiConfig(ExternalServiceConfig aaiConfig) { + this.aaiConfig = aaiConfig; + } + + public ExternalServiceConfig getMsoConfig() { + return msoConfig; + } + + public void setMsoConfig(ExternalServiceConfig msoConfig) { + this.msoConfig = msoConfig; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java new file mode 100644 index 0000000000..1ba539b942 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java @@ -0,0 +1,269 @@ +package org.openecomp.sdc.be.config; +/** + * Contains DMAAP Client configuration parameters + */ +public class DmaapConsumerConfiguration { + + private String hosts; + private String consumerGroup; + private String consumerId; + private Integer timeoutMs; + private Integer limit; + private Integer pollingInterval; + private String topic; + private Double latitude; + private Double longitude; + private String version; + private String serviceName; + private String environment; + private String partner; + private String routeOffer; + private String protocol; + private String contenttype; + private Boolean dme2TraceOn; + private String aftEnvironment; + private Integer aftDme2ConnectionTimeoutMs; + private Integer aftDme2RoundtripTimeoutMs; + private Integer aftDme2ReadTimeoutMs; + private String dme2preferredRouterFilePath; + private Credential credential; + private Integer timeLimitForNotificationHandleMs; + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + public String getConsumerGroup() { + return consumerGroup; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public String getConsumerId() { + return consumerId; + } + + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } + + public Integer getTimeoutMs() { + return timeoutMs; + } + + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Integer getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getPartner() { + return partner; + } + + public void setPartner(String partner) { + this.partner = partner; + } + + public String getRouteOffer() { + return routeOffer; + } + + public void setRouteOffer(String routeOffer) { + this.routeOffer = routeOffer; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getContenttype() { + return contenttype; + } + + public void setContenttype(String contenttype) { + this.contenttype = contenttype; + } + + public Boolean isDme2TraceOn() { + return dme2TraceOn; + } + + public Boolean getDme2TraceOn() { + return dme2TraceOn; + } + + public void setDme2TraceOn(Boolean dme2TraceOn) { + this.dme2TraceOn = dme2TraceOn; + } + + public String getAftEnvironment() { + return aftEnvironment; + } + + public void setAftEnvironment(String aftEnvironment) { + this.aftEnvironment = aftEnvironment; + } + + public Integer getAftDme2ConnectionTimeoutMs() { + return aftDme2ConnectionTimeoutMs; + } + + public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) { + this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs; + } + + public Integer getAftDme2RoundtripTimeoutMs() { + return aftDme2RoundtripTimeoutMs; + } + + public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) { + this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs; + } + + public Integer getAftDme2ReadTimeoutMs() { + return aftDme2ReadTimeoutMs; + } + + public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) { + this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs; + } + + public String getDme2preferredRouterFilePath() { + return dme2preferredRouterFilePath; + } + + public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) { + this.dme2preferredRouterFilePath = dme2preferredRouterFilePath; + } + + public Credential getCredential() { + return credential; + } + + public void setCredential(Credential credential) { + this.credential = credential; + } + + /** + * Contains Dmaap Client credential parameters: username and password + */ + public static class Credential{ + + private String username; + private String password; + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + + } + + @Override + public String toString() { + return "DmaapConsumerConfiguration [hosts=" + hosts + ", consumerGroup=" + consumerGroup + ", consumerId=" + + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + pollingInterval + + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + ", version=" + version + + ", serviceName=" + serviceName + ", environment=" + environment + ", partner=" + partner + + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + contenttype + + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment + + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs=" + + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs + + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath + + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs+ ", credential=" + credential + "]"; + } + + public Integer getTimeLimitForNotificationHandleMs() { + return timeLimitForNotificationHandleMs; + } + + public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { + this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java new file mode 100644 index 0000000000..82eb0a2f32 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.config; + +public class DmeConfiguration { + private String dme2Search = "DME2SEARCH"; + private String dme2Resolve = "DME2RESOLVE"; + + public String getDme2Search() { + return dme2Search; + } + + public void setDme2Search(String dme2Search) { + this.dme2Search = dme2Search; + } + + public String getDme2Resolve() { + return dme2Resolve; + } + + public void setDme2Resolve(String dme2Resolve) { + this.dme2Resolve = dme2Resolve; + } + + @Override + public String toString() { + return "DmeConfiguration [dme2Search=" + dme2Search + ", dme2Resolve=" + dme2Resolve + "]"; + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java index 40daf96d36..6751e3cfe2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java @@ -70,7 +70,6 @@ public class ErrorInfo { this.errorInfoType = ErrorInfoType.POLICY_EXCEPTION; } else { // unexpected - should it fail the startup? - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.ErrorConfigFileFormat, "Error Info"); BeEcompErrorManager.getInstance().logErrorConfigFileFormat("Error Info", "Could not set error info type for message id " + messageId); log.debug("Error: unexpected error message ID {}, should start with {} or {}", messageId, SVC_PREFIX, diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java index ac7391d8cc..f2438fcbfc 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java @@ -20,27 +20,24 @@ package org.openecomp.sdc.be.monitoring; -import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.servlet.ServletContext; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.config.HttpClientConfig; +import org.openecomp.sdc.common.http.config.Timeouts; import org.openecomp.sdc.common.monitoring.MonitoringEvent; import org.openecomp.sdc.common.monitoring.MonitoringMetricsFetcher; import org.slf4j.Logger; @@ -93,48 +90,22 @@ public class BeMonitoringService { } private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { - CloseableHttpClient httpClient = null; try { Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) .getConfiguration(); String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeFqdn(), config.getBeHttpPort()); - httpClient = getHttpClient(config); - HttpPost httpPost = new HttpPost(redirectedUrl); + + final int timeout = 3000; String monitoringMetricsJson = gson.toJson(monitoringMetrics); - HttpEntity myEntity = new StringEntity(monitoringMetricsJson); - httpPost.setEntity(myEntity); - httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - int beResponseStatus; - CloseableHttpResponse beResponse; - try { - beResponse = httpClient.execute(httpPost); - beResponseStatus = beResponse.getStatusLine().getStatusCode(); - if (beResponseStatus != HttpStatus.SC_OK) { - monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus); - } - } catch (Exception e) { - monitoringLogger.error("Monitoring error when trying to connect to BE", e); - } + HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); + HttpResponse<String> httpResponse = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); + int beResponseStatus = httpResponse.getStatusCode(); + if (beResponseStatus != HttpStatus.SC_OK) { + monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus); + } } catch (Exception e) { - monitoringLogger.error("Unexpected monitoring error", e); - } finally { - if (httpClient != null) { - try { - httpClient.close(); - } catch (IOException e) { - } - } + monitoringLogger.error("Monitoring BE failed with exception ", e); } } - - private CloseableHttpClient getHttpClient(Configuration config) { - int timeout = 3000; - RequestConfig.Builder requestBuilder = RequestConfig.custom(); - requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout); - - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setDefaultRequestConfig(requestBuilder.build()); - return builder.build(); - } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java index 691b8ea159..5d33e9918f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.common.api; -public interface Constants { +public final class Constants { public static final String APPLICATION_NAME = "application-name"; public static final String APPLICATION_VERSION = "application-version"; @@ -48,24 +48,20 @@ public interface Constants { public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID"; + public static final String X_TRANSACTION_ID_HEADER = "X-TransactionId"; + public static final String X_FROM_APP_ID = "X-FromAppId"; public static final String HTTP = "http"; public static final String HTTPS = "https"; public static final String HTTP_IV_USER = "HTTP_IV_USER"; public static final String A4C_CSAR_CONTEXT = "/rest/csars/"; public static final String WEB_APPLICATION_CONTEXT_WRAPPER_ATTR = "web-application-context-wrapper"; public static final String CATALOG_BE = "catalog-be"; - public static final String HTTP_CSP_FIRSTNAME = "HTTP_CSP_FIRSTNAME"; - public static final String HTTP_CSP_LASTNAME = "HTTP_CSP_LASTNAME"; - public static final String HTTP_IV_REMOTE_ADDRESS = "HTTP_IV_REMOTE_ADDRESS"; - public static final String HTTP_CSP_TYPE = "HTTP_CSP_WSTYPE"; public static final String RESOURCE_SUPPORTED_VERSION = "0.0.1"; public static final String ARTIFACT_ID_FORMAT = "%s:%s:%s"; // resourceName:resourceVersion:artifactName public static final String SERVICE_ARTIFACT_ID_FORMAT = "%s:%s:%s:%s"; // serviceName:serviceVersion:nodeTemplateName:artifactName public static final String CONTENT_DISPOSITION = "content-disposition"; public static final String DOWNLOAD_ARTIFACT_LOGIC_ATTR = "downloadArtifactLogic"; public static final String ASDC_RELEASE_VERSION_ATTR = "SDC-Version"; - // public static final String AUDITING_MANAGER = "auditingManager"; - // public static final String USER_ADMIN_MANAGER = "userAdminManager"; public static final String YEAR = "year"; public static final String MONTH = "month"; public static final String DAY = "day"; @@ -83,7 +79,6 @@ public interface Constants { public static final String ACCEPT_HEADER = "Accept"; public static final String STANDARD_INTERFACE_TYPE = "standard"; public static final String MURANO_PKG_ARTIFACT_TYPE = "MURANO-PKG"; - public static final String ARTIFACT_GROUP_TYPE_FIELD = "artifactGroupType"; // TOSCA public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; @@ -92,6 +87,8 @@ public interface Constants { public static final String IS_BASE = "isBase"; public static final String HEAT_FILE_PROPS = "heat_file"; + public static final String GROUP_POLICY_NAME_DELIMETER = ".."; + public static final String POLICY_UID_POSTFIX = ".policy"; public static final String MODULE_NAME_FORMAT = "%s..%s..module-%s"; public static final String MODULE_DESC_PATTERN = "[\\_\\-\\.a-zA-Z0-9]+"; public static final String MODULE_OLD_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+)(::module-)(\\d+)"; @@ -99,6 +96,7 @@ public interface Constants { public static final String MODULE_NAME_DELIMITER = "module-"; public static final String IMPORT_STRUCTURE = "importStructure"; public static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule"; + public static final String GROUP_TOSCA_HEAT = "org.openecomp.groups.heat.HeatStack"; public static final String ARTIFACT_GROUP_TYPE = "artifactGroupType"; public static final String ARTIFACT_LABEL = "artifactLabel"; @@ -107,6 +105,7 @@ public interface Constants { public static final String ARTIFACT_DESCRIPTION = "description"; public static final String ARTIFACT_TYPE = "artifactType"; public static final String ARTIFACT_NAME = "artifactName"; + public static final String IS_FROM_CSAR = "isFromCsar"; public static final String ARTIFACT_ID = "uniqueId"; public static final String REQUIRED_ARTIFACTS = "requiredArtifacts"; public static final String ARTIFACT_HEAT_PARAMS = "heatParameters"; @@ -134,8 +133,10 @@ public interface Constants { public static final String HC_COMPONENT_FE = "FE"; public static final String HC_COMPONENT_BE = "BE"; public static final String HC_COMPONENT_TITAN = "TITAN"; + public static final String HC_COMPONENT_ES = "ES"; public static final String HC_COMPONENT_CASSANDRA = "CASSANDRA"; public static final String HC_COMPONENT_DISTRIBUTION_ENGINE = "DE"; + public static final String HC_COMPONENT_DMAAP_ENGINE = "DMAPP"; //external HealthCheck components public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING"; @@ -143,4 +144,6 @@ public interface Constants { //Plugin BL public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL"; + + private Constants(){} } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java index 8afd2fb4c9..7a22495643 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java @@ -51,7 +51,7 @@ public class HealthCheckInfo { this.version = version; this.description = description; this.componentsInfo = componentsInfo; - } +} public HealthCheckInfo() { super(); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java index 6a54071f42..49f04d2ee1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java @@ -20,98 +20,15 @@ package org.openecomp.sdc.common.config; -import java.util.Formatter; -import java.util.IllegalFormatException; -import java.util.Locale; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompAlarmSeverity; -import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompErrorSeverity; -import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompErrorType; - import com.jcabi.aspects.Loggable; @Loggable(prepend = true, value = Loggable.TRACE, trim = false) -public abstract class AbsEcompErrorManager implements IEcompErrorManager { +public abstract class AbsEcompErrorManager { public static final String PARAM_STR = "%s"; public abstract IEcompConfigurationManager getConfigurationManager(); - @Deprecated - @Override - public void processEcompError(EcompErrorName ecompErrorName, String ecompErrorContext, - String... descriptionParams) { - - /* - * //Getting the relevant config manager IEcompConfigurationManager - * configurationManager = getConfigurationManager(); - * - * //Getting the error by name EcompErrorInfo ecompErrorInfo = - * configurationManager.getEcompErrorConfiguration().getEcompErrorInfo( - * ecompErrorName.name()); - * - * if (ecompErrorInfo != null){ ecompErrorInfo = - * setDescriptionParams(ecompErrorInfo, ecompErrorName.name(), - * descriptionParams); EcompErrorLogUtil.logEcompError(ecompErrorName, - * ecompErrorInfo, ecompErrorContext); } else { - * EcompErrorLogUtil.logEcompError(EcompErrorName.EcompErrorNotFound, - * getErrorInfoForUnknownErrorName(ecompErrorName.name()), - * ecompErrorContext); } - */ - - } - - private EcompErrorInfo setDescriptionParams(EcompErrorInfo ecompErrorInfo, String ecompErrorName, - String... descriptionParams) { - String description = ecompErrorInfo.getDescription(); - // Counting number of params in description - int countMatches = StringUtils.countMatches(description, PARAM_STR); - // Catching cases when there are more params passed than there are in - // the description (formatter will ignore extra params and won't throw - // exception) - if (countMatches != descriptionParams.length) { - return getErrorInfoForDescriptionParamsMismatch(ecompErrorName); - } - // Setting params of the description if any - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - try { - formatter.format(description, (Object[]) descriptionParams).toString(); - ecompErrorInfo.setDescription(formatter.toString()); - } catch (IllegalFormatException e) { - // Number of passed params doesn't match number of params in config - // file - return getErrorInfoForDescriptionParamsMismatch(ecompErrorName); - } finally { - formatter.close(); - } - return ecompErrorInfo; - } - - private EcompErrorInfo getErrorInfoForUnknownErrorName(String ecompErrorName) { - EcompErrorInfo ecompErrorInfo = new EcompErrorInfo(); - ecompErrorInfo.setCode(EcompErrorConfiguration.ECODE_PREFIX + "3001"); - ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name()); - ecompErrorInfo.setSeverity(EcompErrorSeverity.ERROR.name()); - ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.MAJOR.name()); - ecompErrorInfo.setDescription(new StringBuilder().append("Ecomp error element not found in YAML, name: ") - .append(ecompErrorName).toString()); - return ecompErrorInfo; - } - - private EcompErrorInfo getErrorInfoForDescriptionParamsMismatch(String ecompErrorName) { - EcompErrorInfo ecompErrorInfo = new EcompErrorInfo(); - ecompErrorInfo.setCode(EcompErrorConfiguration.ECODE_PREFIX + "3002"); - ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name()); - ecompErrorInfo.setSeverity(EcompErrorSeverity.ERROR.name()); - ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.MAJOR.name()); - ecompErrorInfo.setDescription(new StringBuilder() - .append("Ecomp error description params mismatch between code and YAML or wrong format, name: ") - .append(ecompErrorName).toString()); - return ecompErrorInfo; - } - public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... descriptionParams) { EcompErrorLogUtil.logEcompError(context, ecompErrorEnum, descriptionParams); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java index aaee26004f..aabd6d9305 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java @@ -44,8 +44,9 @@ public enum EcompErrorCode { "Connection problem towards U-EB server. Cannot reach host %s", "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_212( "Couldn't resolve hostIP. Desciption: %s"), E_213( - "Site switch over was done. Site is now in %s mode"), E_299( - "Internal Connection problem. Description: %s"), + "Site switch over was done. Site is now in %s mode"), E_214( + "Dmaap Connection problem."), E_299( + "Internal Connection problem. Description: %s"), // [resource/service/product] E_300("Mandatory %s Component %s cannot be found in repository"), diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java index c79677a9ef..575cbe9e7e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java @@ -22,9 +22,14 @@ package org.openecomp.sdc.common.config; public enum EcompErrorEnum { + BeUebAuthenticationError(EcompErrorCode.E_100, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + + DmaapHealthCheckError(EcompErrorCode.E_214, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, + EcompClassification.ERROR), + InternalAuthenticationInfo(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), InternalAuthenticationWarning(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MINOR, @@ -43,7 +48,9 @@ public enum EcompErrorEnum { AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), FeHealthCheckRecovery(EcompErrorCode.E_209, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, - null), BeHealthCheckError(EcompErrorCode.E_200, ErrorType.SYSTEM_ERROR, + null),DmaapHealthCheckRecovery( EcompErrorCode.E_210, ErrorType.RECOVERY, + AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, + null), BeHealthCheckError(EcompErrorCode.E_200, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, BeHealthCheckRecovery), diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java index 6bd139bb28..5da7808376 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java @@ -37,5 +37,7 @@ public enum EcompErrorName { // BeRepositoryQueryError, BeDaoSystemError, BeSystemError, BeInvalidConfigurationError, BeMissingConfigurationError, BeUebConnectionError, BeUebObjectNotFoundError, BeUebSystemError, BeDistributionEngineSystemError, BeDistributionEngineInvalidArtifactType, BeConfigurationInvalidListSizeError, BeUebAuthenticationError, BeUebUnkownHostError, BeInvalidTypeError, BeInvalidValueError, BeFailedLockObjectError, BeInvalidJsonInput, BeDistributionMissingError, ErrorConfigFileFormat, // model - BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError; + BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError, + //dmaap + DmaapHealthCheckRecovery , DmaapHealthCheckError; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompErrorManager.java deleted file mode 100644 index 7b9aa8e730..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompErrorManager.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.config; - -public interface IEcompErrorManager { - - public void processEcompError(EcompErrorName ecompErrorName, String ecompErrorContext, String... descriptionParams); - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java index 53aa2391d5..0dd15073da 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java @@ -68,6 +68,9 @@ public enum AuditingFieldsKeysEnum { AUDIT_DISTRIBUTION_RESOURCE_URL(String.class, "RESOURCE_URL"), AUDIT_DISTRIBUTION_STATUS_TIME(String.class, "STATUS_TIME"), AUDIT_DISTRIBUTION_STATUS_DESC(String.class, "STATUS_DESC"), + AUDIT_DISTRIBUTION_ENVIRONMENT_ID(String.class, "ENV_ID"), + AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT(String.class, "VNF_WORKLOAD_CONTEXT"), + AUDIT_DISTRIBUTION_TENANT(String.class, "TENANT"), // category AUDIT_CATEGORY_NAME(String.class, "CATEGORY_NAME"), @@ -75,6 +78,13 @@ public enum AuditingFieldsKeysEnum { AUDIT_GROUPING_NAME(String.class, "GROUPING_NAME"), AUDIT_DETAILS(String.class, "DETAILS"), + //operational environment + AUDIT_OPERATIONAL_ENVIRONMENT_ID(String.class, "OPERATIONAL_ENVIRONMENT_ID"), + AUDIT_OPERATIONAL_ENVIRONMENT_NAME(String.class, "OPERATIONAL_ENVIRONMENT_NAME"), + AUDIT_OPERATIONAL_ENVIRONMENT_TYPE(String.class, "OPERATIONAL_ENVIRONMENT_TYPE"), + AUDIT_OPERATIONAL_ENVIRONMENT_ACTION(String.class, "OPERATIONAL_ENVIRONMENT_ACTION"), + AUDIT_TENANT_CONTEXT(String.class, "TENANT_CONTEXT"), + // authentication AUDIT_AUTH_URL(String.class, "URL"), AUDIT_AUTH_USER(String.class, "USER"), diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java index de94358ab4..64266f5985 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java @@ -21,10 +21,25 @@ package org.openecomp.sdc.common.datastructure; import java.io.Serializable; +import java.util.Arrays; import java.util.List; +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; +import org.apache.commons.lang3.math.NumberUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.F; import fj.data.Either; /** @@ -36,14 +51,16 @@ import fj.data.Either; public class FunctionalInterfaces { private static final int DEFAULT_REDO_INTERVAL_TIME_MS = 50; private static final int DEFAULT_MAX_WAIT_TIME_MS = 10000; - + private static final Logger LOGGER = LoggerFactory.getLogger(FunctionalInterfaces.class); + /** * This is an interface of a List that implements Serializable + * * @author mshitrit * * @param <T> */ - public interface SerializableList<T> extends List<T> , Serializable { + public interface SerializableList<T> extends List<T>, Serializable { } /** @@ -94,6 +111,17 @@ public class FunctionalInterfaces { R apply(T t) throws E; } + public interface FunctionTwoParamThrows<T1, T2, R, E extends Exception> { + /** + * Same apply method, but throws an exception + * + * @param t1 + * @param t2 + * @return + */ + R apply(T1 t1, T2 t2) throws E; + } + /** * @author mshitrit Supplier that throws an exception * @param <R> @@ -264,6 +292,80 @@ public class FunctionalInterfaces { /** * Runs the given method.<br> + * Verify the method result against the resultVerifier.<br> + * If verification passed returns the result.<br> + * If Verification failed keeps retrying until maxRetries reached.<br> + * If Exception Occurred keeps retrying until it passes or until maxRetries + * reached,<br> + * If last retry result caused an exception - it is thrown. + * + * @param methodToRun + * given Method + * @param resultVerifier + * verifier for the method result + * @param maxRetries + * @return + */ + public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier, + long maxRetries) { + boolean stopSearch = false; + R ret = null; + int retriesCount = 0; + FunctionalAttException functionalExceotion = null; + boolean isExceptionInLastTry = false; + while (!stopSearch) { + try { + ret = methodToRun.get(); + stopSearch = resultVerifier.apply(ret); + isExceptionInLastTry = false; + } catch (Exception e) { + functionalExceotion = new FunctionalAttException(e); + isExceptionInLastTry = true; + } finally { + if (++retriesCount >= maxRetries) { + stopSearch = true; + } + } + } + if (isExceptionInLastTry) { + throw functionalExceotion; + } else { + return ret; + } + } + + public static <R> R retryMethodOnException(SupplierThrows<R, Exception> methodToRun, + Function<Exception, Boolean> exceptionVerifier, long maxRetries) throws Exception { + boolean stopSearch = false; + R ret = null; + int retriesCount = 0; + Exception exception = null; + while (!stopSearch) { + try { + exception = null; + ret = methodToRun.get(); + stopSearch = true; + } + catch (Exception e) { + exception = e; + stopSearch = exceptionVerifier.apply(e); + } + finally { + if (++retriesCount >= maxRetries) { + stopSearch = true; + } + } + } + if (exception != null) { + throw exception; + } + else { + return ret; + } + } + + /** + * Runs the given method.<br> * In case exception occurred runs the method again either until succeed or * until 10 seconds pass. * @@ -312,17 +414,15 @@ public class FunctionalInterfaces { * @param eitherToConvert * @return */ - public static <T1,T2,T3> Either<T1,T2> convertEitherRight(Either<T3,T2> eitherToConvert){ - if( eitherToConvert.isLeft() ){ + public static <T1, T2, T3> Either<T1, T2> convertEitherRight(Either<T3, T2> eitherToConvert) { + if (eitherToConvert.isLeft()) { throw new UnsupportedOperationException("Can not convert either right value because it has left value"); - } - else{ + } else { return Either.right(eitherToConvert.right().value()); } - - + } - + /** * Converts Either containing left value to another either with different * type of right value and the same type of left value. @@ -330,14 +430,95 @@ public class FunctionalInterfaces { * @param eitherToConvert * @return */ - public static <T1,T2,T3> Either<T1,T2> convertEitherLeft(Either<T1,T3> eitherToConvert){ - if( eitherToConvert.isLeft() ){ + public static <T1, T2, T3> Either<T1, T2> convertEitherLeft(Either<T1, T3> eitherToConvert) { + if (eitherToConvert.isLeft()) { throw new UnsupportedOperationException("Can not convert either left value because it has right value"); + } else { + return Either.left(eitherToConvert.left().value()); + } + + } + + /** + * Returns enum value for a field <br> + * + * @param fieldValue + * @param values + * @param enumValueGetter + * @return + */ + public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values, + Function<T, String> enumValueGetter, T defaultValue) { + return getEnumValueByFieldValue(fieldValue, values, enumValueGetter, defaultValue, true); + + } + + + public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values, + Function<T, String> enumValueGetter, T defaultValue, boolean isCaseSensetive ){ + + final Predicate<? super T> predicate; + if( isCaseSensetive ){ + predicate = e -> fieldValue.equals(enumValueGetter.apply(e)); } else{ - return Either.left(eitherToConvert.left().value()); + predicate = e -> fieldValue.equalsIgnoreCase(enumValueGetter.apply(e)); + } + Optional<T> optionalFound = + // Stream of values of enum + Arrays.asList(values).stream(). + // Filter in the one that match the field + filter(predicate). + // collect + findAny(); + T ret; + ret = optionalFound.isPresent() ? optionalFound.get() : defaultValue; + return ret; + + } + + /** + * This method runs the given method.<br> + * In case given method finished running within timeoutInMs limit it returns + * Either which left value is the result of the method that ran.<br> + * In case given method did not finish running within timeoutInMs limit it + * returns Either which right value is false. <br> + * + * @param supplier + * @param timeoutInMs + * - if 0 or lower no timeout is used + * @return + */ + public static <T> Either<T, Boolean> runMethodWithTimeOut(Supplier<T> supplier, long timeoutInMs) { + Either<T, Boolean> result; + if (timeoutInMs <= NumberUtils.LONG_ZERO) { + result = Either.left(supplier.get()); + } else { + ExecutorService pool = Executors.newSingleThreadExecutor(); + Future<T> future = pool.submit(supplier::get); + try { + T calcValue = future.get(timeoutInMs, TimeUnit.MILLISECONDS); + result = Either.left(calcValue); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + LOGGER.debug("method run was canceled because it has passed its time limit of {} MS", timeoutInMs, e); + result = Either.right(false); + } finally { + pool.shutdownNow(); + } } - + return result; + } + + public static <T> F<T, Boolean> convertToFunction(Consumer<T> consumer) { + F<T, Boolean> func = t -> { + try { + consumer.accept(t); + return true; + } catch (Exception e) { + return false; + } + }; + return func; } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerAudit.java new file mode 100644 index 0000000000..e5f5fc99dd --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerAudit.java @@ -0,0 +1,184 @@ +package org.openecomp.sdc.common.ecomplog; + +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ALERT_SEVERITY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_CLASS_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ELAPSED_TIME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_END_TIMESTAMP; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_INSTANCE_UUID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD1; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD2; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD3; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD4; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PROCESS_KEY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_REMOTE_HOST; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_CODE; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_DESC; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_STATUS_CODE; + +import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers; +import org.openecomp.sdc.common.ecomplog.Enums.Severity; +import org.openecomp.sdc.common.ecomplog.Enums.StatusCode; +import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper; +import org.slf4j.MDC; +import org.slf4j.MarkerFactory; + +public class EcompLoggerAudit extends EcompLoggerBase{ + private static EcompLoggerAudit instanceLoggerAudit = EcompLoggerFactory.getLogger(EcompLoggerAudit.class); + + EcompLoggerAudit(IEcompMdcWrapper ecompMdcWrapper) { + super (ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.AUDIT_MARKER.text())); + } + + public static EcompLoggerAudit getInstance() { + return instanceLoggerAudit; + } + + @Override + public EcompLoggerAudit startTimer() { + return (EcompLoggerAudit) super.startTimer(); + } + + public EcompLoggerAudit stopTimer() { + ecompMdcWrapper.stopTimer(); + return this; + } + + // automatic parameter this is optional + public EcompLoggerAudit setAutoServerFQDN(String serverFQDN) { + ecompMdcWrapper.setAutoServerFQDN(serverFQDN); + return this; + } + + // automatic parameter this is optional + public EcompLoggerAudit setAutoServerIPAddress(String serverIPAddress) { + ecompMdcWrapper.setAutoServerIPAddress(serverIPAddress); + return this; + } + + public EcompLoggerAudit setInstanceUUID(String instanceUUID) { + ecompMdcWrapper.setInstanceUUID(instanceUUID); + return this; + } + + public EcompLoggerAudit setOptClassName(String className) { + MDC.put("ClassName", className); + return this; + } + + public EcompLoggerAudit setOptProcessKey(String processKey) { + ecompMdcWrapper.setProcessKey(processKey); + return this; + } + + public EcompLoggerAudit setOptAlertSeverity(Severity alertSeverity) { + ecompMdcWrapper.setAlertSeverity(alertSeverity); + return this; + } + + // ecomplog optional parameter + public EcompLoggerAudit setOptCustomField1(String customField1) { + ecompMdcWrapper.setOptCustomField1(customField1); + return this; + } + + // ecomplog optional parameter + public EcompLoggerAudit setOptCustomField2(String customField2) { + ecompMdcWrapper.setOptCustomField2(customField2); + return this; + } + + // ecomplog optional parameter + public EcompLoggerAudit setOptCustomField3(String customField3) { + ecompMdcWrapper.setOptCustomField3(customField3); + return this; + } + + public EcompLoggerAudit setOptCustomField4(String customField4) { + ecompMdcWrapper.setOptCustomField4(customField4); + return this; + } + + @Override + public EcompLoggerAudit setKeyRequestId(String keyRequestId) { + return (EcompLoggerAudit) super.setKeyRequestId(keyRequestId); + } + + public EcompLoggerAudit setRemoteHost(String remoteHost) { + ecompMdcWrapper.setRemoteHost(remoteHost); + return this; + } + + public EcompLoggerAudit setServiceName(String serviceName) { + ecompMdcWrapper.setServiceName(serviceName); + return this; + } + + public EcompLoggerAudit setStatusCode(String statusCode) { + // status code is either success (COMPLETE) or failure (ERROR) of the request. + String respStatus = Integer.parseInt(statusCode) / 100 == 2 ? StatusCode.COMPLETE.getStatusCodeEnum() : StatusCode.ERROR.getStatusCodeEnum(); + ecompMdcWrapper.setStatusCode(respStatus); + return this; + } + + public EcompLoggerAudit setPartnerName(String partnerName) { + ecompMdcWrapper.setPartnerName(partnerName); + return this; + } + + public EcompLoggerAudit setResponseCode(EcompLoggerErrorCode responseCode) { + ecompMdcWrapper.setResponseCode(responseCode.getErrorCode()); + return this; + } + + public EcompLoggerAudit setResponseDesc(String responseDesc) { + ecompMdcWrapper.setResponseDesc(responseDesc); + return this; + } + + public EcompLoggerAudit setOptServiceInstanceId(String serviceInstanceId) { + ecompMdcWrapper.setServiceInstanceId(serviceInstanceId); + return this; + } + + @Override + public EcompLoggerAudit clear() { + return (EcompLoggerAudit) super.clear(); + } + + @Override + public void initializeMandatoryFields() { + + ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP); + ecompMdcWrapper.setMandatoryField(MDC_END_TIMESTAMP); + ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID); + ecompMdcWrapper.setMandatoryField(MDC_SERVICE_NAME); + ecompMdcWrapper.setMandatoryField(MDC_PARTNER_NAME); + ecompMdcWrapper.setMandatoryField(MDC_STATUS_CODE); + ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_CODE); + ecompMdcWrapper.setMandatoryField(MDC_SERVICE_INSTANCE_ID); + ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_DESC); + ecompMdcWrapper.setMandatoryField(MDC_ELAPSED_TIME); + + //Theoretically Optional, but practically Mandatory + ecompMdcWrapper.setMandatoryField(MDC_SERVER_IP_ADDRESS); + ecompMdcWrapper.setMandatoryField(MDC_SERVER_FQDN); + + ecompMdcWrapper.setOptionalField(MDC_INSTANCE_UUID); + ecompMdcWrapper.setOptionalField(MDC_ALERT_SEVERITY); + ecompMdcWrapper.setOptionalField(MDC_REMOTE_HOST); + ecompMdcWrapper.setOptionalField(MDC_CLASS_NAME); + ecompMdcWrapper.setOptionalField(MDC_PROCESS_KEY); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD1); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD2); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD3); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD4); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerBase.java new file mode 100644 index 0000000000..535e8a4204 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerBase.java @@ -0,0 +1,79 @@ +package org.openecomp.sdc.common.ecomplog; + +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS; + +import org.openecomp.sdc.common.ecomplog.Enums.LogLevel; +import org.openecomp.sdc.common.ecomplog.api.IEcompLogger; +import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; + + +/** + * Created by mm288v on 12/27/2017. + * This class holds the common behavior of all Loger-Typed classes. + * The Concrete loggers shoudl derive from this one. + */ +public abstract class EcompLoggerBase implements IEcompLogger{ + private static Logger myLogger = LoggerFactory.getLogger(IEcompLogger.class.getName()); + private Marker myMarker; + IEcompMdcWrapper ecompMdcWrapper; + + EcompLoggerBase(IEcompMdcWrapper ecompMdcWrapper, Marker marker) { + this.ecompMdcWrapper = ecompMdcWrapper; + initializeMandatoryFields(); + this.myMarker = marker; + } + + @Override + public void log(LogLevel errorLevel, String message) { + + ecompMdcWrapper.validateMandatoryFields(); + + if (this instanceof EcompLoggerAudit || this instanceof EcompLoggerMetric) { + MDC.put(MDC_SERVER_IP_ADDRESS, EcompMDCWrapper.getInstance().getHostAddress()); + MDC.put(MDC_SERVER_FQDN, EcompMDCWrapper.getInstance().getFqdn()); + } + + if (errorLevel.equals(LogLevel.ERROR)) { + myLogger.error(myMarker, message); + return; + } + + if (errorLevel.equals(LogLevel.WARN)) { + myLogger.warn(myMarker, message); + return; + } + + if (errorLevel.equals(LogLevel.INFO)) { + myLogger.info(myMarker, message); + return; + } + + if (errorLevel.equals(LogLevel.DEBUG)) { + myLogger.info(myMarker, message); + } + } + + @Override + public IEcompLogger clear() { + ecompMdcWrapper.clear(); + return this; + } + + @Override + public IEcompLogger startTimer() { + ecompMdcWrapper.startTimer(); + return this; + } + + @Override + public IEcompLogger setKeyRequestId(String keyRequestId) { + ecompMdcWrapper.setKeyRequestId(keyRequestId); + return this; + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerDebug.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerDebug.java new file mode 100644 index 0000000000..aecb487e24 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerDebug.java @@ -0,0 +1,51 @@ +package org.openecomp.sdc.common.ecomplog; + +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID; + +import org.openecomp.sdc.common.ecomplog.Enums.LogLevel; +import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers; +import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper; +import org.slf4j.MarkerFactory; + +public class EcompLoggerDebug extends EcompLoggerBase { + + private static EcompLoggerDebug instanceLoggerDebug = EcompLoggerFactory.getLogger(EcompLoggerDebug.class); + + protected final String endOfRecordDelimiter = "|^\\n"; + + EcompLoggerDebug(IEcompMdcWrapper ecompMdcWrapper) { + super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text())); + } + + public static EcompLoggerDebug getInstance() { + return instanceLoggerDebug; + } + + @Override + public void log(LogLevel errorLevel, String message) { + String formattedMessage = String.format("%s%s", message, endOfRecordDelimiter); + super.log(errorLevel, formattedMessage); + } + + @Override + public void initializeMandatoryFields() { + ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP); + ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID); + } + + @Override + public EcompLoggerDebug clear() { + return (EcompLoggerDebug) super.clear(); + } + + @Override + public EcompLoggerDebug startTimer() { + return (EcompLoggerDebug) super.startTimer(); + } + + @Override + public EcompLoggerDebug setKeyRequestId(String keyRequestId) { + return (EcompLoggerDebug) super.setKeyRequestId(keyRequestId); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerError.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerError.java new file mode 100644 index 0000000000..92a495fda7 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerError.java @@ -0,0 +1,77 @@ +package org.openecomp.sdc.common.ecomplog; + +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_CATEGORY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_CODE; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_DESC; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_ENTITY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_SERVICE_NAME; + +import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers; +import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper; +import org.slf4j.MarkerFactory; + +public class EcompLoggerError extends EcompLoggerBase{ + private static EcompLoggerError instanceLoggerError = EcompLoggerFactory.getLogger(EcompLoggerError.class); + + EcompLoggerError(IEcompMdcWrapper ecompMdcWrapper) { + super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.ERROR_MARKER.text())); + } + + public static EcompLoggerError getInstance() { + return instanceLoggerError; + } + + @Override + public void initializeMandatoryFields() { + ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP); + ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID); + ecompMdcWrapper.setMandatoryField(MDC_SERVICE_NAME); + ecompMdcWrapper.setMandatoryField(MDC_PARTNER_NAME); + ecompMdcWrapper.setMandatoryField(MDC_ERROR_CATEGORY); + ecompMdcWrapper.setMandatoryField(MDC_ERROR_CODE); + ecompMdcWrapper.setMandatoryField(MDC_ERROR_DESC); + + ecompMdcWrapper.setOptionalField(MDC_TARGET_ENTITY); + ecompMdcWrapper.setOptionalField(MDC_TARGET_SERVICE_NAME); + } + + @Override + public EcompLoggerError startTimer() { + return (EcompLoggerError) super.startTimer(); + } + + @Override + public EcompLoggerError setKeyRequestId(String keyRequestId) { + return (EcompLoggerError) super.setKeyRequestId(keyRequestId); + } + + public EcompLoggerError setServiceName(String serviceName) { + ecompMdcWrapper.setServiceName(serviceName); + return this; + } + + public EcompLoggerError setTargetEntity(String targetEntity) { + ecompMdcWrapper.setTargetEntity(targetEntity); + return this; + } + + public EcompLoggerError setErrorCode(EcompLoggerErrorCode errorCode) { + ecompMdcWrapper.setErrorCode(errorCode.getErrorCode()); + return this; + } + + public EcompLoggerError setErrorDescription(String errorDescription) { + ecompMdcWrapper.setErrorDescription(errorDescription); + return this; + } + + public EcompLoggerError clear() { + return (EcompLoggerError) super.clear(); + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerFactory.java new file mode 100644 index 0000000000..2ea1280f48 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerFactory.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.common.ecomplog; + +/** + * Created by dd4296 on 12/26/2017. + * this factory helps decouple the classes for Stopwatch and EcompMDCWrapper from + * the EcompLogger classes + */ +public class EcompLoggerFactory { + + private EcompLoggerFactory() { + } + + @SuppressWarnings("unchecked") + static public <T, V> V getLogger(Class<T> type) { + + if (type.getName().equals(EcompLoggerAudit.class.getName())) { + return (V) new EcompLoggerAudit(new EcompMDCWrapper(new Stopwatch())); + } + + if (type.getName().equals(EcompLoggerDebug.class.getName())) { + return (V) new EcompLoggerDebug(new EcompMDCWrapper(new Stopwatch())); + } + + if (type.getName().equals(EcompLoggerMetric.class.getName())) { + return (V) new EcompLoggerMetric(new EcompMDCWrapper(new Stopwatch())); + } + + if (type.getName().equals(EcompLoggerError.class.getName())) { + return (V) new EcompLoggerError(new EcompMDCWrapper(new Stopwatch())); + } + + return null; + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerMetric.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerMetric.java new file mode 100644 index 0000000000..2405a0eadf --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerMetric.java @@ -0,0 +1,207 @@ +package org.openecomp.sdc.common.ecomplog; + +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ALERT_SEVERITY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_CLASS_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ELAPSED_TIME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_END_TIMESTAMP; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_INSTANCE_UUID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD1; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD2; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD3; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD4; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PROCESS_KEY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_REMOTE_HOST; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_CODE; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_DESC; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_STATUS_CODE; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_ENTITY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_SERVICE_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_VIRTUAL_ENTITY; + +import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers; +import org.openecomp.sdc.common.ecomplog.Enums.Severity; +import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper; +import org.slf4j.MarkerFactory; + + +public class EcompLoggerMetric extends EcompLoggerBase{ + private static EcompLoggerMetric instanceLoggerMetric = (EcompLoggerMetric) EcompLoggerFactory.getLogger(EcompLoggerMetric.class); + + EcompLoggerMetric(IEcompMdcWrapper ecompMdcWrapper) { + super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.METRIC_MARKER.text())); + } + + public static EcompLoggerMetric getInstance() { + return instanceLoggerMetric; + } + + @Override + public EcompLoggerMetric startTimer() { + return (EcompLoggerMetric) super.startTimer(); + } + + @Override + public EcompLoggerMetric setKeyRequestId(String keyRequestId) { + return (EcompLoggerMetric) super.setKeyRequestId(keyRequestId); + } + + public EcompLoggerMetric stopTimer() { + ecompMdcWrapper.stopTimer(); + return this; + } + + // automatic parameter this is optional + public EcompLoggerMetric setAutoServerFQDN(String serverFQDN) { + ecompMdcWrapper.setAutoServerFQDN(serverFQDN); + return this; + } + + // automatic parameter this is optional + public EcompLoggerMetric setAutoServerIPAddress(String serverIPAddress) { + ecompMdcWrapper.setAutoServerIPAddress(serverIPAddress); + return this; + } + + public EcompLoggerMetric setInstanceUUID(String instanceUUID) { + ecompMdcWrapper.setInstanceUUID(instanceUUID); + return this; + } + + // ecomplog optional parameter + public EcompLoggerMetric setOptProcessKey(String processKey) { + ecompMdcWrapper.setProcessKey(processKey); + return this; + } + + // ecomplog optional parameter + public EcompLoggerMetric setOptAlertSeverity(Severity alertSeverity) { + ecompMdcWrapper.setAlertSeverity(alertSeverity); + return this; + } + + // ecomplog optional parameter + public EcompLoggerMetric setOptCustomField1(String customField1) { + ecompMdcWrapper.setOptCustomField1(customField1); + return this; + } + + // ecomplog optional parameter + public EcompLoggerMetric setOptCustomField2(String customField2) { + ecompMdcWrapper.setOptCustomField2(customField2); + return this; + } + + // ecomplog optional parameter + public EcompLoggerMetric setOptCustomField3(String customField3) { + ecompMdcWrapper.setOptCustomField3(customField3); + return this; + } + + // ecomplog optional parameter + public EcompLoggerMetric setOptCustomField4(String customField4) { + ecompMdcWrapper.setOptCustomField4(customField4); + return this; + } + + public EcompLoggerMetric setRemoteHost(String remoteHost) { + ecompMdcWrapper.setRemoteHost(remoteHost); + return this; + } + + public EcompLoggerMetric setServiceName(String serviceName) { + ecompMdcWrapper.setServiceName(serviceName); + return this; + } + + public EcompLoggerMetric setStatusCode(String statusCode) { + ecompMdcWrapper.setStatusCode(statusCode); + return this; + } + + public EcompLoggerMetric setPartnerName(String partnerName) { + ecompMdcWrapper.setPartnerName(partnerName); + return this; + } + + public EcompLoggerMetric setResponseCode(int responseCode) { + ecompMdcWrapper.setResponseCode(responseCode); + return this; + } + + public EcompLoggerMetric setResponseDesc(String responseDesc) { + ecompMdcWrapper.setResponseDesc(responseDesc); + return this; + } + + public EcompLoggerMetric setOptServiceInstanceId(String serviceInstanceId) { + ecompMdcWrapper.setServiceInstanceId(serviceInstanceId); + return this; + } + + public EcompLoggerMetric setOptClassName(String className) { + ecompMdcWrapper.setClassName(className); + return this; + } + + public EcompLoggerMetric setTargetEntity(String targetEntity) { + ecompMdcWrapper.setTargetEntity(targetEntity); + return this; + } + + public EcompLoggerMetric setTargetServiceName(String targetServiceName) { + ecompMdcWrapper.setTargetServiceName(targetServiceName); + return this; + } + + public EcompLoggerMetric setTargetVirtualEntity(String targetVirtualEntity) { + ecompMdcWrapper.setTargetVirtualEntity(targetVirtualEntity); + return this; + } + + @Override + public EcompLoggerMetric clear () { + return (EcompLoggerMetric) super.clear(); + } + + + @Override + public void initializeMandatoryFields() { + + ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP); + ecompMdcWrapper.setMandatoryField(MDC_END_TIMESTAMP); + ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID); + ecompMdcWrapper.setMandatoryField(MDC_SERVICE_NAME); + ecompMdcWrapper.setMandatoryField(MDC_PARTNER_NAME); + ecompMdcWrapper.setMandatoryField(MDC_STATUS_CODE); + ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_CODE); + ecompMdcWrapper.setMandatoryField(MDC_SERVICE_INSTANCE_ID); + ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_DESC); + ecompMdcWrapper.setMandatoryField(MDC_ELAPSED_TIME); + ecompMdcWrapper.setMandatoryField(MDC_TARGET_ENTITY); + ecompMdcWrapper.setMandatoryField(MDC_TARGET_SERVICE_NAME); + ecompMdcWrapper.setMandatoryField(MDC_TARGET_VIRTUAL_ENTITY); + + //Theoretically Optional, but practically Mandatory + ecompMdcWrapper.setMandatoryField(MDC_SERVER_IP_ADDRESS); + ecompMdcWrapper.setMandatoryField(MDC_SERVER_FQDN); + + ecompMdcWrapper.setOptionalField(MDC_INSTANCE_UUID); + ecompMdcWrapper.setOptionalField(MDC_ALERT_SEVERITY); + ecompMdcWrapper.setOptionalField(MDC_REMOTE_HOST); + ecompMdcWrapper.setOptionalField(MDC_CLASS_NAME); + ecompMdcWrapper.setOptionalField(MDC_PROCESS_KEY); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD1); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD2); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD3); + ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD4); + + + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompMDCWrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompMDCWrapper.java new file mode 100644 index 0000000000..1d833ec6f9 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompMDCWrapper.java @@ -0,0 +1,290 @@ +package org.openecomp.sdc.common.ecomplog; + +import static java.lang.Integer.valueOf; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ALERT_SEVERITY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_CLASS_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_CODE; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_DESC; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_INSTANCE_UUID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD1; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD2; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD3; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD4; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PROCESS_KEY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_REMOTE_HOST; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_CODE; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_DESC; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_STATUS_CODE; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_ENTITY; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_SERVICE_NAME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_VIRTUAL_ENTITY; + +import java.net.InetAddress; +import java.util.ArrayList; + +import org.openecomp.sdc.common.ecomplog.Enums.Severity; +import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper; +import org.openecomp.sdc.common.ecomplog.api.IStopWatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +public class EcompMDCWrapper implements IEcompMdcWrapper { + + private static EcompMDCWrapper instanceMdcWrapper = new EcompMDCWrapper(new Stopwatch()); + + public static EcompMDCWrapper getInstance() { + return instanceMdcWrapper; + } + + private IStopWatch stopWatch; + protected static Logger log = LoggerFactory.getLogger(EcompMDCWrapper.class.getName()); + protected ArrayList<String> mandatoryFields = new ArrayList<>(); + protected ArrayList<String> optionalFields = new ArrayList<>(); + protected static String hostAddress; + protected static String fqdn; + + // in package classes can instantiate this class + // to use directly from outside the package usr the getInstance() Method + EcompMDCWrapper(IStopWatch stopwatch) { + this.stopWatch = stopwatch; + } + + static { + try { + hostAddress = InetAddress.getLocalHost().getHostAddress(); + fqdn = InetAddress.getByName(hostAddress).getCanonicalHostName(); + } catch (Exception ex) { + log.error("failed to get machine parameters", ex); + } + } + + @Override + public EcompMDCWrapper startTimer() { + stopWatch.start(); + return this; + } + + @Override + public EcompMDCWrapper stopTimer() { + try { + stopWatch.stop(); + } catch (Exception ex) { + log.error("StopWatch failed; probably start was not called before Stopwatch", ex); + } + return this; + } + + @Override + public EcompMDCWrapper setClassName(String className) { + MDC.put(MDC_CLASS_NAME, className); + return this; + } + + // automatic parameter this is optional + @Override + public EcompMDCWrapper setAutoServerFQDN(String serverFQDN) { + MDC.put(MDC_SERVER_FQDN, serverFQDN); + return this; + } + + // automatic parameter this is optional + @Override + public EcompMDCWrapper setAutoServerIPAddress(String serverIPAddress) { + MDC.put(MDC_SERVER_IP_ADDRESS, serverIPAddress); + return this; + } + + @Override + public EcompMDCWrapper setInstanceUUID(String instanceUUID) { + MDC.put(MDC_INSTANCE_UUID, instanceUUID); + return this; + } + + @Override + public EcompMDCWrapper setProcessKey(String processKey) { + MDC.put(MDC_PROCESS_KEY, processKey); + return this; + } + + @Override + public EcompMDCWrapper setAlertSeverity(Severity alertSeverity) { + MDC.put(MDC_ALERT_SEVERITY, String.valueOf(alertSeverity.getSeverityType())); + return this; + } + + @Override + public EcompMDCWrapper setOptCustomField1(String customField1) { + MDC.put(MDC_OPT_FIELD1, customField1); + return this; + } + + @Override + public EcompMDCWrapper setOptCustomField2(String customField2) { + MDC.put(MDC_OPT_FIELD2, customField2); + return this; + } + + @Override + public EcompMDCWrapper setOptCustomField3(String customField3) { + MDC.put(MDC_OPT_FIELD3, customField3); + return this; + } + + @Override + public EcompMDCWrapper setOptCustomField4(String customField4) { + MDC.put(MDC_OPT_FIELD4, customField4); + return this; + } + + @Override + public EcompMDCWrapper setKeyRequestId(String keyRequestId) { + MDC.put(MDC_KEY_REQUEST_ID, keyRequestId); // eg. servletRequest.getSession().getId() + return this; + } + + @Override + public EcompMDCWrapper setRemoteHost(String remoteHost) { + MDC.put(MDC_REMOTE_HOST, remoteHost); + return this; + } + + @Override + public EcompMDCWrapper setServiceName(String serviceName) { + MDC.put(MDC_SERVICE_NAME, serviceName); + return this; + } + + @Override + public EcompMDCWrapper setStatusCode(String statusCode) { + MDC.put(MDC_STATUS_CODE, statusCode); + return this; + } + + @Override + public EcompMDCWrapper setPartnerName(String partnerName) { + MDC.put(MDC_PARTNER_NAME, partnerName); + return this; + } + + @Override + public EcompMDCWrapper setResponseCode(int responseCode) { + MDC.put(MDC_RESPONSE_CODE, Integer.toString(responseCode)); + return this; + } + + @Override + public EcompMDCWrapper setResponseDesc(String responseDesc) { + MDC.put(MDC_RESPONSE_DESC, responseDesc); + return this; + } + + @Override + public EcompMDCWrapper setServiceInstanceId(String serviceInstanceId) { + MDC.put(MDC_SERVICE_INSTANCE_ID, serviceInstanceId); + return this; + } + + @Override + public EcompMDCWrapper setTargetEntity(String targetEntity) { + MDC.put(MDC_TARGET_ENTITY, targetEntity); + return this; + } + + @Override + public EcompMDCWrapper setTargetServiceName(String targetServiceName) { + MDC.put(MDC_TARGET_SERVICE_NAME, targetServiceName); + return this; + } + + @Override + public EcompMDCWrapper setTargetVirtualEntity(String targetVirtualEntity) { + MDC.put(MDC_TARGET_VIRTUAL_ENTITY, targetVirtualEntity); + return this; + } + + @Override + public EcompMDCWrapper setErrorCode(int errorCode) { + MDC.put(MDC_ERROR_CODE, valueOf(errorCode).toString()); + return this; + } + + @Override + public EcompMDCWrapper setErrorDescription(String errorDescription) { + MDC.put(MDC_ERROR_DESC, errorDescription); + return this; + } + + @Override + public void validateMandatoryFields() { + // this method only checks if the mandatory fields have been initialized + String filedNameThatHasNotBeenInitialized = checkMandatoryFieldsExistInMDC(); + + if (MDC.getCopyOfContextMap() == null || MDC.getCopyOfContextMap().isEmpty()) { + writeLogMDCEmptyError(); + return; + } + + if (!"".equalsIgnoreCase(filedNameThatHasNotBeenInitialized)) { + writeLogMissingFieldsError(filedNameThatHasNotBeenInitialized); + } + } + + protected void writeLogMissingFieldsError(String FiledNameThatHasNotBeenInitialized) { + log.error("mandatory parameters for EELF logging, missing fields: %s", FiledNameThatHasNotBeenInitialized); + } + + protected void writeLogMDCEmptyError() { + log.error("write to log when MDC is empty error"); + } + + @Override + public EcompMDCWrapper clear() { + mandatoryFields.forEach(MDC::remove); + optionalFields.forEach(MDC::remove); + return this; + } + + protected String checkMandatoryFieldsExistInMDC() { + // this method returns a String of uninitialised fields + StringBuilder missingFields = new StringBuilder(); + mandatoryFields.forEach(field -> { + if (isMDCParamEmpty(field)) { + missingFields.append(field).append(" "); + } + }); + return missingFields.toString(); + } + + @Override + public void setMandatoryField(String parameterName) { + mandatoryFields.add(parameterName); + } + + @Override + public void setOptionalField(String parameterName) { + optionalFields.add(parameterName); + } + + @Override + public boolean isMDCParamEmpty(String mdcKeyName) { + String val = MDC.get(mdcKeyName); + return (val == null || val.trim().length() == 0); + } + + @Override + public String getFqdn() { + return fqdn; + } + + @Override + public String getHostAddress() { + return hostAddress; + } +}
\ No newline at end of file diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/EcompLoggerErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/EcompLoggerErrorCode.java new file mode 100644 index 0000000000..c6862656bb --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/EcompLoggerErrorCode.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.common.ecomplog.Enums; + +/** + * Created by dd4296 on 12/26/2017. + */ +public enum EcompLoggerErrorCode { + SUCCESS(0), + PERMISSION_ERROR(100), + AVAILABILITY_TIMEOUTS_ERROR(200), + DATA_ERROR(300), + SCHEMA_ERROR(400), + BUSINESS_PROCESS_ERROR(500), + UNKNOWN_ERROR(900); + + int errorCode; + + EcompLoggerErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public int getErrorCode() { + return errorCode; + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogLevel.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogLevel.java new file mode 100644 index 0000000000..2fc7d7f26f --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogLevel.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.common.ecomplog.Enums; + +/** + * Created by dd4296 on 12/14/2017. + */ +public enum LogLevel { + INFO, + WARN, + DEBUG, + ERROR, + FATAL +} + diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogMarkers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogMarkers.java new file mode 100644 index 0000000000..b26e8c105d --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogMarkers.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.common.ecomplog.Enums; + +/** + * Created by mm288v on 12/27/2017. + * This enum reflects the Marker text in logback.xml file per each ecomp marker + */ +public enum LogMarkers { + DEBUG_MARKER("DEBUG_MARKER"), + ERROR_MARKER("ERROR_MARKER"), + AUDIT_MARKER("AUDIT_MARKER"), + METRIC_MARKER("METRICS"); + + private String text; + + LogMarkers (String text){ + this.text = text; + } + + public String text(){ + return text; + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/Severity.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/Severity.java new file mode 100644 index 0000000000..f842927af2 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/Severity.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.common.ecomplog.Enums; + +/** + * Created by dd4296 on 12/14/2017. + */ +public enum Severity { + OK(0), + WARNING(1), + CRITICAL(2), + DOWN(3), + UNREACHABLE(4); + + int severityType; + + Severity(int serveryType) { + this.severityType = serveryType; + } + + public int getSeverityType() { + return severityType; + } +} + diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/StatusCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/StatusCode.java new file mode 100644 index 0000000000..2fdd96f11b --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/StatusCode.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.common.ecomplog.Enums; + +public enum StatusCode { + ERROR("ERROR"), + COMPLETE("COMPLETE"); + + String statusCode; + + StatusCode(String statusCode){this.statusCode = statusCode;} + + public String getStatusCodeEnum(){ + return statusCode; + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Stopwatch.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Stopwatch.java new file mode 100644 index 0000000000..76262e7815 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Stopwatch.java @@ -0,0 +1,61 @@ +package org.openecomp.sdc.common.ecomplog; + +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ELAPSED_TIME; +import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_END_TIMESTAMP; + +import java.time.Clock; +import java.time.Duration; +import java.time.LocalDateTime; + +import org.openecomp.sdc.common.ecomplog.api.IStopWatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +/** + * Created by dd4296 on 12/13/2017. + * this is local implementation of the stopwatch class from EELF standard with the same interface + * can be replaced if needed with EELF lib + */ +public class Stopwatch implements IStopWatch { + + private static Logger log = LoggerFactory.getLogger(Stopwatch.class.getName()); + + public Stopwatch() { + } + + public void start() { + if (MDC.get(MDC_BEGIN_TIMESTAMP) == null || MDC.get(MDC_BEGIN_TIMESTAMP).trim().length() == 0) + MDC.put(MDC_BEGIN_TIMESTAMP, generatedTimeNow()); + } + + public void stop() { + if (MDC.get(MDC_BEGIN_TIMESTAMP) == null) { + log.error("call to stop without calling start first, this is not compliant with EELF format"); + } + MDC.put(MDC_END_TIMESTAMP, generatedTimeNow()); + setElapsedTime(); + } + + private void setElapsedTime() { + + try { + + final LocalDateTime startTime = LocalDateTime.parse(MDC.get(MDC_BEGIN_TIMESTAMP)); + final LocalDateTime endTime = LocalDateTime.parse(MDC.get(MDC_END_TIMESTAMP)); + + final Duration timeDifference = Duration.between(startTime, endTime); + + MDC.put(MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis())); + + } catch(Exception ex) { + log.error("failed to calculate elapsed time",ex); + } + } + + private String generatedTimeNow() { + return String.valueOf(LocalDateTime.now(Clock.systemUTC())); + } + +}
\ No newline at end of file diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogConfiguration.java new file mode 100644 index 0000000000..6521ea78e1 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogConfiguration.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.common.ecomplog.api; + +public interface IEcompLogConfiguration { + String PROPERTY_LOGGING_FILE_NAME = "com.att.ecomplog.logging.file"; + String PROPERTY_LOGGING_FILE_PATH = "com.att.ecomplog.logging.path"; + String GENERAL_LOGGER_NAME = "com.att.ecomplog"; + String METRICS_LOGGER_NAME = "com.att.ecomplog.metrics"; + String PERF_LOGGER_NAME = "com.att.ecomplog.perf"; + String POLICY_LOGGER_NAME = "com.att.ecomplog.policy"; + String SECURITY_LOGGER_NAME = "com.att.ecomplog.security"; + String SERVER_LOGGER_NAME = "com.att.ecomplog.server"; + String AUDIT_LOGGER_NAME = "com.att.ecomplog.audit"; + String ERROR_LOGGER_NAME = "com.att.ecomplog.error"; + String DEBUG_LOGGER_NAME = "com.att.ecomplog.debug"; + String MDC_KEY_REQUEST_ID = "RequestId"; + String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceId"; + String MDC_SERVICE_NAME = "ServiceName"; + String MDC_INSTANCE_UUID = "InstanceUUID"; + String MDC_SERVER_IP_ADDRESS = "ServerIPAddress"; + String MDC_SERVER_FQDN = "ServerFQDN"; + String MDC_REMOTE_HOST = "RemoteHost"; + String MDC_ALERT_SEVERITY = "AlertSeverity"; + String MDC_BEGIN_TIMESTAMP = "BeginTimestamp"; + String MDC_END_TIMESTAMP = "EndTimestamp"; + String MDC_PARTNER_NAME = "PartnerName"; + String MDC_STATUS_CODE = "StatusCode"; + String MDC_RESPONSE_CODE = "ResponseCode"; + String MDC_RESPONSE_DESC = "ResponseDescription"; + String MDC_ELAPSED_TIME = "ElapsedTime"; + String MDC_PROCESS_KEY = "ProcessKey"; + String MDC_TARGET_ENTITY = "TargetEntity"; + String MDC_TARGET_SERVICE_NAME = "TargetServiceName"; + String MDC_TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; + String MDC_ERROR_CATEGORY = "ErrorCategory"; + String MDC_ERROR_CODE = "ErrorCode"; + String MDC_ERROR_DESC = "ErrorDescription"; + String MDC_CLASS_NAME = "ClassName"; + String MDC_OPT_FIELD1 = "CustomField1"; + String MDC_OPT_FIELD2 = "CustomField2"; + String MDC_OPT_FIELD3 = "CustomField3"; + String MDC_OPT_FIELD4 = "CustomField4"; +}
\ No newline at end of file diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogger.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogger.java new file mode 100644 index 0000000000..569343eaf6 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogger.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.common.ecomplog.api; + +import org.openecomp.sdc.common.ecomplog.Enums.LogLevel; + +/** + * Created by dd4296 on 12/24/2017. + */ +public interface IEcompLogger { + void log(LogLevel errorLevel, String message); + void initializeMandatoryFields(); + IEcompLogger clear(); + IEcompLogger startTimer(); + IEcompLogger setKeyRequestId(String keyRequestId); +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompMdcWrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompMdcWrapper.java new file mode 100644 index 0000000000..37d77fd6c5 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompMdcWrapper.java @@ -0,0 +1,75 @@ +package org.openecomp.sdc.common.ecomplog.api; + +import org.openecomp.sdc.common.ecomplog.EcompMDCWrapper; +import org.openecomp.sdc.common.ecomplog.Enums.Severity; + +/** + * Created by dd4296 on 12/25/2017. + */ +public interface IEcompMdcWrapper { + EcompMDCWrapper startTimer(); + + EcompMDCWrapper stopTimer(); + + EcompMDCWrapper setClassName(String className); + + // automatic parameter this is optional + EcompMDCWrapper setAutoServerFQDN(String serverFQDN); + + // automatic parameter this is optional + EcompMDCWrapper setAutoServerIPAddress(String serverIPAddress); + + EcompMDCWrapper setInstanceUUID(String instanceUUID); + + EcompMDCWrapper setProcessKey(String processKey); + + EcompMDCWrapper setAlertSeverity(Severity alertSeverity); + + EcompMDCWrapper setOptCustomField1(String customField1); + + EcompMDCWrapper setOptCustomField2(String customField2); + + EcompMDCWrapper setOptCustomField3(String customField3); + + EcompMDCWrapper setOptCustomField4(String customField4); + + EcompMDCWrapper setKeyRequestId(String keyRequestId); + + EcompMDCWrapper setRemoteHost(String remoteHost); + + EcompMDCWrapper setServiceName(String serviceName); + + EcompMDCWrapper setStatusCode(String statusCode); + + EcompMDCWrapper setPartnerName(String partnerName); + + EcompMDCWrapper setResponseCode(int responseCode); + + EcompMDCWrapper setResponseDesc(String responseDesc); + + EcompMDCWrapper setServiceInstanceId(String serviceInstanceId); + + EcompMDCWrapper setTargetEntity(String targetEntity); + + EcompMDCWrapper setTargetServiceName(String targetServiceName); + + EcompMDCWrapper setTargetVirtualEntity(String targetVirtualEntity); + + EcompMDCWrapper setErrorCode(int errorCode); + + EcompMDCWrapper setErrorDescription(String errorDescription); + + EcompMDCWrapper clear(); + + void validateMandatoryFields(); + + void setMandatoryField(String mdcKeyRequestId); + + void setOptionalField(String mdcKeyRequestId); + + boolean isMDCParamEmpty(String mdcKeyName); + + String getFqdn(); + + String getHostAddress(); +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IStopWatch.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IStopWatch.java new file mode 100644 index 0000000000..4f1649cef1 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IStopWatch.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.common.ecomplog.api; + +/** + * Created by dd4296 on 12/14/2017. + * + * stop watch interface compliant with ecomplog stop watch class + */ +public interface IStopWatch { + void start(); + void stop(); +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcAudit.java new file mode 100644 index 0000000000..57499b340d --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcAudit.java @@ -0,0 +1,92 @@ +package org.openecomp.sdc.common.ecomplogwrapper; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.ecomplog.EcompLoggerAudit; +import org.openecomp.sdc.common.ecomplog.Enums.LogLevel; +import org.openecomp.sdc.common.ecomplog.Enums.Severity; +import org.slf4j.MDC; + + +/** + * Created by dd4296 on 12/19/2017. + * + * audit log for asdc using the ecomplog library + * this is adapted for filter classes + */ +public class EcompLoggerSdcAudit extends EcompLoggerSdcUtilBase { + + private static String AUDIT_ON = "auditOn"; + private String className; + + public EcompLoggerSdcAudit(String className) { + this.className = className; + } + + public void startLog() { + EcompLoggerAudit + .getInstance() + .clear() + .startTimer(); + MDC.put(AUDIT_ON, "true"); + } + + public static boolean isFlowBeingTakenCare(){ + try + { + if (MDC.get(AUDIT_ON).equals("true")){ + return true; + } + return false; + } + catch (Exception E) + { + return false; + } + } + + public void log(HttpServletRequest sr, + ContainerRequestContext requestContext, + Response.StatusType statusInfo, + MultivaluedMap<String, Object> responseHeaders, + LogLevel errorLevel, + Severity securityLevel, + String message) { + + try { + EcompLoggerAudit.getInstance() + .stopTimer() + .setRemoteHost(sr.getRemoteAddr()) + .setServiceName(getServiceName(requestContext)) + .setResponseCode(convertHttpCodeToErrorCode(statusInfo.getStatusCode())) + .setStatusCode(Integer.toString(statusInfo.getStatusCode())) + .setResponseDesc(statusInfo.getReasonPhrase()) + .setKeyRequestId(getRequestIDfromHeaders(responseHeaders.get(Constants.X_ECOMP_REQUEST_ID_HEADER))) + + .setPartnerName(getPartnerName( + requestContext.getHeaderString("user-agent"), + requestContext.getHeaderString("USER_ID"), + getUrl(requestContext))) + + .setInstanceUUID(requestContext.getHeaderString(Constants.X_ECOMP_INSTANCE_ID_HEADER)) + + .setOptServiceInstanceId(requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER)) + .setOptClassName(className) + .setOptAlertSeverity(securityLevel) + .setOptCustomField1(requestContext.getMethod() + ": " + getUrl(requestContext)) + .setOptCustomField2(Integer.toString(statusInfo.getStatusCode())) + .log(errorLevel, message); + } + catch (Exception E) + { + log.warn("Faild to write to Audit Log. Original Message: {}", message); + } + finally { + MDC.put(AUDIT_ON,"false"); + } + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcDebug.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcDebug.java new file mode 100644 index 0000000000..57e9e8c5a0 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcDebug.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.common.ecomplogwrapper; + +import java.util.Arrays; + +import org.openecomp.sdc.common.ecomplog.EcompLoggerDebug; +import org.openecomp.sdc.common.ecomplog.Enums.LogLevel; + +public class EcompLoggerSdcDebug { + + public void log(LogLevel errorLevel, + String uuid, + String message, + Exception ex) { + + StringBuilder stackTrack = new StringBuilder(); + Arrays.asList(ex.getStackTrace()).forEach(item -> stackTrack.append(item.toString()).append("\n")); + + EcompLoggerDebug.getInstance() + .clear() + .startTimer() + .setKeyRequestId(uuid) + .log(errorLevel, String.format("%s %s", message, stackTrack.toString())); + } + + public void log(LogLevel errorLevel, + String uuid, + String message) { + + EcompLoggerDebug.getInstance() + .clear() + .startTimer() + .setKeyRequestId(uuid) + .log(errorLevel, message); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcError.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcError.java new file mode 100644 index 0000000000..a2478c40eb --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcError.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.common.ecomplogwrapper; + +import org.openecomp.sdc.common.ecomplog.EcompLoggerError; +import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.ecomplog.Enums.LogLevel; + +public class EcompLoggerSdcError { + + public void log(LogLevel errorLevel, + EcompLoggerErrorCode errorCodeEnum, + String uuid, + String errorDescription, + String partnerName, + String targetEntity, + String message) { + + EcompLoggerError.getInstance() + .clear() + .startTimer() + .setErrorDescription(errorDescription) + .setErrorCode(errorCodeEnum) + .setKeyRequestId(uuid) + .setServiceName(partnerName) + .setTargetEntity(targetEntity) + .log(errorLevel, message); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcMetric.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcMetric.java new file mode 100644 index 0000000000..8603a77d08 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcMetric.java @@ -0,0 +1,71 @@ +package org.openecomp.sdc.common.ecomplogwrapper; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; + +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.ecomplog.EcompLoggerAudit; +import org.openecomp.sdc.common.ecomplog.EcompLoggerMetric; +import org.openecomp.sdc.common.ecomplog.Enums.LogLevel; +import org.openecomp.sdc.common.ecomplog.Enums.Severity; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +/** + * Created by dd4296 on 12/20/2017. + * + * METRIC log for asdc using the ecomplog library + */ +public class EcompLoggerSdcMetric extends EcompLoggerSdcUtilBase { + + private String className; + + public EcompLoggerSdcMetric(String className) { + this.className = className; + } + + public void startLog() { + EcompLoggerAudit + .getInstance() + .clear() + .startTimer(); + } + + public void writeToLog(HttpServletRequest sr, + ContainerRequestContext requestContext, + Response.StatusType statusInfo, + LogLevel errorLevel, + Severity securityLevel, + String targetEntity, + String targetServiceName, + String targetVirtualEntity, + String message) { + + EcompLoggerMetric.getInstance() + .stopTimer() + .setRemoteHost(sr.getRemoteAddr()) + .setServiceName(getServiceName(requestContext)) + .setResponseCode(statusInfo.getStatusCode()) + .setStatusCode(Integer.toString(statusInfo.getStatusCode())) + .setResponseDesc(statusInfo.getReasonPhrase()) + .setKeyRequestId(ThreadLocalsHolder.getUuid()) + + .setPartnerName(getPartnerName( + requestContext.getHeaderString("user-agent"), + requestContext.getHeaderString("USER_ID"), + getUrl(requestContext))) + + .setInstanceUUID(requestContext.getHeaderString(Constants.X_ECOMP_INSTANCE_ID_HEADER)) + + .setOptServiceInstanceId(requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER)) + .setOptClassName(className) + .setOptAlertSeverity(securityLevel) + .setOptCustomField1(getUrl(requestContext) + "/" + requestContext.getMethod()) + + .setTargetEntity(targetEntity) + .setTargetServiceName(targetServiceName) + .setTargetVirtualEntity(targetVirtualEntity) + + .log(errorLevel, message); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcUtilBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcUtilBase.java new file mode 100644 index 0000000000..3fe49c17e6 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcUtilBase.java @@ -0,0 +1,198 @@ +package org.openecomp.sdc.common.ecomplogwrapper; + +import static java.net.HttpURLConnection.HTTP_BAD_METHOD; +import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; +import static java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT; +import static java.net.HttpURLConnection.HTTP_CONFLICT; +import static java.net.HttpURLConnection.HTTP_ENTITY_TOO_LARGE; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; +import static java.net.HttpURLConnection.HTTP_GONE; +import static java.net.HttpURLConnection.HTTP_LENGTH_REQUIRED; +import static java.net.HttpURLConnection.HTTP_NOT_ACCEPTABLE; +import static java.net.HttpURLConnection.HTTP_NOT_FOUND; +import static java.net.HttpURLConnection.HTTP_PAYMENT_REQUIRED; +import static java.net.HttpURLConnection.HTTP_PRECON_FAILED; +import static java.net.HttpURLConnection.HTTP_PROXY_AUTH; +import static java.net.HttpURLConnection.HTTP_REQ_TOO_LONG; +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_UNSUPPORTED_TYPE; + +import java.util.List; +import java.util.StringTokenizer; + +import javax.ws.rs.container.ContainerRequestContext; + +import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by dd4296 on 12/20/2017. + * + * base class for metric and audit ecomplog logging + * holding the specific logic for data extraction + */ +public class EcompLoggerSdcUtilBase { + + protected static Logger log = LoggerFactory.getLogger(EcompLoggerSdcUtilBase.class.getName()); + + String getRequestIDfromHeaders(List<Object> requestHeader) { + // this method gets list of type object. + // toString method returns the RequestId with brackets. + String requestHeaderString = requestHeader.toString(); + return requestHeaderString.replace("[","").replace("]",""); + } + + + // this method translates http error code to ECOMP Logger Error code + // this is a naive translation and is not a result of any documented format ECOMP specification + protected EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) { + if (isSuccessError(httpResponseCode)) + return EcompLoggerErrorCode.SUCCESS; + + if (isSchemaError(httpResponseCode)) + return EcompLoggerErrorCode.SCHEMA_ERROR; + + if (isDataError(httpResponseCode)) + return EcompLoggerErrorCode.DATA_ERROR; + + if (isPermissionsError(httpResponseCode)) + return EcompLoggerErrorCode.PERMISSION_ERROR; + + if (isTimeoutOrAvailabilityError(httpResponseCode)) + return EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR; + + if (isBusinessProcessError(httpResponseCode)) + return EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; + + + return EcompLoggerErrorCode.UNKNOWN_ERROR; + } + + private boolean isTimeoutOrAvailabilityError(int httpResponseCode) { + + switch (httpResponseCode) { + case HTTP_BAD_REQUEST: + case HTTP_UNAUTHORIZED: + case HTTP_NOT_FOUND: + case HTTP_CLIENT_TIMEOUT: + case HTTP_GONE: + return true; + } + + return false; + } + + private boolean isPermissionsError(int httpResponseCode) { + + switch (httpResponseCode) { + case HTTP_PAYMENT_REQUIRED: + case HTTP_FORBIDDEN: + case HTTP_BAD_METHOD: + case HTTP_PROXY_AUTH: + return true; + } + + return false; + } + + private boolean isDataError(int httpResponseCode) { + + switch (httpResponseCode) { + case HTTP_NOT_ACCEPTABLE: + case HTTP_LENGTH_REQUIRED: + case HTTP_PRECON_FAILED: + case HTTP_REQ_TOO_LONG: + case HTTP_ENTITY_TOO_LARGE: + case HTTP_UNSUPPORTED_TYPE: + return true; + } + + return false; + } + + private boolean isSchemaError(int httpResponseCode) { + return HTTP_CONFLICT == httpResponseCode; + } + + private boolean isSuccessError(int httpResponseCode) { + return httpResponseCode < 399; + } + + private boolean isBusinessProcessError(int httpResponseCode) { + return httpResponseCode > 499; + } + + protected String getPartnerName(String userAgent, String userId, String url) { + + if (!isNullOrEmpty(userId)) { + return userId; + } + + String urlUser = getUserIdFromUrl(url); + + if (!isNullOrEmpty(urlUser)) + return urlUser; + + String userAgentName = getUserIdFromUserAgent(userAgent); + + if (!isNullOrEmpty(userAgentName)) + return userAgentName; + + return ""; + } + + private String getUserIdFromUserAgent(String userAgent) { + if (userAgent != null && userAgent.length() > 0) { + if (userAgent.toLowerCase().contains("firefox")) { + return "fireFox_FE"; + } + + if (userAgent.toLowerCase().contains("msie")) { + return "explorer_FE"; + } + + if (userAgent.toLowerCase().contains("chrome")) { + return "chrome_FE"; + } + + return userAgent; + } + return null; + } + + private String getUserIdFromUrl(String url) { + if (url != null && url.toLowerCase().contains("user")) { + StringTokenizer st = new StringTokenizer(url, "/"); + while (st.hasMoreElements()) { + if ("user".equalsIgnoreCase(st.nextToken())) { + return st.nextToken(); + } + } + } + return null; + } + + protected String getUrl(ContainerRequestContext requestContext) { + String url = ""; + + try { + if (requestContext.getUriInfo() != null && requestContext.getUriInfo().getRequestUri() != null) { + url = requestContext.getUriInfo().getRequestUri().toURL().toString(); + } + } catch (Exception ex) { + log.error("failed to get url from request context ", ex); + } + + return url; + } + + private boolean isNullOrEmpty(String str) { + return (str == null || str.isEmpty()); + } + + protected String getServiceName(ContainerRequestContext requestContext) { + return (requestContext.getUriInfo().getRequestUri().toString()) + .replace(requestContext.getUriInfo().getBaseUri().toString(), "/"); + } +}
\ No newline at end of file diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java new file mode 100644 index 0000000000..1f25d31944 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.common.http.client.api; +import org.apache.http.client.HttpRequestRetryHandler; + +public interface ComparableHttpRequestRetryHandler extends HttpRequestRetryHandler { + public default <T extends HttpRequestRetryHandler> boolean compare(T handler) { + return (handler != null && getClass() == handler.getClass()); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java new file mode 100644 index 0000000000..26518a6456 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java @@ -0,0 +1,147 @@ +package org.openecomp.sdc.common.http.client.api; + +import java.io.IOException; +import java.net.URI; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScheme; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPatch; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpClient { + private static final Logger logger = LoggerFactory.getLogger(HttpClient.class); + + private final CloseableHttpClient client; + private final HttpClientConfigImmutable configImmutable; + + HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { + this.client = client; + this.configImmutable = configImmutable; + } + + <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + HttpGet httpGet = new HttpGet(url); + return execute(httpGet, headers, responseBuilder); + } + + <T> HttpResponse<T> put(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + HttpPut httpPut = new HttpPut(url); + httpPut.setEntity(entity); + return execute(httpPut, headers, responseBuilder); + } + + <T> HttpResponse<T> post(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + HttpPost httpPost = new HttpPost(url); + httpPost.setEntity(entity); + return execute(httpPost, headers, responseBuilder); + } + + <T> HttpResponse<T> patch(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + HttpPatch httpPatch = new HttpPatch(url); + httpPatch.setEntity(entity); + return execute(httpPatch, headers, responseBuilder); + } + + <T> HttpResponse<T> delete(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + HttpDelete httpDelete = new HttpDelete(url); + return execute(httpDelete, headers, responseBuilder); + } + + void close() { + try { + client.close(); + } + catch (IOException e) { + logger.debug("Close http client failed with exception ", e); + } + } + + private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + if(configImmutable.getHeaders() != null) { + configImmutable.getHeaders().forEach((k, v) -> request.addHeader(k, v)); + } + + if (headers != null) { + headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString())); + } + + HttpClientContext httpClientContext = null; + if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) { + httpClientContext = createHttpContext(request.getURI()); + } + + logger.debug("Execute request {}", request.getRequestLine()); + try (CloseableHttpResponse response = client.execute(request, httpClientContext)) { + return responseBuilder.apply(response); + } + catch (Exception e) { + String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); + BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR); + logger.debug("{}: ",description, e); + + throw new HttpExecuteException(description, e); + } + } + + private HttpClientContext createHttpContext(URI uri) { + if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) { + return null; + } + + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + int port = getPort(uri); + credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), + new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword())); + + HttpClientContext localContext = HttpClientContext.create(); + localContext.setCredentialsProvider(credentialsProvider); + + AuthCache authCache = new BasicAuthCache(); + authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme()); + localContext.setAuthCache(authCache); + + return localContext; + } + + private int getPort(URI uri) { + int port = uri.getPort(); + if(port < 0) { + if(Constants.HTTPS.equals(uri.getScheme())) { + port = 443; + } + else + if (Constants.HTTP.equals(uri.getScheme())) { + port = 80; + } + else { + port = AuthScope.ANY_PORT; + logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port); + } + } + return port; + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java new file mode 100644 index 0000000000..bfd3b473b4 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java @@ -0,0 +1,154 @@ +package org.openecomp.sdc.common.http.client.api; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.common.http.config.BasicAuthorization; +import org.openecomp.sdc.common.http.config.ClientCertificate; +import org.openecomp.sdc.common.http.config.HttpClientConfig; +import org.openecomp.sdc.common.http.config.Timeouts; + +final class HttpClientConfigImmutable { + + private final Map<String, String> headers; + private final BasicAuthorization basicAuthorization; + private final ClientCertificate clientCertificate; + private final Timeouts timeouts; + /* + * use ComparableHttpRequestRetryHandler.compare instead of default generated equals + */ + private final ComparableHttpRequestRetryHandler retryHandler; + private final int numOfRetries; + + static HttpClientConfigImmutable getOrCreate(HttpClientConfig httpClientConfig) { + // TODO: retrive from a pool if exist, otherwise create new + return new HttpClientConfigImmutable(httpClientConfig); + } + + HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { + timeouts = httpClientConfig.getTimeouts() != null ? new Timeouts(httpClientConfig.getTimeouts()) : null; + basicAuthorization = httpClientConfig.getBasicAuthorization() != null ? new BasicAuthorization(httpClientConfig.getBasicAuthorization()) : null; + clientCertificate = httpClientConfig.getClientCertificate() != null ? new ClientCertificate(httpClientConfig.getClientCertificate()) : null; + headers = httpClientConfig.getHeaders() != null ? Collections.unmodifiableMap(new HashMap<>(httpClientConfig.getHeaders())) : null; + retryHandler = httpClientConfig.getRetryHandler(); + numOfRetries = httpClientConfig.getNumOfRetries(); + } + + Map<String, String> getHeaders() { + return headers; + } + + int getNumOfRetries() { + return numOfRetries; + } + + String getBasicAuthPassword() { + return basicAuthorization != null ? basicAuthorization.getPassword() : null; + } + + String getBasicAuthUserName() { + return basicAuthorization != null ? basicAuthorization.getUserName() : null; + } + + String getClientCertKeyStore() { + return clientCertificate != null ? clientCertificate.getKeyStore() : null; + } + + String getClientCertKeyPassword() { + return clientCertificate != null ? clientCertificate.getKeyStorePassword() : null; + } + + ClientCertificate getClientCertificate() { + return clientCertificate != null ? new ClientCertificate(clientCertificate) : null; + } + + int getReadTimeoutMs() { + return timeouts.getReadTimeoutMs(); + } + + int getConnectTimeoutMs() { + return timeouts.getConnectTimeoutMs(); + } + + int getConnectPoolTimeoutMs() { + return timeouts.getConnectPoolTimeoutMs(); + } + + ComparableHttpRequestRetryHandler getRetryHandler() { + return retryHandler; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((basicAuthorization == null) ? 0 : basicAuthorization.hashCode()); + result = prime * result + ((clientCertificate == null) ? 0 : clientCertificate.hashCode()); + result = prime * result + ((headers == null) ? 0 : headers.hashCode()); + result = prime * result + ((retryHandler == null) ? 0 : retryHandler.hashCode()); + result = prime * result + ((timeouts == null) ? 0 : timeouts.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + HttpClientConfigImmutable other = (HttpClientConfigImmutable) obj; + if (basicAuthorization == null) { + if (other.basicAuthorization != null) + return false; + } + else if (!basicAuthorization.equals(other.basicAuthorization)) + return false; + if (clientCertificate == null) { + if (other.clientCertificate != null) + return false; + } + else if (!clientCertificate.equals(other.clientCertificate)) + return false; + if (headers == null) { + if (other.headers != null) + return false; + } + else if (!headers.equals(other.headers)) + return false; + if (retryHandler == null) { + if (other.retryHandler != null) + return false; + } + else if (!retryHandler.compare(other.retryHandler)) + return false; + if (timeouts == null) { + if (other.timeouts != null) + return false; + } + else if (!timeouts.equals(other.timeouts)) + return false; + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HttpClientConfigImmutable [basicAuthorization="); + builder.append(basicAuthorization); + builder.append(", clientCertificate="); + builder.append(clientCertificate); + builder.append(", retryHandler="); + builder.append(retryHandler); + builder.append(", timeouts="); + builder.append(timeouts); + builder.append(", headers="); + builder.append(headers); + builder.append(", numOfRetries="); + builder.append(numOfRetries); + builder.append("]"); + return builder.toString(); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java new file mode 100644 index 0000000000..c52880cb96 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java @@ -0,0 +1,51 @@ +package org.openecomp.sdc.common.http.client.api; + +import org.apache.http.client.HttpRequestRetryHandler; +import org.apache.http.client.UserTokenHandler; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.http.config.ClientCertificate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpClientFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientFactory.class); + private static final UserTokenHandler userTokenHandler = context -> null; + private final HttpConnectionMngFactory connectionMngFactory; + + HttpClientFactory(HttpConnectionMngFactory connectionMngFactory) { + this.connectionMngFactory = connectionMngFactory; + } + + HttpClient createClient(String protocol, HttpClientConfigImmutable config) { + LOGGER.debug("Create {} client based on {}", protocol, config); + + ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; + HttpClientConnectionManager connectionManager = connectionMngFactory.getOrCreate(clientCertificate); + RequestConfig requestConfig = createClientTimeoutConfiguration(config); + CloseableHttpClient client = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .setConnectionManager(connectionManager) + .setUserTokenHandler(userTokenHandler) + .setRetryHandler(resolveRetryHandler(config)) + .build(); + + return new HttpClient(client, config); + } + + private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) { + return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null; + } + + private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) { + return RequestConfig.custom() + .setConnectTimeout(config.getConnectTimeoutMs()) + .setSocketTimeout(config.getReadTimeoutMs()) + .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs()) + .build(); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java new file mode 100644 index 0000000000..6a408c92cd --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java @@ -0,0 +1,117 @@ +package org.openecomp.sdc.common.http.client.api; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContextBuilder; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.http.config.ClientCertificate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpConnectionMngFactory { + + private static final String P12_KEYSTORE_EXTENTION = ".p12"; + private static final String PFX_KEYSTORE_EXTENTION = ".pfx"; + private static final String JKS_KEYSTORE_EXTENTION = ".jks"; + + private static final String P12_KEYSTORE_TYPE = "pkcs12"; + private static final String JKS_KEYSTORE_TYPE = "jks"; + + private static final Logger logger = LoggerFactory.getLogger(HttpConnectionMngFactory.class); + private static final int DEFAULT_CONNECTION_POOL_SIZE = 30; + private static final int DEFAULT_MAX_CONNECTION_PER_ROUTE = 5; + private static final int VALIDATE_CONNECTION_AFTER_INACTIVITY_MS = 10000; + + private Map<ClientCertificate, HttpClientConnectionManager> sslClientConnectionManagers = new ConcurrentHashMap<>(); + private HttpClientConnectionManager plainClientConnectionManager; + + HttpConnectionMngFactory() { + plainClientConnectionManager = createConnectionMng(null); + } + + HttpClientConnectionManager getOrCreate(ClientCertificate clientCertificate) { + if(clientCertificate == null) { + return plainClientConnectionManager; + } + return sslClientConnectionManagers.computeIfAbsent(clientCertificate, k -> createConnectionMng(clientCertificate)); + } + + private HttpClientConnectionManager createConnectionMng(ClientCertificate clientCertificate) { + + SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); + SSLConnectionSocketFactory sslsf = null; + try { + sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy()); + + if(clientCertificate != null) { + setClientSsl(clientCertificate, sslContextBuilder); + } + sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE); + } + catch (GeneralSecurityException e) { + logger.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); + sslsf = SSLConnectionSocketFactory.getSocketFactory(); + } + + Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() + .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory()) + .register(Constants.HTTPS, sslsf).build(); + + PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry); + + manager.setMaxTotal(DEFAULT_CONNECTION_POOL_SIZE); + manager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION_PER_ROUTE); + manager.setValidateAfterInactivity(VALIDATE_CONNECTION_AFTER_INACTIVITY_MS); + + return manager; + } + + private void setClientSsl(ClientCertificate clientCertificate, SSLContextBuilder sslContextBuilder) { + try { + char[] keyStorePassword = clientCertificate.getKeyStorePassword().toCharArray(); + KeyStore clientKeyStore = createClientKeyStore(clientCertificate.getKeyStore(), keyStorePassword); + sslContextBuilder.loadKeyMaterial(clientKeyStore, keyStorePassword); + logger.debug("#setClientSsl - Set Client Certificate authentication"); + } + catch (IOException | GeneralSecurityException e) { + logger.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e); + } + } + + private KeyStore createClientKeyStore(String keyStorePath, char[] keyStorePassword) throws IOException, GeneralSecurityException { + KeyStore keyStore = null; + try (InputStream stream = new FileInputStream(keyStorePath)) { + keyStore = KeyStore.getInstance(getKeyStoreType(keyStorePath)); + keyStore.load(stream, keyStorePassword); + } + return keyStore; + } + + private String getKeyStoreType(String keyStore) { + if(!StringUtils.isEmpty(keyStore)) { + if(keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) { + return P12_KEYSTORE_TYPE; + } + else if(keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) { + return JKS_KEYSTORE_TYPE; + } + } + return KeyStore.getDefaultType(); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java new file mode 100644 index 0000000000..6f3638ef2d --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.common.http.client.api; + +public class HttpExecuteException extends Exception { + + private static final long serialVersionUID = 1L; + + public HttpExecuteException(String message) { + super (message); + } + + public HttpExecuteException(String message, Throwable cause) { + super (message, cause); + } + + public HttpExecuteException(Throwable cause) { + super(cause); + } + + @Override + public Throwable getCause() { + Throwable cause = super.getCause(); + return cause != null ? cause : this; + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java new file mode 100644 index 0000000000..57911144a1 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java @@ -0,0 +1,136 @@ +package org.openecomp.sdc.common.http.client.api; + +import org.apache.http.HttpEntity; +import org.openecomp.sdc.common.http.config.HttpClientConfig; + +import java.util.Properties; + +//TODO- remove all static and use instance methods for better testing +public abstract class HttpRequest { + + static final Properties defaultHeaders = null; + static final HttpClientConfig defaultConfig = new HttpClientConfig(); + + + + private HttpRequest() { + } + + /* + * GET response as string + */ + public static HttpResponse<String> get(String url) throws HttpExecuteException { + return get(url, defaultHeaders, defaultConfig); + } + + public static HttpResponse<String> get(String url, Properties headers) throws HttpExecuteException { + return get(url, headers, defaultConfig); + } + + public static HttpResponse<String> get(String url, HttpClientConfig config) throws HttpExecuteException { + return get(url, defaultHeaders, config); + } + + public static HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + return HttpRequestHandler.get().get(url, headers, config); + } + + /* + * GET response as byte array + */ + public static HttpResponse<byte[]> getAsByteArray(String url) throws HttpExecuteException { + return getAsByteArray(url, defaultHeaders, defaultConfig); + } + + public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers) throws HttpExecuteException { + return getAsByteArray(url, headers, defaultConfig); + } + + public static HttpResponse<byte[]> getAsByteArray(String url, HttpClientConfig config) throws HttpExecuteException { + return getAsByteArray(url, defaultHeaders, config); + } + + public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + return HttpRequestHandler.get().getAsByteArray(url, headers, config); + } + + /* + * PUT + */ + public static HttpResponse<String> put(String url, HttpEntity entity) throws HttpExecuteException { + return put(url, defaultHeaders, entity, defaultConfig); + } + + public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { + return put(url, headers, entity, defaultConfig); + } + + public static HttpResponse<String> put(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + return put(url, defaultHeaders, entity, config); + } + + public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + return HttpRequestHandler.get().put(url, headers, entity, config); + } + + /* + * POST + */ + public static HttpResponse<String> post(String url, HttpEntity entity) throws HttpExecuteException { + return post(url, defaultHeaders, entity, defaultConfig); + } + + public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { + return post(url, headers, entity, defaultConfig); + } + + public static HttpResponse<String> post(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + return post(url, defaultHeaders, entity, config); + } + + public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + return HttpRequestHandler.get().post(url, headers, entity, config); + } + + /* + * PATCH + */ + public static HttpResponse<String> patch(String url, HttpEntity entity) throws HttpExecuteException { + return patch(url, defaultHeaders, entity, defaultConfig); + } + + public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { + return patch(url, headers, entity, defaultConfig); + } + + public static HttpResponse<String> patch(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + return patch(url, defaultHeaders, entity, config); + } + + public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + return HttpRequestHandler.get().patch(url, headers, entity, config); + } + + /* + * DELETE + */ + public static HttpResponse<String> delete(String url) throws HttpExecuteException { + return delete(url, defaultHeaders, defaultConfig); + } + + public static HttpResponse<String> delete(String url, Properties headers) throws HttpExecuteException { + return delete(url, headers, defaultConfig); + } + + public static HttpResponse<String> delete(String url, HttpClientConfig config) throws HttpExecuteException { + return delete(url, defaultHeaders, config); + } + + public static HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + return HttpRequestHandler.get().delete(url, headers, config); + } + + public static void destroy() { + HttpRequestHandler.get().destroy(); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java new file mode 100644 index 0000000000..5722fc9c4e --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java @@ -0,0 +1,114 @@ +package org.openecomp.sdc.common.http.client.api; + +import java.io.InputStream; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.util.EntityUtils; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows; +import org.openecomp.sdc.common.http.config.HttpClientConfig; + +public enum HttpRequestHandler { + HANDLER; + private static final String HTTPS_PREFIX = "https://"; + private static final String HTTP_PREFIX = "http://"; + + private Map<HttpClientConfigImmutable, HttpClient> clients = new ConcurrentHashMap<>(); + private HttpClientFactory clientFactory; + + private FunctionThrows<CloseableHttpResponse, HttpResponse<byte[]>, Exception> byteResponseBuilder = (CloseableHttpResponse httpResponse) -> { + HttpEntity entity = httpResponse.getEntity(); + byte[] response = null; + if (entity != null) { + InputStream content = entity.getContent(); + if (content != null) { + response = IOUtils.toByteArray(content); + } + } + return new HttpResponse<>(response, + httpResponse.getStatusLine().getStatusCode(), + httpResponse.getStatusLine().getReasonPhrase()); + }; + + private FunctionThrows<CloseableHttpResponse, HttpResponse<String>, Exception> stringResponseBuilder = (CloseableHttpResponse httpResponse) -> { + HttpEntity entity = httpResponse.getEntity(); + String response = null; + if (entity != null) { + response = EntityUtils.toString(entity); + } + return new HttpResponse<>(response, + httpResponse.getStatusLine().getStatusCode(), + httpResponse.getStatusLine().getReasonPhrase()); + }; + + HttpRequestHandler() { + HttpConnectionMngFactory connectionMngFactory = new HttpConnectionMngFactory(); + clientFactory = new HttpClientFactory(connectionMngFactory); + } + + static HttpRequestHandler get() { + return HANDLER; + } + + public HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + HttpClient client = getOrCreateClient(url, config); + return client.<String>get(url, headers, stringResponseBuilder); + } + + public HttpResponse<byte []> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + HttpClient client = getOrCreateClient(url, config); + return client.<byte[]>get(url, headers, byteResponseBuilder); + } + + public HttpResponse<String> put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + HttpClient client = getOrCreateClient(url, config); + return client.<String>put(url, headers, entity, stringResponseBuilder); + } + + public HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + HttpClient client = getOrCreateClient(url, config); + return client.<String>post(url, headers, entity, stringResponseBuilder); + } + + public HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { + HttpClient client = getOrCreateClient(url, config); + return client.<String>patch(url, headers, entity, stringResponseBuilder); + } + + public HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.defaultConfig); + return client.<String>delete(url, headers, stringResponseBuilder); + } + + public void destroy() { + clients.forEach((k, v) -> v.close()); + clients.clear(); + } + + private HttpClient getOrCreateClient(String url, HttpClientConfig config) throws HttpExecuteException { + String protocol = getProtocol(url); + HttpClientConfigImmutable httpClientConfigImmutable = HttpClientConfigImmutable.getOrCreate(config); + return clients.computeIfAbsent(httpClientConfigImmutable, k -> createClient(protocol, httpClientConfigImmutable)); + } + + private HttpClient createClient(String protocol, HttpClientConfigImmutable config) { + return clientFactory.createClient(protocol, config); + } + + private String getProtocol(String url) throws HttpExecuteException { + if (url.startsWith(HTTPS_PREFIX)) { + return Constants.HTTPS; + } + else if (url.startsWith(HTTP_PREFIX)) { + return Constants.HTTP; + } + else { + throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url)); + } + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java new file mode 100644 index 0000000000..c67345c813 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java @@ -0,0 +1,48 @@ +package org.openecomp.sdc.common.http.client.api; + +import org.apache.commons.lang3.StringUtils; + +public class HttpResponse<T> { + private final T response; + private final int statusCode; + private final String description; + + public HttpResponse(T response, int statusCode) { + this.response = response; + this.statusCode = statusCode; + this.description = StringUtils.EMPTY; + } + + public HttpResponse(T response, int statusCode, String description) { + this.response = response; + this.statusCode = statusCode; + this.description = description; + } + + public T getResponse() { + return response; + } + + public int getStatusCode() { + return statusCode; + } + + public String getDescription() { + return description; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HttpResponse [response="); + builder.append(response); + builder.append(", statusCode="); + builder.append(statusCode); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } + + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java new file mode 100644 index 0000000000..6f34f80071 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java @@ -0,0 +1,10 @@ +package org.openecomp.sdc.common.http.client.api; + +import org.apache.http.HttpStatus; + +public final class Responses { + public static final HttpResponse<String> INTERNAL_SERVER_ERROR = new HttpResponse<>("Internal server error", HttpStatus.SC_INTERNAL_SERVER_ERROR); + + private Responses() { + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java new file mode 100644 index 0000000000..7776c53035 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.common.http.client.api; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; + +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class RestUtils { + + public static void addBasicAuthHeader(Properties headers, String username, String password) { + byte[] credentials = Base64.encodeBase64((username + ":" + password).getBytes(StandardCharsets.UTF_8)); + headers.setProperty(HttpHeaders.AUTHORIZATION, "Basic " + new String(credentials, StandardCharsets.UTF_8)); + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java new file mode 100644 index 0000000000..3e3b61f0f1 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.common.http.client.api; + +import org.apache.http.protocol.HttpContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public class RetryHandlers { + + private static final Logger LOGGER = LoggerFactory.getLogger(RetryHandlers.class); + + private RetryHandlers(){} + + public static ComparableHttpRequestRetryHandler getDefault(int numOfRetries) { + return (IOException exception, int executionCount, HttpContext context) -> { + LOGGER.debug("failed sending request with exception", exception); + LOGGER.debug("try request number: {}", executionCount); + return executionCount <= numOfRetries; + }; + } + + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java new file mode 100644 index 0000000000..4fb8fadce4 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.common.http.config; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.security.SecurityUtil; + +import fj.data.Either; + +public class BasicAuthorization { + private String userName; + private String password; + + public BasicAuthorization() { + } + + public BasicAuthorization(BasicAuthorization basicAuthorization) { + setUserName(basicAuthorization.userName); + setPassword(basicAuthorization.password, false); + } + + public void setUserName(String userName) { + validate(userName); + this.userName = userName; + } + + public void setPassword(String password) { + setPassword(password, true); + } + + public String getUserName() { + return userName; + } + + public String getPassword() { + return password; + } + + + private void setPassword(String password, boolean isEncoded) { + validate(password); + if(isEncoded) { + Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(password); + if(passkey.isLeft()) { + this.password = passkey.left().value(); + } + else { + throw new IllegalArgumentException(passkey.right().value()); + } + } + else { + this.password = password; + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((password == null) ? 0 : password.hashCode()); + result = prime * result + ((userName == null) ? 0 : userName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BasicAuthorization other = (BasicAuthorization) obj; + if (password == null) { + if (other.password != null) + return false; + } + else if (!password.equals(other.password)) + return false; + if (userName == null) { + if (other.userName != null) + return false; + } + else if (!userName.equals(other.userName)) + return false; + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("BasicAuthentication [userName="); + builder.append(userName); + builder.append("]"); + return builder.toString(); + } + + private void validate(String str) { + if(StringUtils.isEmpty(str)) { + throw new IllegalArgumentException("BasicAuthorization username and/or password cannot be empty"); + } + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java new file mode 100644 index 0000000000..972a4178e0 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java @@ -0,0 +1,100 @@ +package org.openecomp.sdc.common.http.config; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.security.SecurityUtil; + +import fj.data.Either; + +public class ClientCertificate { + private String keyStore; + private String keyStorePassword; + + public ClientCertificate() { + } + + public ClientCertificate(ClientCertificate clientCertificate) { + setKeyStore(clientCertificate.getKeyStore()); + setKeyStorePassword(clientCertificate.getKeyStorePassword(), false); + } + + public void setKeyStore(String keyStore) { + validate(keyStore); + this.keyStore = keyStore; + } + + public void setKeyStorePassword(String keyStorePassword) { + setKeyStorePassword(keyStorePassword, true); + } + + private void setKeyStorePassword(String keyStorePassword, boolean isEncoded) { + validate(keyStorePassword); + if(isEncoded) { + Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(keyStorePassword); + if (passkey.isLeft()) { + this.keyStorePassword = passkey.left().value(); + } + else { + throw new IllegalArgumentException(passkey.right().value()); + } + } + else { + this.keyStorePassword = keyStorePassword; + } + } + + public String getKeyStore() { + return keyStore; + } + + public String getKeyStorePassword() { + return keyStorePassword; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((keyStore == null) ? 0 : keyStore.hashCode()); + result = prime * result + ((keyStorePassword == null) ? 0 : keyStorePassword.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ClientCertificate other = (ClientCertificate) obj; + if (keyStore == null) { + if (other.keyStore != null) + return false; + } + else if (!keyStore.equals(other.keyStore)) + return false; + if (keyStorePassword == null) { + if (other.keyStorePassword != null) + return false; + } + else if (!keyStorePassword.equals(other.keyStorePassword)) + return false; + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ClientCertificate [keyStore="); + builder.append(keyStore); + builder.append("]"); + return builder.toString(); + } + + private void validate(String str) { + if(StringUtils.isEmpty(str)) { + throw new IllegalArgumentException("ClientCertificate keystore and/or kestorePassword cannot be empty"); + } + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java new file mode 100644 index 0000000000..d1e1733565 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.common.http.config; + +public class ExternalServiceConfig { + + private HttpRequestConfig httpRequestConfig; + private HttpClientConfig httpClientConfig; + + public HttpRequestConfig getHttpRequestConfig() { + return httpRequestConfig; + } + + public void setHttpRequestConfig(HttpRequestConfig httpRequestConfig) { + this.httpRequestConfig = httpRequestConfig; + } + + public HttpClientConfig getHttpClientConfig() { + return httpClientConfig; + } + + public void setHttpClientConfig(HttpClientConfig httpClientConfig) { + this.httpClientConfig = httpClientConfig; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ExternalServiceConfig [httpRequestConfig="); + builder.append(httpRequestConfig); + builder.append(", httpClientConfig="); + builder.append(httpClientConfig); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java new file mode 100644 index 0000000000..69789957b4 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java @@ -0,0 +1,99 @@ +package org.openecomp.sdc.common.http.config; + +import java.util.Map; + +import org.openecomp.sdc.common.http.client.api.ComparableHttpRequestRetryHandler; + +public class HttpClientConfig { + + private BasicAuthorization basicAuthorization; + private ClientCertificate clientCertificate; + private ComparableHttpRequestRetryHandler retryHandler; + private Timeouts timeouts = Timeouts.DEFAULT; + private Map<String, String> headers; + private int numOfRetries; + + public HttpClientConfig() { + } + + public HttpClientConfig(Timeouts timeouts) { + setTimeouts(timeouts); + } + + public HttpClientConfig(Timeouts timeouts, ClientCertificate clientCertificate) { + setTimeouts(timeouts); + setClientCertificate(clientCertificate); + } + + public HttpClientConfig(Timeouts timeouts, BasicAuthorization basicAuthorization) { + setTimeouts(timeouts); + setBasicAuthorization(basicAuthorization); + } + + public ComparableHttpRequestRetryHandler getRetryHandler() { + return retryHandler; + } + + public void setRetryHandler(ComparableHttpRequestRetryHandler retryHandler) { + this.retryHandler = retryHandler; + } + + public Timeouts getTimeouts() { + return timeouts; + } + + public void setTimeouts(Timeouts timeouts) { + this.timeouts = timeouts; + } + + public BasicAuthorization getBasicAuthorization() { + return basicAuthorization; + } + + public void setBasicAuthorization(BasicAuthorization basicAuthorization) { + this.basicAuthorization = basicAuthorization; + } + + public ClientCertificate getClientCertificate() { + return clientCertificate; + } + + public void setClientCertificate(ClientCertificate clientCertificate) { + this.clientCertificate = clientCertificate; + } + + public Map<String, String> getHeaders() { + return headers; + } + + public void setHeaders(Map<String, String> headers) { + this.headers = headers; + } + + public int getNumOfRetries() { + return numOfRetries; + } + + public void setNumOfRetries(int numOfRetries) { + this.numOfRetries = numOfRetries; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HttpClientConfig [basicAuthorization="); + builder.append(basicAuthorization); + builder.append(", clientCertificate="); + builder.append(clientCertificate); + builder.append(", retryHandler="); + builder.append(retryHandler); + builder.append(", timeouts="); + builder.append(timeouts); + builder.append(", headers="); + builder.append(headers); + builder.append(", numOfRetries="); + builder.append(numOfRetries); + builder.append("]"); + return builder.toString(); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java new file mode 100644 index 0000000000..8ea8e1f600 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java @@ -0,0 +1,40 @@ +package org.openecomp.sdc.common.http.config; + +import java.util.HashMap; +import java.util.Map; + +public class HttpRequestConfig { + + private String serverRootUrl; + private Map<String, String> resourceNamespaces; + + public String getServerRootUrl() { + return serverRootUrl; + } + + public void setServerRootUrl(String serverRootUrl) { + this.serverRootUrl = serverRootUrl; + } + + public Map<String, String> getResourceNamespaces() { + if(resourceNamespaces == null) { + resourceNamespaces = new HashMap<>(); + } + return resourceNamespaces; + } + + public void setResourceNamespaces(Map<String, String> resourceNamespaces) { + this.resourceNamespaces = resourceNamespaces; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HttpRequestConfig [serverRootUrl="); + builder.append(serverRootUrl); + builder.append(", resourceNamespaces="); + builder.append(resourceNamespaces); + builder.append("]"); + return builder.toString(); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java new file mode 100644 index 0000000000..d759b3eef4 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java @@ -0,0 +1,102 @@ +package org.openecomp.sdc.common.http.config; + +public class Timeouts { + + private static final int DEFAULT_TIMEOUT_MS = 15000; + private int connectTimeoutMs = DEFAULT_TIMEOUT_MS; + private int readTimeoutMs = DEFAULT_TIMEOUT_MS; + private int connectPoolTimeoutMs = DEFAULT_TIMEOUT_MS; + + public static final Timeouts DEFAULT; + static { + DEFAULT = new Timeouts(); + } + + private Timeouts() { + } + + public Timeouts(int connectTimeoutMs, int readTimeoutMs) { + setConnectTimeoutMs(connectTimeoutMs); + setReadTimeoutMs(readTimeoutMs); + } + + public Timeouts(Timeouts timeouts) { + setReadTimeoutMs(timeouts.readTimeoutMs); + setConnectTimeoutMs(timeouts.connectTimeoutMs); + setConnectPoolTimeoutMs(timeouts.connectPoolTimeoutMs); + } + + public int getConnectTimeoutMs() { + return connectTimeoutMs; + } + + public void setConnectTimeoutMs(int connectTimeoutMs) { + validate(connectTimeoutMs); + this.connectTimeoutMs = connectTimeoutMs; + } + + public int getReadTimeoutMs() { + return readTimeoutMs; + } + + public void setReadTimeoutMs(int readTimeoutMs) { + validate(readTimeoutMs); + this.readTimeoutMs = readTimeoutMs; + } + + public int getConnectPoolTimeoutMs() { + return connectPoolTimeoutMs; + } + + public void setConnectPoolTimeoutMs(int connectPoolTimeoutMs) { + validate(connectPoolTimeoutMs); + this.connectPoolTimeoutMs = connectPoolTimeoutMs; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + connectPoolTimeoutMs; + result = prime * result + connectTimeoutMs; + result = prime * result + readTimeoutMs; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Timeouts other = (Timeouts) obj; + if (connectPoolTimeoutMs != other.connectPoolTimeoutMs) + return false; + if (connectTimeoutMs != other.connectTimeoutMs) + return false; + if (readTimeoutMs != other.readTimeoutMs) + return false; + return true; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Timeouts [connectTimeoutMs="); + builder.append(connectTimeoutMs); + builder.append(", readTimeoutMs="); + builder.append(readTimeoutMs); + builder.append(", connectPoolTimeoutMs="); + builder.append(connectPoolTimeoutMs); + builder.append("]"); + return builder.toString(); + } + + private void validate(int timeout) { + if(timeout <= 0) { + throw new IllegalArgumentException("Timeout values cannot be less than zero"); + } + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/IRestClient.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/IRestClient.java deleted file mode 100644 index 8deb3d7d64..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/IRestClient.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.rest.api; - -import java.util.Properties; - -/** - * This interface describe the methods of the REST generic client. Each method - * will receive the destination URI and specific list of headers. With this - * information the REST Client will create a request to the specific REST Web - * server. Error from the REST Web server will be return by proprietary - * exception object. - * - * @author esofer - * - */ -public interface IRestClient { - - /** - * This method will return resource according to the given URI. - * - * @param uri - * Full URL path to the desire resource. - * @param headers - * - list of headers in format of name and value, to be add as - * part of the HTTP request. - * @return JSON representation of the requested resource. - */ - public RestResponse doGET(String uri, Properties headers); - - /** - * This method will CREATE resource according to the given URI. - * - * @param uri - * Full URL path to the desire resource. - * @param headers - * - list of headers in format of name and value, to be add as - * part of the HTTP request. - * @param objectToCreate - * - JSON representation of the resource. - */ - public RestResponse doPOST(String uri, Properties headers, Object objectToCreate); - - /** - * This method will UPDATE resource according to the given URI. - * - * @param uri - * Full URL path to the desire resource. - * @param headers - * - list of headers in format of name and value, to be add as - * part of the HTTP request. - * @param objectToUpdate - * - JSON representation of the resource. - */ - public RestResponse doPUT(String uri, Properties headers, Object objectToUpdate); - - /** - * This method will return resource according to the given URI. - * - * @param uri - * Full URL path to the desire resource. - * @param headers - * - list of headers in format of name and value, to be add as - * part of the HTTP request. - * - */ - public RestResponse doDELETE(String uri, Properties headers); - - /** - * initialize the rest client instance. The timeout is infinite. - */ - public boolean init() throws Exception; - - /** - * initialize the rest client instance with a given timeout in milliseconds. - * - * @param restConfigurationInfo - */ - public boolean init(RestConfigurationInfo restConfigurationInfo); - - /** - * destroy the connections - */ - public void destroy(); -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java deleted file mode 100644 index 6f652cc8a4..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.rest.api; - -public class RestClientServiceExeption extends Exception { - - private static final long serialVersionUID = 8258477052369440242L; - - /** - * Default Constructor. - */ - public RestClientServiceExeption() { - super(); - } - - /** - * Constructor. - * - * @param msg - * String - */ - public RestClientServiceExeption(String msg) { - super(msg); - } - - /** - * Constructor. - * - * @param cause - * Throwable - */ - public RestClientServiceExeption(Throwable cause) { - super(cause); - } - - /** - * Constructor. - * - * @param msg - * String - * @param cause - * Throwable - */ - public RestClientServiceExeption(String msg, Throwable cause) { - super(msg, cause); - } - - /** - * - * @param response - * - * public RSClientServiceExeption(ClientResponse response) { super(); this.response = response; } - * - * public ClientResponse getResponse() { return response; } - * - * public void setResponse(ClientResponse response) { this.response = response; } - */ -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponse.java deleted file mode 100644 index b08cf7332b..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponse.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.rest.api; - -public class RestResponse { - - private String response; - - private String statusDescription; - - private int httpStatusCode = 0; - - public RestResponse(String response, String statusDescription, int httpStatusCode) { - super(); - this.response = response; - this.statusDescription = statusDescription; - this.httpStatusCode = httpStatusCode; - } - - /** - * @return the response - */ - public String getResponse() { - return response; - } - - /** - * @param response - * the response to set - */ - public void setResponse(String response) { - this.response = response; - } - - /** - * @return the httpStatusCode - */ - public int getHttpStatusCode() { - return httpStatusCode; - } - - /** - * @param httpStatusCode - * the httpStatusCode to set - */ - public void setHttpStatusCode(int httpStatusCode) { - this.httpStatusCode = httpStatusCode; - } - - /** - * @return the statusDescription - */ - public String getStatusDescription() { - return statusDescription; - } - - /** - * @param statusDescription - * the statusDescription to set - */ - public void setStatusDescription(String statusDescription) { - this.statusDescription = statusDescription; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - * - * ERROR: Error from Rest Server:Status: 400 Message: Bad Request Body: - * Invalid cell: Cell with cell name dmgrCell22 does not exist! - * - */ - public String toString() { - - StringBuilder stringBuilder = new StringBuilder(); - - stringBuilder.append("Status: "); - stringBuilder.append(httpStatusCode); - stringBuilder.append("\n"); - stringBuilder.append("Message: "); - stringBuilder.append(statusDescription); - stringBuilder.append("\n"); - stringBuilder.append("Body: "); - stringBuilder.append(response); - - return stringBuilder.toString(); - - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArray.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArray.java deleted file mode 100644 index 7a4d8ee4cb..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArray.java +++ /dev/null @@ -1,133 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.rest.api; - -import java.util.Arrays; - -import org.apache.http.HttpStatus; - -public class RestResponseAsByteArray { - - private byte[] response; - - private String statusDescription; - - private int httpStatusCode = 0; - - public RestResponseAsByteArray(byte[] response, String statusDescription, int httpStatusCode) { - super(); - this.response = response; - this.statusDescription = statusDescription; - this.httpStatusCode = httpStatusCode; - } - - /** - * @return the response - */ - public byte[] getResponse() { - return response; - } - - /** - * @param response - * the response to set - */ - public void setResponse(byte[] response) { - this.response = response; - } - - /** - * @return the httpStatusCode - */ - public int getHttpStatusCode() { - return httpStatusCode; - } - - /** - * @param httpStatusCode - * the httpStatusCode to set - */ - public void setHttpStatusCode(int httpStatusCode) { - this.httpStatusCode = httpStatusCode; - } - - /** - * @return the statusDescription - */ - public String getStatusDescription() { - return statusDescription; - } - - /** - * @param statusDescription - * the statusDescription to set - */ - public void setStatusDescription(String statusDescription) { - this.statusDescription = statusDescription; - } - - public String toString() { - - StringBuilder stringBuilder = new StringBuilder(); - - stringBuilder.append("Status: "); - stringBuilder.append(httpStatusCode); - stringBuilder.append("\n"); - stringBuilder.append("Message: "); - stringBuilder.append(statusDescription); - stringBuilder.append("\n"); - stringBuilder.append("Body length: "); - stringBuilder.append(response == null ? 0 : response.length); - - return stringBuilder.toString(); - - } - - public String toPrettyString() { - - int maxBytesToDisplay = 200; - - StringBuilder stringBuilder = new StringBuilder(); - - stringBuilder.append("Status: "); - stringBuilder.append(httpStatusCode); - stringBuilder.append("\n"); - stringBuilder.append("Message: "); - stringBuilder.append(statusDescription); - stringBuilder.append("\n"); - if (httpStatusCode != HttpStatus.SC_OK) { - stringBuilder.append("Body(maximum " + maxBytesToDisplay + " bytes): "); - if (response != null) { - byte[] subArray = Arrays.copyOfRange(response, 0, Math.min(maxBytesToDisplay, response.length)); - if (subArray != null && subArray.length > 0) { - String responseStr = new String(subArray); - stringBuilder.append(responseStr); - } - } - } else { - stringBuilder.append("Body length: "); - stringBuilder.append(response == null ? 0 : response.length); - } - - return stringBuilder.toString(); - - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java deleted file mode 100644 index eed083ab68..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java +++ /dev/null @@ -1,427 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.rest.impl; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.Map.Entry; -import java.util.Properties; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; - -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.HeaderElement; -import org.apache.http.HeaderElementIterator; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.message.BasicHeaderElementIterator; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.EntityUtils; -import org.openecomp.sdc.common.rest.api.IRestClient; -import org.openecomp.sdc.common.rest.api.RestClientServiceExeption; -import org.openecomp.sdc.common.rest.api.RestConfigurationInfo; -import org.openecomp.sdc.common.rest.api.RestResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HttpRestClientServiceImpl implements IRestClient { - - private Logger log = LoggerFactory.getLogger(HttpRestClientServiceImpl.class.getName()); - - public final static int DEFAULT_CONNECTION_POOL_SIZE = 10; - - public final static int DEFAULT_CONNECT_TIMEOUT = 10; - - private DefaultHttpClient httpClient; - - private SSLSocketFactory sslFactory; - - private Logger logger = LoggerFactory.getLogger(HttpRestClientServiceImpl.class.getName()); - - PoolingClientConnectionManager cm = null; - - public boolean init() { - - return init(new RestConfigurationInfo()); - - } - - public boolean init(RestConfigurationInfo restConfigurationInfo) { - - boolean initialized = false; - - logger.debug("HttpRestClientServiceImpl::init - start. restConfigurationInfo= {}", restConfigurationInfo); - - try { - createHttpClient(restConfigurationInfo); - - initialized = true; - } catch (KeyManagementException e) { - String msg = "Failed creating client config for rest. " + e.getMessage(); - logger.error(msg, e); - // throw new RestClientServiceExeption(e.getMessage()); - } catch (NoSuchAlgorithmException e) { - String msg = "Failed creating client config for rest. " + e.getMessage(); - logger.error(msg, e); - // throw new RestClientServiceExeption(msg); - } - - logger.debug("HttpRestClientServiceImpl::init - finish successfully"); - - return initialized; - } - - public void destroy() { - - if (this.httpClient != null) { - this.httpClient.getConnectionManager().shutdown(); - logger.info("After closing connection Manager of rest Client."); - } - - } - - private void createHttpClient(RestConfigurationInfo restConfigurationInfo) throws KeyManagementException, NoSuchAlgorithmException { - - PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); - - Integer connPoolSizeObj = restConfigurationInfo.getConnectionPoolSize(); - int connPoolSize = DEFAULT_CONNECTION_POOL_SIZE; - if (connPoolSizeObj != null) { - connPoolSize = connPoolSizeObj.intValue(); - if (connPoolSize <= 0) { - connPoolSize = DEFAULT_CONNECTION_POOL_SIZE; - } - } - cm.setMaxTotal(connPoolSize); - - this.httpClient = new DefaultHttpClient(cm); - - int timeoutInSec = restConfigurationInfo.getReadTimeoutInSec() == null ? 0 : restConfigurationInfo.getReadTimeoutInSec(); - int connectTimeoutInSec = restConfigurationInfo.getConnectTimeoutInSec() == null ? DEFAULT_CONNECT_TIMEOUT : restConfigurationInfo.getConnectTimeoutInSec(); - HttpParams params = new BasicHttpParams(); - params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutInSec * 1000); - params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutInSec * 1000); - - this.httpClient.setParams(params); - - Boolean ignoreCertificateObj = restConfigurationInfo.getIgnoreCertificate(); - boolean ignoreCertificate = false; - if (ignoreCertificateObj != null) { - ignoreCertificate = ignoreCertificateObj.booleanValue(); - } - if (ignoreCertificate == true) { - - this.sslFactory = createSSLSocketFactory(); - - Scheme scheme = new Scheme("https", 9443, sslFactory); - this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme); - } - - // addKeepAlive(); - - this.cm = cm; - } - - private void addKeepAlive() { - - this.httpClient.setReuseStrategy(new ConnectionReuseStrategy() { - - public boolean keepAlive(HttpResponse response, HttpContext context) { - // TODO Auto-generated method stub - return true; - } - - }); - - this.httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { - - public long getKeepAliveDuration(HttpResponse response, HttpContext context) { - log.debug("============ In getKeepAliveDuration ================= "); - - HeaderIterator headerIterator = response.headerIterator(HTTP.CONN_KEEP_ALIVE); - if (headerIterator != null) { - HeaderElementIterator it = new BasicHeaderElementIterator(headerIterator); - while (it.hasNext()) { - HeaderElement he = it.nextElement(); - String param = he.getName(); - String value = he.getValue(); - if (value != null && param.equalsIgnoreCase("timeout")) { - try { - log.debug("============ In getKeepAliveDuration ================= {}", value); - - return Long.parseLong(value) * 1000; - } catch (NumberFormatException ignore) { - log.error("Failed parsing retrieved value of timeout header.", ignore); - } - } - } - } - return 20; - } - }); - - } - - protected SSLSocketFactory createSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { - TrustManager easyTrustManager = new javax.net.ssl.X509TrustManager() { - - public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { - // TODO Auto-generated method stub - - } - - public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { - // TODO Auto-generated method stub - - } - - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - // TODO Auto-generated method stub - return null; - } - - }; - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, new TrustManager[] { easyTrustManager }, null); - SSLSocketFactory sslFactory = new SSLSocketFactory(sslContext); - - sslFactory.setHostnameVerifier(new X509HostnameVerifier() { - - public boolean verify(String arg0, SSLSession arg1) { - // TODO Auto-generated method stub - return false; - } - - public void verify(String host, SSLSocket ssl) throws IOException { - // TODO Auto-generated method stub - - } - - public void verify(String host, java.security.cert.X509Certificate cert) throws SSLException { - // TODO Auto-generated method stub - - } - - public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { - // TODO Auto-generated method stub - - } - - }); - return sslFactory; - } - - /** - * Executes RS-GET to perform FIND. - * - * @param headerParameterKey - * String - * @param headerParameterValue - * String - * @return String - */ - public RestResponse doGET(String uri, Properties headers) { - logger.debug("Before executing uri {}. headers = {}", uri, headers); - - HttpGet httpGet = new HttpGet(uri); - - RestResponse response = execute(httpGet, headers); - - return response; - } - - private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) { - - if (headers != null) { - for (Entry<Object, Object> entry : headers.entrySet()) { - httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString()); - } - } - - } - - public RestResponse doPOST(String uri, Properties headers, Object objectToCreate) { - - logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers); - - HttpPost httpPost = new HttpPost(uri); - - if (objectToCreate != null) { - StringEntity se; - try { - se = new StringEntity(objectToCreate.toString()); - - // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, - // "application/json")); - httpPost.setEntity(se); - } catch (UnsupportedEncodingException e) { - String msg = "Failed creating Entity for post request." + e.getMessage(); - log.error(msg, e); - return null; - // throw new RestClientServiceExeption(msg); - } - } - - RestResponse response = execute(httpPost, headers); - - return response; - - } - - public RestResponse doPUT(String uri, Properties headers, Object objectToCreate) { - - logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers); - - HttpPut httpPut = new HttpPut(uri); - - if (objectToCreate != null) { - StringEntity se; - try { - se = new StringEntity(objectToCreate.toString()); - - // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, - // "application/json")); - httpPut.setEntity(se); - } catch (UnsupportedEncodingException e) { - String msg = "Failed creating Entity for post request." + e.getMessage(); - // throw new RestClientServiceExeption(msg); - log.error(msg, e); - return null; - } - } - - RestResponse response = execute(httpPut, headers); - - return response; - } - - private RestResponse execute(HttpRequestBase httpRequestBase, Properties headers) { - - String response = null; - String statusDesc = null; - int statusCode = HttpStatus.SC_OK; - - try { - - addHeadersToRequest(httpRequestBase, headers); - - HttpResponse httpResponse = this.httpClient.execute(httpRequestBase); - - statusCode = httpResponse.getStatusLine().getStatusCode(); - statusDesc = httpResponse.getStatusLine().getReasonPhrase(); - - HttpEntity entity = httpResponse.getEntity(); - if (entity != null) { - response = EntityUtils.toString(entity); - } - // ensure the connection gets released to the manager - EntityUtils.consume(entity); - - logResponse(response, httpRequestBase.getMethod()); - - } catch (Exception exception) { - httpRequestBase.abort(); - log.error("Failed to execute the {} request {}", httpRequestBase.getMethod(), httpRequestBase.getURI(), exception); - // processAndThrowException(exception); - return null; - } - - RestResponse restResponse = new RestResponse(response, statusDesc, statusCode); - - if (logger.isDebugEnabled()) { - URI uri = httpRequestBase.getURI(); - String url = uri.toString(); - logger.debug("After executing uri {}. response = {}", url, restResponse); - } - - return restResponse; - } - - public RestResponse doDELETE(String uri, Properties headers) { - - if (logger.isDebugEnabled()) { - logger.debug("Before executing uri {}. headers = {}", uri, headers); - } - - HttpDelete httpDelete = new HttpDelete(uri); - - RestResponse restResponse = execute(httpDelete, headers); - - return restResponse; - - } - - /** - * This method print the JSON response from the REST Server - * - * @param response - * the JSON response from the REST server - * @param method - * name of method - */ - private void logResponse(String response, String method) { - logger.debug("{} response = {}", method, response); - } - - /** - * Exception during client invocation usually it happens when status code starting with 400 or 500 is returned - * - * @param exception - * Exception - * @throws RSClientServiceExeption - */ - private void processAndThrowException(Exception exception) throws RestClientServiceExeption { - - logger.debug("\n------------------------"); - logger.debug("FAILURE: {}", exception.getMessage()); - - throw new RestClientServiceExeption(exception); - - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/RestClientServiceFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/RestClientServiceFactory.java deleted file mode 100644 index 5bf250f59c..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/RestClientServiceFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.rest.impl; - -import org.openecomp.sdc.common.rest.api.IRestClient; -import org.openecomp.sdc.common.rest.api.RestConfigurationInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RestClientServiceFactory { - - private static Logger log = LoggerFactory.getLogger(RestClientServiceFactory.class.getName()); - - public static IRestClient createRestClientService(RestConfigurationInfo restConfigurationInfo) { - - log.trace("Enter createRestClientService"); - - HttpRestClientServiceImpl restClientServiceImpl = new HttpRestClientServiceImpl(); - - boolean result = restClientServiceImpl.init(restConfigurationInfo); - if (result == false) { - return null; - } - - log.trace("Exit createRestClientService"); - - return restClientServiceImpl; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java new file mode 100644 index 0000000000..2e31eebd23 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.test; + +import java.io.File; + +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class BaseConfDependent { + protected static ConfigurationManager configurationManager; + protected static String componentName; + protected static String confPath; + + + protected static void setUp(){ + ExternalConfiguration.setAppName(componentName); + ExternalConfiguration.setConfigDir(confPath); + ExternalConfiguration.listenForChanges(); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + configurationManager = new ConfigurationManager(configurationSource); + + configurationManager.getConfiguration().setTitanInMemoryGraph(true); + + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/EitherPair.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/EitherPair.java new file mode 100644 index 0000000000..44f0d251c2 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/EitherPair.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.common.util; + +import fj.data.Either; + +import java.util.function.BiFunction; +import java.util.function.Function; + +public class EitherPair<L, M, R> { + + private Either<L, R> firstEither; + private Either<M, R> secondEither; + + private EitherPair(Either<L, R> firstEither, Either<M, R> secondEither) { + this.firstEither = firstEither; + this.secondEither = secondEither; + } + + public static <L, M, R> EitherPair<L, M, R> from(Either<L, R> firstEither, + Either<M, R> secondEither) { + return new EitherPair<>(firstEither, secondEither); + } + + public <X> X either(BiFunction<L, M, X> onLeft, Function<R, X > onRight) { + if (firstEither.isRight()) { + return onRight.apply(firstEither.right().value()); + } + if (secondEither.isRight()) { + return onRight.apply(secondEither.right().value()); + } + return onLeft.apply(firstEither.left().value(), secondEither.left().value()); + } + + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java index e0d5206066..91222a049c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java @@ -1,21 +1,24 @@ package org.openecomp.sdc.common.util; -import java.util.List; - +import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.common.api.HealthCheckInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class HealthCheckUtil { +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; - private static Logger log = LoggerFactory.getLogger(HealthCheckUtil.class.getName()); +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; - public static boolean getAggregateStatus(List<HealthCheckInfo> healthCheckInfos) { +public class HealthCheckUtil { + private static Logger log = LoggerFactory.getLogger(HealthCheckUtil.class.getName()); + public boolean getAggregateStatus(List<HealthCheckInfo> healthCheckInfos, Collection<String> excludes) { boolean status = true; - + excludes = CollectionUtils.isEmpty(excludes) ? new ArrayList<>() : excludes; for (HealthCheckInfo healthCheckInfo : healthCheckInfos) { - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckInfo.HealthCheckStatus.DOWN)) { + if (!excludes.contains(healthCheckInfo.getHealthCheckComponent()) && healthCheckInfo.getHealthCheckStatus().equals(DOWN)) { log.debug("Component {} is reported as DOWN - Aggregated HC will be DOWN", healthCheckInfo.getHealthCheckComponent()); status = false; break; @@ -25,18 +28,16 @@ public class HealthCheckUtil { return status; } - public static String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos, String parentDescription) { + public String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos, String parentDescription) { StringBuilder sb = new StringBuilder(); healthCheckInfos.forEach(x -> { - if (x.getHealthCheckStatus() == HealthCheckInfo.HealthCheckStatus.DOWN) { + if (x.getHealthCheckStatus() == DOWN) { sb.append("Component ").append(x.getHealthCheckComponent()).append(" is Down, "); } }); return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : ""; - -// return description; } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java index 9022e7246e..1f60632f1b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java @@ -54,8 +54,9 @@ public class JsonUtils { public static boolean isEmptyJson(JsonElement json) { return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject()); } - + public static boolean isJsonNullOrEmpty(JsonObject json) { return json.isJsonNull() || isEmptyJson(json); } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java index 6c47659dad..004c2d0a67 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.common.util; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - +import com.google.common.base.CharMatcher; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; @@ -36,7 +30,12 @@ import org.jsoup.Jsoup; import org.jsoup.helper.StringUtil; import org.jsoup.safety.Whitelist; -import com.google.common.base.CharMatcher; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; public class ValidationUtils { public final static Integer COMPONENT_NAME_MAX_LENGTH = 1024; @@ -126,6 +125,12 @@ public class ValidationUtils { public final static Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4; public final static Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100; + public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100; + public final static Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH-1) + "}$"); + + public final static Integer POLICY_MAX_LENGTH = 1024; + public final static Pattern POLICY_NAME_PATTERN = Pattern + .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH-1) + "}$"); public static boolean validateArtifactLabel(String label) { return ARTIFACT_LABEL_PATTERN.matcher(label).matches(); @@ -367,7 +372,7 @@ public class ValidationUtils { } public static String normalizeComponentInstanceName(String name) { - String[] split = splitComponentInctanceName(name); + String[] split = splitComponentInstanceName(name); StringBuffer sb = new StringBuffer(); for (String splitElement : split) { sb.append(splitElement); @@ -383,7 +388,7 @@ public class ValidationUtils { return split; } - private static String[] splitComponentInctanceName(String name) { + private static String[] splitComponentInstanceName(String name) { String normalizedName = name.toLowerCase(); normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); String[] split = normalizedName.split(" "); @@ -527,5 +532,8 @@ public class ValidationUtils { String stripped = HtmlCleaner.stripHtml(htmlText, false); return stripped; } - + + public static boolean validateForwardingPathNamePattern(String forwardingPathName) { + return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches(); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java index 203609aee3..322725b032 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java @@ -271,6 +271,7 @@ public class YamlToObjectConverter { Iterable<Object> mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents)); for (Object o : mappedToscaTemplateIt) { + System.out.println("Loaded object type:" + o.getClass()); Map<String, Object> map = (Map<String, Object>) o; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java index 9ee8fc6be0..7267bd148c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,394 +20,401 @@ package org.openecomp.sdc.fe.config; -import static java.lang.String.format; +import org.openecomp.sdc.common.api.BasicConfiguration; import java.util.Date; import java.util.List; -import org.openecomp.sdc.common.api.BasicConfiguration; +import static java.lang.String.format; public class Configuration extends BasicConfiguration { - /** - * fe FQDN - */ - private String feFqdn; - /** - * backend host - */ - private String beHost; - /** - * backend http port - */ - private Integer beHttpPort; - /** - * backend http secured port - */ - private Integer beSslPort; - - private Integer healthCheckSocketTimeoutInMs; - - private Integer healthCheckIntervalInSeconds; - - private FeMonitoringConfig systemMonitoring; - - private String kibanaHost; - - private Integer kibanaPort; - - private String kibanaProtocol; - - private String onboardingForwardContext; - - private OnboardingConfig onboarding; - - private DcaeConfig dcae; - - public String getKibanaProtocol() { - return kibanaProtocol; - } - - public void setKibanaProtocol(String kibanaProtocol) { - this.kibanaProtocol = kibanaProtocol; - } - - public String getKibanaHost() { - return kibanaHost; - } - - public void setKibanaHost(String kibanaHost) { - this.kibanaHost = kibanaHost; - } - - public Integer getKibanaPort() { - return kibanaPort; - } - - public void setKibanaPort(Integer kibanaPort) { - this.kibanaPort = kibanaPort; - } - - public FeMonitoringConfig getSystemMonitoring() { - return systemMonitoring; - } - - public void setSystemMonitoring(FeMonitoringConfig systemMonitoring) { - this.systemMonitoring = systemMonitoring; - } - - public Integer getHealthCheckSocketTimeoutInMs() { - return healthCheckSocketTimeoutInMs; - } - - public Integer getHealthCheckSocketTimeoutInMs(int defaultVal) { - return healthCheckSocketTimeoutInMs == null ? defaultVal : healthCheckSocketTimeoutInMs; - } - - public void setHealthCheckSocketTimeoutInMs(Integer healthCheckSocketTimeout) { - this.healthCheckSocketTimeoutInMs = healthCheckSocketTimeout; - } - - public Integer getHealthCheckIntervalInSeconds() { - return healthCheckIntervalInSeconds; - } - - public Integer getHealthCheckIntervalInSeconds(int defaultVal) { - return healthCheckIntervalInSeconds == null ? defaultVal : healthCheckIntervalInSeconds; - } - - public void setHealthCheckIntervalInSeconds(Integer healthCheckInterval) { - this.healthCheckIntervalInSeconds = healthCheckInterval; - } - - /** - * be http context - */ - private String beContext; - /** - * backend protocol. http | https - */ - private String beProtocol = "http"; - - private Date released; - private String version = "1111"; - private Connection connection; - private List<String> protocols; - - private int threadpoolSize; - private int requestTimeout; - - private List<List<String>> identificationHeaderFields; - private List<List<String>> optionalHeaderFields; - private List<String> forwardHeaderFields; - - public Date getReleased() { - return released; - } - - public String getVersion() { - return version; - } - - public void setReleased(Date released) { - this.released = released; - } - - public void setVersion(String version) { - this.version = version; - } - - public Connection getConnection() { - return connection; - } - - public void setConnection(Connection connection) { - this.connection = connection; - } - - public List<String> getProtocols() { - return protocols; - } - - public void setProtocols(List<String> protocols) { - this.protocols = protocols; - } - - public String getBeHost() { - return beHost; - } - - public void setBeHost(String beHost) { - this.beHost = beHost; - } - - public Integer getBeHttpPort() { - return beHttpPort; - } - - public void setBeHttpPort(Integer beHttpPort) { - this.beHttpPort = beHttpPort; - } - - public Integer getBeSslPort() { - return beSslPort; - } - - public void setBeSslPort(Integer beSslPort) { - this.beSslPort = beSslPort; - } - - public String getBeContext() { - return beContext; - } - - public void setBeContext(String beContext) { - this.beContext = beContext; - } - - public String getBeProtocol() { - return beProtocol; - } - - public void setBeProtocol(String beProtocol) { - this.beProtocol = beProtocol; - } - - public int getThreadpoolSize() { - return threadpoolSize; - } - - public void setThreadpoolSize(int threadpoolSize) { - this.threadpoolSize = threadpoolSize; - } - - public int getRequestTimeout() { - return requestTimeout; - } - - public void setRequestTimeout(int requestTimeout) { - this.requestTimeout = requestTimeout; - } - - public List<List<String>> getIdentificationHeaderFields() { - return identificationHeaderFields; - } - - public void setIdentificationHeaderFields(List<List<String>> identificationHeaderFields) { - this.identificationHeaderFields = identificationHeaderFields; - } - - public List<List<String>> getOptionalHeaderFields() { - return optionalHeaderFields; - } - - public void setOptionalHeaderFields(List<List<String>> optionalHeaderFields) { - this.optionalHeaderFields = optionalHeaderFields; - } - - public List<String> getForwardHeaderFields() { - return forwardHeaderFields; - } + /** + * fe FQDN + */ + private String feFqdn; + /** + * backend host + */ + private String beHost; + /** + * backend http port + */ + private Integer beHttpPort; + /** + * backend http secured port + */ + private Integer beSslPort; + + private Integer healthCheckSocketTimeoutInMs; + + private Integer healthCheckIntervalInSeconds; + + private List<String> healthStatusExclude; + + private FeMonitoringConfig systemMonitoring; + + private String kibanaHost; + + private Integer kibanaPort; + + private String kibanaProtocol; + + private String onboardingForwardContext; + + private OnboardingConfig onboarding; + + private DcaeConfig dcae; + /** + * be http context + */ + private String beContext; + /** + * backend protocol. http | https + */ + private String beProtocol = "http"; + private Date released; + private String version = "1111"; + private Connection connection; + private List<String> protocols; + private int threadpoolSize; + private int requestTimeout; + private List<List<String>> identificationHeaderFields; + private List<List<String>> optionalHeaderFields; + private List<String> forwardHeaderFields; + + public String getKibanaProtocol() { + return kibanaProtocol; + } + + public void setKibanaProtocol(String kibanaProtocol) { + this.kibanaProtocol = kibanaProtocol; + } + + public String getKibanaHost() { + return kibanaHost; + } + + public void setKibanaHost(String kibanaHost) { + this.kibanaHost = kibanaHost; + } + + public Integer getKibanaPort() { + return kibanaPort; + } + + public void setKibanaPort(Integer kibanaPort) { + this.kibanaPort = kibanaPort; + } + + public FeMonitoringConfig getSystemMonitoring() { + return systemMonitoring; + } + + public void setSystemMonitoring(FeMonitoringConfig systemMonitoring) { + this.systemMonitoring = systemMonitoring; + } + + public Integer getHealthCheckSocketTimeoutInMs() { + return healthCheckSocketTimeoutInMs; + } + + public void setHealthCheckSocketTimeoutInMs(Integer healthCheckSocketTimeout) { + this.healthCheckSocketTimeoutInMs = healthCheckSocketTimeout; + } + + public Integer getHealthCheckSocketTimeoutInMs(int defaultVal) { + return healthCheckSocketTimeoutInMs == null ? defaultVal : healthCheckSocketTimeoutInMs; + } + + public Integer getHealthCheckIntervalInSeconds() { + return healthCheckIntervalInSeconds; + } + + public void setHealthCheckIntervalInSeconds(Integer healthCheckInterval) { + this.healthCheckIntervalInSeconds = healthCheckInterval; + } + + public Integer getHealthCheckIntervalInSeconds(int defaultVal) { + return healthCheckIntervalInSeconds == null ? defaultVal : healthCheckIntervalInSeconds; + } - public void setForwardHeaderFields(List<String> forwardHeaderFields) { - this.forwardHeaderFields = forwardHeaderFields; - } + public Date getReleased() { + return released; + } - public String getFeFqdn() { - return feFqdn; - } + public void setReleased(Date released) { + this.released = released; + } - public void setFeFqdn(String feFqdn) { - this.feFqdn = feFqdn; - } + public String getVersion() { + return version; + } - public static class FeMonitoringConfig { + public void setVersion(String version) { + this.version = version; + } + + public Connection getConnection() { + return connection; + } + + public void setConnection(Connection connection) { + this.connection = connection; + } + + public List<String> getProtocols() { + return protocols; + } + + public void setProtocols(List<String> protocols) { + this.protocols = protocols; + } + + public String getBeHost() { + return beHost; + } + + public void setBeHost(String beHost) { + this.beHost = beHost; + } - Boolean enabled; - Boolean isProxy; - Integer probeIntervalInSeconds; + public Integer getBeHttpPort() { + return beHttpPort; + } - public Boolean getEnabled() { - return enabled; - } + public void setBeHttpPort(Integer beHttpPort) { + this.beHttpPort = beHttpPort; + } - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } + public Integer getBeSslPort() { + return beSslPort; + } + + public void setBeSslPort(Integer beSslPort) { + this.beSslPort = beSslPort; + } + + public String getBeContext() { + return beContext; + } + + public void setBeContext(String beContext) { + this.beContext = beContext; + } + + public String getBeProtocol() { + return beProtocol; + } + + public void setBeProtocol(String beProtocol) { + this.beProtocol = beProtocol; + } + + public int getThreadpoolSize() { + return threadpoolSize; + } + + public void setThreadpoolSize(int threadpoolSize) { + this.threadpoolSize = threadpoolSize; + } + + public int getRequestTimeout() { + return requestTimeout; + } + + public void setRequestTimeout(int requestTimeout) { + this.requestTimeout = requestTimeout; + } + + public List<List<String>> getIdentificationHeaderFields() { + return identificationHeaderFields; + } + + public void setIdentificationHeaderFields(List<List<String>> identificationHeaderFields) { + this.identificationHeaderFields = identificationHeaderFields; + } + + public List<List<String>> getOptionalHeaderFields() { + return optionalHeaderFields; + } + + public void setOptionalHeaderFields(List<List<String>> optionalHeaderFields) { + this.optionalHeaderFields = optionalHeaderFields; + } + + public List<String> getForwardHeaderFields() { + return forwardHeaderFields; + } + + public void setForwardHeaderFields(List<String> forwardHeaderFields) { + this.forwardHeaderFields = forwardHeaderFields; + } + + public String getFeFqdn() { + return feFqdn; + } + + public void setFeFqdn(String feFqdn) { + this.feFqdn = feFqdn; + } + + public String getOnboardingForwardContext() { + return onboardingForwardContext; + } + + public void setOnboardingForwardContext(String onboardingForwardContext) { + this.onboardingForwardContext = onboardingForwardContext; + } + + public OnboardingConfig getOnboarding() { + return onboarding; + } + + public void setOnboarding(OnboardingConfig onboarding) { + this.onboarding = onboarding; + } + + public DcaeConfig getDcae() { + return dcae; + } + + public void setDcae(DcaeConfig dcae) { + this.dcae = dcae; + } + + @Override + public String toString() { + return new StringBuilder().append(format("backend host: %s%n", beHost)) + .append(format("backend http port: %s%n", beHttpPort)) + .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext)) + .append(format("backend protocol: %s%n", beProtocol)) + .append(format("onboarding forward context: %s%n", onboardingForwardContext)) + .append(format("Version: %s%n", version)).append(format("Released: %s%n", released)) + .append(format("Connecting to database: %s%n", connection)) + .append(format("Supported protocols: %s%n", protocols)).toString(); + } + + public static class FeMonitoringConfig { + + Boolean enabled; + Boolean isProxy; + Integer probeIntervalInSeconds; + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Boolean getIsProxy() { + return isProxy; + } + + public void setIsProxy(Boolean isProxy) { + this.isProxy = isProxy; + } + + public Integer getProbeIntervalInSeconds() { + return probeIntervalInSeconds; + } + + public void setProbeIntervalInSeconds(Integer probeIntervalInSeconds) { + this.probeIntervalInSeconds = probeIntervalInSeconds; + } + + public Integer getProbeIntervalInSeconds(int defaultVal) { + return probeIntervalInSeconds == null ? defaultVal : probeIntervalInSeconds; + } + } + + public static class OnboardingConfig { + + String protocol = "http"; + String host; + Integer port; + String healthCheckUri; + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public String getHealthCheckUri() { + return healthCheckUri; + } + + public void setHealthCheckUri(String healthCheckUri) { + this.healthCheckUri = healthCheckUri; + } + } + + public static class DcaeConfig { + + String protocol = "http"; + String host; + Integer port; + String healthCheckUri; + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getHost() { + return host; + } - public Boolean getIsProxy() { - return isProxy; - } + public void setHost(String host) { + this.host = host; + } - public void setIsProxy(Boolean isProxy) { - this.isProxy = isProxy; - } + public Integer getPort() { + return port; + } - public Integer getProbeIntervalInSeconds() { - return probeIntervalInSeconds; - } + public void setPort(Integer port) { + this.port = port; + } - public Integer getProbeIntervalInSeconds(int defaultVal) { - return probeIntervalInSeconds == null ? defaultVal : probeIntervalInSeconds; - } + public String getHealthCheckUri() { + return healthCheckUri; + } - public void setProbeIntervalInSeconds(Integer probeIntervalInSeconds) { - this.probeIntervalInSeconds = probeIntervalInSeconds; - } - } + public void setHealthCheckUri(String healthCheckUri) { + this.healthCheckUri = healthCheckUri; + } + } - public String getOnboardingForwardContext() { - return onboardingForwardContext; - } + public List<String> getHealthStatusExclude() { + return healthStatusExclude; + } - public void setOnboardingForwardContext(String onboardingForwardContext) { - this.onboardingForwardContext = onboardingForwardContext; - } + public void setHealthStatusExclude(List<String> healthStatusExclude) { + this.healthStatusExclude = healthStatusExclude; + } - public OnboardingConfig getOnboarding() { - return onboarding; - } - - public void setOnboarding(OnboardingConfig onboarding) { - this.onboarding = onboarding; - } - - public static class OnboardingConfig { - - String protocol = "http"; - String host; - Integer port; - String healthCheckUri; - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public Integer getPort() { - return port; - } - - public void setPort(Integer port) { - this.port = port; - } - - public String getHealthCheckUri() { - return healthCheckUri; - } - - public void setHealthCheckUri(String healthCheckUri) { - this.healthCheckUri = healthCheckUri; - } - } - - public DcaeConfig getDcae() { - return dcae; - } - - public void setDcae(DcaeConfig dcae) { - this.dcae = dcae; - } - - public static class DcaeConfig { - - String protocol = "http"; - String host; - Integer port; - String healthCheckUri; - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public Integer getPort() { - return port; - } - - public void setPort(Integer port) { - this.port = port; - } - - public String getHealthCheckUri() { - return healthCheckUri; - } - - public void setHealthCheckUri(String healthCheckUri) { - this.healthCheckUri = healthCheckUri; - } - } - - @Override - public String toString() { - return new StringBuilder().append(format("backend host: %s%n", beHost)) - .append(format("backend http port: %s%n", beHttpPort)) - .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext)) - .append(format("backend protocol: %s%n", beProtocol)) - .append(format("onboarding forward context: %s%n", onboardingForwardContext)) - .append(format("Version: %s%n", version)).append(format("Released: %s%n", released)) - .append(format("Connecting to database: %s%n", connection)) - .append(format("Supported protocols: %s%n", protocols)).toString(); - } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java index 482be7697d..68078071f3 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java @@ -20,25 +20,22 @@ package org.openecomp.sdc.fe.monitoring; -import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.servlet.ServletContext; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.config.HttpClientConfig; +import org.openecomp.sdc.common.http.config.Timeouts; import org.openecomp.sdc.common.monitoring.MonitoringEvent; import org.openecomp.sdc.common.monitoring.MonitoringMetricsFetcher; import org.openecomp.sdc.fe.config.Configuration; @@ -93,48 +90,22 @@ public class FeMonitoringService { } private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { - CloseableHttpClient httpClient = null; try { Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) .getConfiguration(); String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(), - config.getBeHttpPort()); - httpClient = getHttpClient(config); - HttpPost httpPost = new HttpPost(redirectedUrl); + Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); + + int timeout = 3000; String monitoringMetricsJson = gson.toJson(monitoringMetrics); - HttpEntity myEntity = new StringEntity(monitoringMetricsJson); - httpPost.setEntity(myEntity); - httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - int beResponseStatus; - CloseableHttpResponse beResponse; - try { - beResponse = httpClient.execute(httpPost); - beResponseStatus = beResponse.getStatusLine().getStatusCode(); - if (beResponseStatus != HttpStatus.SC_OK) { - monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus); - } - } catch (Exception e) { - monitoringLogger.error("Monitoring error when trying to connect to BE", e); - } + HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); + HttpResponse<String> resposne = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); + int beResponseStatus = resposne.getStatusCode(); + if (beResponseStatus != HttpStatus.SC_OK) { + monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus); + } } catch (Exception e) { - monitoringLogger.error("Unexpected monitoring error", e); - } finally { - if (httpClient != null) { - try { - httpClient.close(); - } catch (IOException e) { - } - } + monitoringLogger.error("Monitoring BE failed with exception ", e); } } - - private CloseableHttpClient getHttpClient(Configuration config) { - int timeout = 3000; - RequestConfig.Builder requestBuilder = RequestConfig.custom(); - requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout); - - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setDefaultRequestConfig(requestBuilder.build()); - return builder.build(); - } } |