diff options
Diffstat (limited to 'common-app-api/src/main/java/org/openecomp/sdc/common')
61 files changed, 3319 insertions, 1055 deletions
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; } |