diff options
Diffstat (limited to 'src')
26 files changed, 379 insertions, 199 deletions
diff --git a/src/main/java/org/onap/clamp/clds/ClampServlet.java b/src/main/java/org/onap/clamp/clds/ClampServlet.java index 86524d1c6..54aa95e5d 100644 --- a/src/main/java/org/onap/clamp/clds/ClampServlet.java +++ b/src/main/java/org/onap/clamp/clds/ClampServlet.java @@ -32,6 +32,7 @@ import java.io.IOException; import java.security.Principal; import java.util.ArrayList; import java.util.List; + import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -101,8 +102,8 @@ public class ClampServlet extends CamelHttpTransportServlet { permissionList.add(SecureServicePermission .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, READ)); permissionList.add(SecureServicePermission - .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, - UPDATE)); + .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), + cldsPermissionInstance, UPDATE)); } return permissionList; } @@ -139,4 +140,4 @@ public class ClampServlet extends CamelHttpTransportServlet { } } } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java b/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java index d32c4a179..06c77252c 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java @@ -34,13 +34,27 @@ public class DistributionStatusMessage implements IDistributionStatusMessage { private DistributionStatusEnum distributionStatus; private long timestamp; + /** + * Distribution status message constructor. + * + * @param artifactUrl + * Url of specific SDC artifact(resource) + * @param consumerId + * Unique ID of SDC component instance + * @param distributionId + * Distribution ID published in the distribution notification. + * @param distributionStatusEnum + * Status to send in the message + * @param timestamp + * Timestamp of the message + */ public DistributionStatusMessage(final String artifactUrl, final String consumerId, final String distributionId, - final DistributionStatusEnum distributionStatusEnum, final long timestampL) { - artifactURL = artifactUrl; - consumerID = consumerId; - distributionID = distributionId; - distributionStatus = distributionStatusEnum; - timestamp = timestampL; + final DistributionStatusEnum distributionStatusEnum, final long timestamp) { + this.artifactURL = artifactUrl; + this.consumerID = consumerId; + this.distributionID = distributionId; + this.distributionStatus = distributionStatusEnum; + this.timestamp = timestamp; } @Override diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java index 729ef496e..20e13bc7c 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java @@ -38,7 +38,6 @@ import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException; import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException; import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException; import org.onap.clamp.clds.exception.sdc.controller.SdcDownloadException; -import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException; import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact; import org.onap.clamp.clds.sdc.controller.installer.CsarHandler; import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; @@ -348,8 +347,8 @@ public class SdcSingleController { return downloadResult; } - private void sendSdcNotification(NotificationType notificationType, String artifactUrl, String consumerID, - String distributionID, DistributionStatusEnum status, String errorReason, + private void sendSdcNotification(NotificationType notificationType, String artifactUrl, String consumerId, + String distributionId, DistributionStatusEnum status, String errorReason, long timestamp) { String event = "Sending " + notificationType.name() + "(" + status.name() + ")" + " notification to SDC for artifact:" + artifactUrl; @@ -359,7 +358,7 @@ public class SdcSingleController { logger.info(event); String action = ""; try { - IDistributionStatusMessage message = new DistributionStatusMessage(artifactUrl, consumerID, distributionID, + IDistributionStatusMessage message = new DistributionStatusMessage(artifactUrl, consumerId, distributionId, status, timestamp); switch (notificationType) { case DOWNLOAD: diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/ChainGenerator.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/ChainGenerator.java index 27c5b9cbd..8b555fca1 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/ChainGenerator.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/ChainGenerator.java @@ -20,6 +20,7 @@ * =================================================================== * */ + package org.onap.clamp.clds.sdc.controller.installer; import java.util.LinkedList; diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java index 7ef217b4e..f78b9d32d 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java @@ -86,8 +86,8 @@ public class CsarHandler { return clampCsarPath + "/" + controllerName + "/" + artifactElement.getArtifactName(); } - private IArtifactInfo searchForUniqueCsar(INotificationData iNotif) throws CsarHandlerException { - List<IArtifactInfo> serviceArtifacts = iNotif.getServiceArtifacts(); + private IArtifactInfo searchForUniqueCsar(INotificationData notificationData) throws CsarHandlerException { + List<IArtifactInfo> serviceArtifacts = notificationData.getServiceArtifacts(); for (IArtifactInfo artifact : serviceArtifacts) { if (artifact.getArtifactType().equals(CSAR_TYPE)) { return artifact; diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java index 6c41e9c66..441a7ac11 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java @@ -207,7 +207,7 @@ public class CsarInstallerImpl implements CsarInstaller { } private void createPolicyModel(CsarHandler csar) throws PolicyModelException { - try{ + try { Optional<String> policyModelYaml = csar.getPolicyModelYaml(); // save policy model into the database } catch (IOException e) { @@ -228,8 +228,8 @@ public class CsarInstallerImpl implements CsarInstaller { if (policyName != null) { policyNameList.add(filteredPolicyName); } else { - String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef - .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM); + String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) + ef.getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM); if (inputPolicyName != null) { policyNameList.add(GET_INPUT_BLUEPRINT_PARAM); } @@ -249,7 +249,7 @@ public class CsarInstallerImpl implements CsarInstaller { /** * This call must be done when deploying the SDC notification as this call get - * the latest version of the artifact (version can be specified to DCAE call) + * the latest version of the artifact (version can be specified to DCAE call). * * @return The DcaeInventoryResponse object containing the dcae values */ @@ -263,9 +263,10 @@ public class CsarInstallerImpl implements CsarInstaller { private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact, BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException { - Set<MicroService> microServicesFromBlueprint = blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()) ; + Set<MicroService> microServicesFromBlueprint = blueprintParser.getMicroServices( + blueprintArtifact.getDcaeBlueprint()) ; List<MicroService> microServicesChain = chainGenerator.getChainOfMicroServices(microServicesFromBlueprint); - if(microServicesChain.isEmpty()) { + if (microServicesChain.isEmpty()) { microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint()); } String imageText = svgFacade.getSvgImage(microServicesChain); @@ -290,7 +291,8 @@ public class CsarInstallerImpl implements CsarInstaller { if (dcaeInventoryResponse == null) { throw new SdcArtifactInstallerException( - "DCAE inventory response is NULL, query to DCAE fail to be answered properly, this is required to deploy CSAR properly !!!"); + "DCAE inventory response is NULL, query to DCAE fail to be answered properly, " + + "this is required to deploy CSAR properly !!!"); } try { CldsModel cldsModel = new CldsModel(); diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java index 9bc7a022a..5bbc980c9 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java @@ -75,7 +75,7 @@ public class MicroService { } MicroService that = (MicroService) o; return name.equals(that.name) && modelType.equals(that.modelType) && inputFrom.equals(that.inputFrom) - && mappedNameJpa.equals(that.mappedNameJpa); + && mappedNameJpa.equals(that.mappedNameJpa); } @Override diff --git a/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java b/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java index 76417132b..c228e171a 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -53,9 +55,9 @@ public class CldsDictionaryService extends SecureServiceBase { @Autowired private CldsDao cldsDao; - + private LoggingUtils util = new LoggingUtils(logger); - + @PostConstruct private final void initConstruct() { @@ -73,7 +75,7 @@ public class CldsDictionaryService extends SecureServiceBase { */ public ResponseEntity<CldsDictionary> createOrUpdateDictionary(String dictionaryName, CldsDictionary cldsDictionary) { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsDictionaryService: createOrUpdateDictionary", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionUpdateTosca); @@ -82,9 +84,7 @@ public class CldsDictionaryService extends SecureServiceBase { cldsDictionary.setDictionaryName(dictionaryName); } cldsDictionary.save(dictionaryName, cldsDao, getUserId()); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "createOrUpdateDictionary success", this.getClass().getName()); - auditLogger.info("createOrUpdateDictionary completed"); + auditLogInfo("createOrUpdateDictionary", startTime); return new ResponseEntity<>(cldsDictionary, HttpStatus.OK); } @@ -99,14 +99,12 @@ public class CldsDictionaryService extends SecureServiceBase { */ public ResponseEntity<CldsDictionaryItem> createOrUpdateDictionaryElements(String dictionaryName, CldsDictionaryItem dictionaryItem) { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsDictionaryService: createOrUpdateDictionaryElements", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionUpdateTosca); dictionaryItem.save(dictionaryName, cldsDao, getUserId()); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "createOrUpdateDictionaryElements success", this.getClass().getName()); - auditLogger.info("createOrUpdateDictionaryElements completed"); + auditLogInfo("createOrUpdateDictionaryElements", startTime); return new ResponseEntity<>(dictionaryItem, HttpStatus.OK); } @@ -116,14 +114,12 @@ public class CldsDictionaryService extends SecureServiceBase { * @return CldsDictionary List List of CldsDictionary available in DB */ public ResponseEntity<List<CldsDictionary>> getAllDictionaryNames() { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsDictionaryService: getAllDictionaryNames", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); List<CldsDictionary> dictionaries = cldsDao.getDictionary(null, null); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "getAllDictionaryNames success", this.getClass().getName()); - auditLogger.info("getAllDictionaryNames completed"); + auditLogInfo("getAllDictionaryNames", startTime); return new ResponseEntity<>(dictionaries, HttpStatus.OK); } @@ -136,14 +132,12 @@ public class CldsDictionaryService extends SecureServiceBase { * dictionary name */ public ResponseEntity<List<CldsDictionaryItem>> getDictionaryElementsByName(String dictionaryName) { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsDictionaryService: getDictionaryElementsByName", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); List<CldsDictionaryItem> dictionaryItems = cldsDao.getDictionaryElements(dictionaryName, null, null); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "getAllDictionaryNames success", this.getClass().getName()); - auditLogger.info("getAllDictionaryNames completed"); + auditLogInfo("getDictionaryElementsByName", startTime); return new ResponseEntity<>(dictionaryItems, HttpStatus.OK); } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index 63a913314..d9956e3ad 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -204,8 +204,10 @@ public class CldsService extends SecureServiceBase { */ public List<CldsMonitoringDetails> getCldsDetails() { util.entering(request, "CldsService: GET model details"); - Date startTime = new Date(); - final List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); + + final Date startTime = new Date(); + List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); + // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET cldsDetails completed"); @@ -221,7 +223,7 @@ public class CldsService extends SecureServiceBase { */ public CldsInfo getCldsInfo() { util.entering(request, "CldsService: GET cldsInfo"); - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setTimeContext(startTime, new Date()); CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this); @@ -244,7 +246,7 @@ public class CldsService extends SecureServiceBase { */ public String getBpmnXml(String modelName) { util.entering(request, "CldsService: GET model bpmn"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET bpmnText for modelName={}", modelName); final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); @@ -265,7 +267,7 @@ public class CldsService extends SecureServiceBase { */ public String getImageXml(String modelName) { util.entering(request, "CldsService: GET model image"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET imageText for modelName={}", modelName); final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); @@ -334,7 +336,6 @@ public class CldsService extends SecureServiceBase { logger.info("PUT imageText={}", cldsModel.getImageText()); fillInCldsModel(cldsModel); cldsModel.save(cldsDao, getUserId()); - // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("PUT model completed"); @@ -349,7 +350,7 @@ public class CldsService extends SecureServiceBase { */ public List<ValueItem> getModelNames() { util.entering(request, "CldsService: GET model names"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET list of model names"); final List<ValueItem> names = cldsDao.getModelNames(); @@ -388,7 +389,7 @@ public class CldsService extends SecureServiceBase { public ResponseEntity<?> putModelAndProcessAction(String action, String modelName, String test, CldsModel model) throws TransformerException, ParseException { util.entering(request, "CldsService: Process model action"); - Date startTime = new Date(); + final Date startTime = new Date(); String errorMessage = ""; String actionCd = ""; try { @@ -491,7 +492,8 @@ public class CldsService extends SecureServiceBase { instanceCount = dcaeEvent.getInstances().size(); } String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID() - + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName() + + " resourceUUID=" + dcaeEvent.getResourceUUID() + + " artifactName=" + dcaeEvent.getArtifactName() + " instance count=" + instanceCount + " isTest=" + isTest; logger.info("POST dcae event {}", msgInfo); if (isTest) { @@ -568,7 +570,7 @@ public class CldsService extends SecureServiceBase { */ public ResponseEntity<CldsModel> deployModel(String modelName, CldsModel model) { util.entering(request, "CldsService: Deploy model"); - Date startTime = new Date(); + final Date startTime = new Date(); String errorMessage = ""; try { fillInCldsModel(model); @@ -624,7 +626,7 @@ public class CldsService extends SecureServiceBase { */ public ResponseEntity<CldsModel> unDeployModel(String modelName, CldsModel model) { util.entering(request, "CldsService: Undeploy model"); - Date startTime = new Date(); + final Date startTime = new Date(); String errorMessage = ""; try { SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, @@ -714,4 +716,4 @@ public class CldsService extends SecureServiceBase { public void setLoggingUtil(LoggingUtils utilP) { util = utilP; } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index d107731b0..183db8bdb 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -35,8 +35,6 @@ import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.model.ValueItem; import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.clds.util.ONAPLogConstants; -import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -58,10 +56,10 @@ public class CldsTemplateService extends SecureServiceBase { @PostConstruct private final void afterConstruction() { - permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, - "read"); - permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, - "update"); + permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, + cldsPermissionInstance, "read"); + permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, + cldsPermissionInstance, "update"); } @Autowired @@ -78,14 +76,12 @@ public class CldsTemplateService extends SecureServiceBase { */ public String getBpmnTemplate(String templateName) { util.entering(request, "CldsTemplateService: GET template bpmn"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET bpmnText for templateName=" + templateName); - final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET template bpmn completed"); - util.exiting("200", "Get template bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + + CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); + auditLogInfo(util, "GET template bpmn", startTime); return template.getBpmnText(); } @@ -99,14 +95,12 @@ public class CldsTemplateService extends SecureServiceBase { */ public String getImageXml(String templateName) { util.entering(request, "CldsTemplateService: GET template image"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET imageText for templateName=" + templateName); - final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET template image completed"); - util.exiting("200", "Get template image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + + CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); + auditLogInfo(util, "GET template image", startTime); return template.getImageText(); } @@ -121,12 +115,10 @@ public class CldsTemplateService extends SecureServiceBase { final Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET model for templateName=" + templateName); + CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); template.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateTemplate)); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET template completed"); - util.exiting("200", "Get template success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + auditLogInfo(util, "GET template", startTime); return template; } @@ -147,10 +139,7 @@ public class CldsTemplateService extends SecureServiceBase { logger.info("PUT imageText=" + cldsTemplate.getImageText()); cldsTemplate.setName(templateName); cldsTemplate.save(cldsDao, null); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("PUT template completed"); - util.exiting("200", "Put template success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + auditLogInfo(util, "PUT template", startTime); return cldsTemplate; } @@ -161,19 +150,17 @@ public class CldsTemplateService extends SecureServiceBase { */ public List<ValueItem> getTemplateNames() { util.entering(request, "CldsTemplateService: GET template names"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET list of template names"); - final List<ValueItem> names = cldsDao.getTemplateNames(); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET template names completed"); - util.exiting("200", "Get template names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + + List<ValueItem> names = cldsDao.getTemplateNames(); + auditLogInfo(util, "GET template names", startTime); return names; } // Created for the integration test public void setLoggingUtil(LoggingUtils utilP) { - util = utilP; + util = utilP; } } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java index 81bafef47..0d53e9155 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java @@ -25,6 +25,7 @@ package org.onap.clamp.clds.service; +import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Optional; @@ -92,9 +93,7 @@ public class CldsToscaService extends SecureServiceBase { isAuthorized(permissionUpdateTosca); cldsToscaModel.setToscaModelName(toscaModelName); cldsToscaModel = cldsToscaModel.save(cldsDao, refProp, policyClient, getUserId()); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Parse Tosca model and save success", this.getClass().getName()); - auditLogger.info("Parse Tosca model and save completed"); + auditLogInfo("Parse Tosca model and save", startTime); return new ResponseEntity<>(cldsToscaModel, HttpStatus.CREATED); } @@ -104,16 +103,14 @@ public class CldsToscaService extends SecureServiceBase { * @return clds tosca models - list of CLDS tosca models */ public List<CldsToscaModel> getAllToscaModels() { - - Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsToscaService: Get All tosca models", getPrincipalName()); // TODO revisit based on new permissions + final Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsToscaService: Get All tosca models", getPrincipalName()); isAuthorized(permissionReadTosca); - final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get(); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get All tosca models success", this.getClass().getName()); - auditLogger.info("Get All tosca models"); - return cldsToscaModels; + + Optional<List<CldsToscaModel>> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()); + auditLogInfo("Get All tosca models", startTime); + return cldsToscaModels.orElse(Collections.emptyList()); } /** @@ -126,44 +123,41 @@ public class CldsToscaService extends SecureServiceBase { * @return clds tosca model - CLDS tosca model for a given tosca model name */ public CldsToscaModel getToscaModel(String toscaModelName) { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by model name", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName)) - .get(); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get tosca models by model name success", this.getClass().getName()); - auditLogger.info("GET tosca models by model name completed"); - return cldsToscaModels.get(0); + + Optional<List<CldsToscaModel>> cldsToscaModels = Optional.ofNullable( + cldsDao.getToscaModelByName(toscaModelName)); + auditLogInfo("Get tosca models by model name", startTime); + return cldsToscaModels.map(models -> models.get(0)).orElse(null); } /** * REST service that retrieves a CLDS Tosca model lists for a policy type * from the database. - * * @param policyType * The type of the policy * @return clds tosca model - CLDS tosca model for a given policy type */ public CldsToscaModel getToscaModelsByPolicyType(String policyType) { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by policyType", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType)) - .get(); - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get tosca models by policyType success", this.getClass().getName()); - auditLogger.info("GET tosca models by policyType completed"); - return cldsToscaModels.get(0); + + Optional<List<CldsToscaModel>> cldsToscaModels = Optional.ofNullable( + cldsDao.getToscaModelByPolicyType(policyType)); + auditLogInfo("Get tosca models by policyType", startTime); + return cldsToscaModels.map(models -> models.get(0)).orElse(null); } public ResponseEntity<?> deleteToscaModelById(String toscaModeId) { // TODO return null; } - + // Created for the integration test public void setLoggingUtil(LoggingUtils utilP) { util = utilP; diff --git a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java index f65308903..0e28a4b9d 100644 --- a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java +++ b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java @@ -30,6 +30,8 @@ import java.util.Date; import javax.ws.rs.NotAuthorizedException; import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.clamp.clds.util.ONAPLogConstants; +import org.slf4j.event.Level; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; @@ -206,4 +208,19 @@ public abstract class SecureServiceBase { return false; } + + protected void auditLogInfo(LoggingUtils util, String actionDescription, Date startTime) { + LoggingUtils.setTimeContext(startTime, new Date()); + auditLogger.info(actionDescription + " completed"); + util.exiting("200", actionDescription + " success", Level.INFO, + ONAPLogConstants.ResponseStatus.COMPLETED); + } + + protected void auditLogInfo(String actionDescription, Date startTime) { + + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", actionDescription + " success", + this.getClass().getName()); + auditLogger.info(actionDescription + " completed"); + } }
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index cbe7eba96..163ab6913 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -28,6 +28,7 @@ import com.att.eelf.configuration.EELFManager; import java.net.HttpURLConnection; import java.net.InetAddress; +import java.net.URLConnection; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -114,7 +115,7 @@ public class LoggingUtils { */ public static void setResponseContext(String code, String description, String className) { MDC.put("ResponseCode", code); - MDC.put("StatusCode", code.equals("0") ? "COMPLETE" : "ERROR"); + MDC.put("StatusCode", "0".equals(code) ? "COMPLETE" : "ERROR"); MDC.put("ResponseDescription", description != null ? description : ""); MDC.put("ClassName", className != null ? className : ""); } @@ -167,8 +168,6 @@ public class LoggingUtils { return dateFormat; } - - /********************************************************************************************* * Method for ONAP Application Logging Specification v1.2 ********************************************************************************************/ @@ -256,7 +255,7 @@ public class LoggingUtils { public String getProperties(String name) { return MDC.get(name); } - + /** * Report pending invocation with <tt>INVOKE</tt> marker, * setting standard ONAP logging headers automatically. @@ -267,24 +266,7 @@ public class LoggingUtils { * @return The HTTP url connection */ public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) { - final String invocationId = UUID.randomUUID().toString(); - - // Set standard HTTP headers on (southbound request) builder. - con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, - defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); - con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, - invocationId); - con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, - defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); - - invokeContext(targetEntity, targetServiceName, invocationId); - - // Log INVOKE*, with the invocationID as the message body. - // (We didn't really want this kind of behavior in the standard, - // but is it worse than new, single-message MDC?) - this.mlogger.info(ONAPLogConstants.Markers.INVOKE); - this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); - return con; + return this.invokeGeneric(con, targetEntity, targetServiceName); } /** @@ -316,24 +298,7 @@ public class LoggingUtils { * @return The HTTPS url connection */ public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) { - final String invocationId = UUID.randomUUID().toString(); - - // Set standard HTTP headers on (southbound request) builder. - con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, - defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); - con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, - invocationId); - con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, - defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); - - invokeContext(targetEntity, targetServiceName, invocationId); - - // Log INVOKE*, with the invocationID as the message body. - // (We didn't really want this kind of behavior in the standard, - // but is it worse than new, single-message MDC?) - this.mlogger.info(ONAPLogConstants.Markers.INVOKE); - this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); - return con; + return this.invokeGeneric(con, targetEntity, targetServiceName); } /** @@ -410,4 +375,25 @@ public class LoggingUtils { MDC.remove(ONAPLogConstants.MDCs.INVOCATIONID_OUT); MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP); } + + private <T extends URLConnection> T invokeGeneric(final T con, String targetEntity, String targetServiceName) { + final String invocationId = UUID.randomUUID().toString(); + + // Set standard HTTP headers on (southbound request) builder. + con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); + con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, + invocationId); + con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); + + invokeContext(targetEntity, targetServiceName, invocationId); + + // Log INVOKE*, with the invocationID as the message body. + // (We didn't really want this kind of behavior in the standard, + // but is it worse than new, single-message MDC?) + this.mlogger.info(ONAPLogConstants.Markers.INVOKE); + this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); + return con; + } } diff --git a/src/main/resources/logback-default.xml b/src/main/resources/logback-default.xml index bc8ebb909..4c496716c 100644 --- a/src/main/resources/logback-default.xml +++ b/src/main/resources/logback-default.xml @@ -40,7 +40,7 @@ <level>INFO</level> </filter> <encoder> - <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n + <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n </pattern> </encoder> </appender> @@ -76,7 +76,7 @@ <file>${logDirectory}/debug.log</file> <append>true</append> <encoder> - <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n + <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n </pattern> </encoder> <rollingPolicy diff --git a/src/test/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatterTest.java b/src/test/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatterTest.java index c92cdcf35..429611ce6 100644 --- a/src/test/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatterTest.java +++ b/src/test/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatterTest.java @@ -101,7 +101,7 @@ public class TcaRequestFormatterTest { } @Test(expected = TcaRequestFormatterException.class) - public void shouldThrowTcaRequestFormatterException() throws IOException{ + public void shouldThrowTcaRequestFormatterException() throws IOException { //given String service = "TestService"; String policy = "TestService_scope.PolicyName"; @@ -113,4 +113,4 @@ public class TcaRequestFormatterTest { //then TcaRequestFormatter.createPolicyContent(clampProperties, modelProperties, service, policy, tca); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/clamp/clds/it/HttpConnectionManagerItCase.java b/src/test/java/org/onap/clamp/clds/it/HttpConnectionManagerItCase.java index 4c23eca09..69277baf9 100644 --- a/src/test/java/org/onap/clamp/clds/it/HttpConnectionManagerItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/HttpConnectionManagerItCase.java @@ -127,21 +127,21 @@ public class HttpConnectionManagerItCase { @Test(expected = BadRequestException.class) public void testHttpsGet404() throws IOException { - httpConnectionManager.doHttpRequest("https://localhost:" + this.httpsPort + "/designer/index1.html", - "GET", null, null, "DCAE", null, null); + httpConnectionManager.doHttpRequest("https://localhost:" + this.httpsPort + "/designer/index1.html", "GET", + null, null, "DCAE", null, null); fail("Should have raised an BadRequestException"); } @Test(expected = BadRequestException.class) public void testHttpsPost404() throws IOException { - httpConnectionManager.doHttpRequest("https://localhost:" + this.httpsPort + "/designer/index1.html", - "POST", "", "application/json", "DCAE", null, null); + httpConnectionManager.doHttpRequest("https://localhost:" + this.httpsPort + "/designer/index1.html", "POST", + "", "application/json", "DCAE", null, null); fail("Should have raised an BadRequestException"); } @Test(expected = BadRequestException.class) public void testHttpException() throws IOException { - httpConnectionManager.doHttpRequest("http://localhost:" + this.httpsPort + "/designer/index.html", "GET", + httpConnectionManager.doHttpRequest("http://localhost:" + this.httpsPort + "/designer/index.html", "GET", null, null, "DCAE", null, null); fail("Should have raised an BadRequestException"); } diff --git a/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java b/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java index 65aa9b44f..d34042038 100644 --- a/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java @@ -55,10 +55,10 @@ public class CldsReferencePropertiesItCase { */ @Test public void testGetStringValue() { - assertEquals(refProp.getStringValue("policy.onap.name"), "DCAE"); - assertEquals(refProp.getStringValue("policy.ms.policyNamePrefix", ""), "Config_MS_"); - assertEquals(refProp.getStringValue("policy.ms.policyNamePrefix", "testos"), "Config_MS_"); - assertEquals(refProp.getStringValue("policy.ms", "policyNamePrefix"), "Config_MS_"); + assertEquals("DCAE", refProp.getStringValue("policy.onap.name")); + assertEquals("Config_MS_", refProp.getStringValue("policy.ms.policyNamePrefix", "")); + assertEquals("Config_MS_", refProp.getStringValue("policy.ms.policyNamePrefix", "testos")); + assertEquals("Config_MS_", refProp.getStringValue("policy.ms", "policyNamePrefix")); assertNull(refProp.getStringValue("does.not.exist")); } @@ -70,7 +70,7 @@ public class CldsReferencePropertiesItCase { //then assertNotNull(root); assertTrue(root.isJsonObject()); - assertEquals(root.getAsJsonObject().get("DC1").getAsString(), "Data Center 1"); + assertEquals("Data Center 1", root.getAsJsonObject().get("DC1").getAsString()); } @Test @@ -81,7 +81,7 @@ public class CldsReferencePropertiesItCase { //then assertNotNull(root); assertTrue(root.isJsonObject()); - assertEquals(root.getAsJsonObject().get("DC1").getAsString(), "Data Center 1"); + assertEquals("Data Center 1", root.getAsJsonObject().get("DC1").getAsString()); } @Test @@ -101,7 +101,8 @@ public class CldsReferencePropertiesItCase { */ @Test public void testGetFileContent() throws IOException { - String location = "{\n\t\"DC1\": \"Data Center 1\",\n\t\"DC2\": \"Data Center 2\",\n\t\"DC3\": \"Data Center 3\"\n}\n"; + String location = "{\n\t\"DC1\": \"Data Center 1\"," + + "\n\t\"DC2\": \"Data Center 2\",\n\t\"DC3\": \"Data Center 3\"\n}\n"; String content = refProp.getFileContent("ui.location.default"); assertEquals(location, content); // Test composite key @@ -112,9 +113,9 @@ public class CldsReferencePropertiesItCase { @Test public void testGetStringList() { List<String> profileList = refProp.getStringList("policy.pdpUrl1", ","); - assertTrue(profileList.size() == 3); + assertEquals(3, profileList.size()); assertTrue(profileList.get(0).trim().startsWith("http://localhost:")); - assertTrue(profileList.get(1).trim().equals("testpdp")); - assertTrue(profileList.get(2).trim().equals("alpha123")); + assertEquals("testpdp", profileList.get(1).trim()); + assertEquals("alpha123", profileList.get(2).trim()); } } diff --git a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java index dec639770..dcaf2b952 100644 --- a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java +++ b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java @@ -5,6 +5,8 @@ * Copyright (C) 2019 Nokia Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -20,6 +22,7 @@ * =================================================================== * */ + package org.onap.clamp.clds.sdc.controller.installer; import com.google.gson.Gson; @@ -60,6 +63,12 @@ public class BlueprintParserTest { private static JsonObject jsonObjectBlueprintWithoutProperties; private static JsonObject jsonObjectBlueprintWithoutRelationships; + /** + * Method to load Blueprints before all test. + * + * @throws IOException + * In case of issues when opening the files + */ @BeforeClass public static void loadBlueprints() throws IOException { microServiceTheWholeBlueprintValid = ResourceFileUtil @@ -73,12 +82,13 @@ public class BlueprintParserTest { .getResourceAsString("clds/single-microservice-fragment-without-name.yaml"); String microServiceBlueprintWithoutProperties = ResourceFileUtil .getResourceAsString("clds/single-microservice-fragment-without-properties.yaml"); - String microServiceBlueprintWithoutRelationships = ResourceFileUtil - .getResourceAsString("clds/single-microservice-fragment-without-relationships.yaml"); jsonObjectBlueprintValid = yamlToJson(microServiceBlueprintValid); jsonObjectBlueprintWithoutName = yamlToJson(microServiceBlueprintWithoutName); jsonObjectBlueprintWithoutProperties = yamlToJson(microServiceBlueprintWithoutProperties); + + String microServiceBlueprintWithoutRelationships = ResourceFileUtil + .getResourceAsString("clds/single-microservice-fragment-without-relationships.yaml"); jsonObjectBlueprintWithoutRelationships = yamlToJson(microServiceBlueprintWithoutRelationships); } @@ -162,11 +172,11 @@ public class BlueprintParserTest { } @Test - public void fallBackToOneMicroServiceTCATest() { - MicroService tcaMS = new MicroService(BlueprintParser.TCA, "onap.policies.monitoring.cdap.tca.hi.lo.app", "", - ""); - List<MicroService> expected = Collections.singletonList(tcaMS); + public void fallBackToOneMicroServiceTcaTest() { + MicroService tcaMs = new MicroService(BlueprintParser.TCA, + "onap.policies.monitoring.cdap.tca.hi.lo.app", "", ""); + List<MicroService> expected = Collections.singletonList(tcaMs); List<MicroService> actual = new BlueprintParser().fallbackToOneMicroService(microServiceBlueprintOldStyleTCA); Assert.assertEquals(expected, actual); @@ -174,10 +184,10 @@ public class BlueprintParserTest { @Test public void fallBackToOneMicroServiceHolmesTest() { - MicroService holmesMS = new MicroService(BlueprintParser.HOLMES, "onap.policies.monitoring.cdap.tca.hi.lo.app", - "", ""); + MicroService holmesMs = new MicroService(BlueprintParser.HOLMES, + "onap.policies.monitoring.cdap.tca.hi.lo.app", "", ""); - List<MicroService> expected = Collections.singletonList(holmesMS); + List<MicroService> expected = Collections.singletonList(holmesMs); List<MicroService> actual = new BlueprintParser() .fallbackToOneMicroService(microServiceBlueprintOldStyleHolmes); diff --git a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java index 4b41ee818..4b4563cd4 100644 --- a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java +++ b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java @@ -20,6 +20,7 @@ * =================================================================== * */ + package org.onap.clamp.clds.sdc.controller.installer; import java.util.Arrays; @@ -73,4 +74,4 @@ public class ChainGeneratorTest { List<MicroService> actualList = new ChainGenerator().getChainOfMicroServices(inputSet); Assert.assertTrue(actualList.isEmpty()); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/clamp/clds/util/LoggingUtilsTest.java b/src/test/java/org/onap/clamp/clds/util/LoggingUtilsTest.java new file mode 100644 index 000000000..7e2da4d1e --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/util/LoggingUtilsTest.java @@ -0,0 +1,148 @@ +/*- +* ============LICENSE_START======================================================= +* ONAP CLAMP +* Copyright (C) 2019 Samsung. 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.onap.clamp.clds.util; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.Map; + +import javax.net.ssl.HttpsURLConnection; +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.slf4j.MDC; +import org.slf4j.event.Level; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; + +/** + * Test Logging Utils. + */ +@RunWith(MockitoJUnitRunner.class) +public class LoggingUtilsTest { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtilsTest.class); + + private static final String SERVICE_NAME = "LogginUtilsTest: Test Entering method"; + + private LoggingUtils util; + + @Before + public void setup() { + this.util = new LoggingUtils(logger); + } + + @Test + public void testEnteringLoggingUtils() { + // given + final String userName = "test"; + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + UserDetails userDetails = Mockito.mock(UserDetails.class); + Mockito.when(userDetails.getUsername()).thenReturn(userName); + + Authentication localAuth = Mockito.mock(Authentication.class); + Mockito.when(localAuth.getPrincipal()).thenReturn(userDetails); + + SecurityContext securityContext = Mockito.mock(SecurityContext.class); + Mockito.when(securityContext.getAuthentication()).thenReturn(localAuth); + SecurityContextHolder.setContext(securityContext); + + // when + util.entering(request, SERVICE_NAME); + + // then + String[] keys = { ONAPLogConstants.MDCs.PARTNER_NAME, + ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + ONAPLogConstants.MDCs.REQUEST_ID, + ONAPLogConstants.MDCs.INVOCATION_ID, + ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, + ONAPLogConstants.MDCs.SERVER_FQDN, + ONAPLogConstants.MDCs.INSTANCE_UUID, + ONAPLogConstants.MDCs.SERVICE_NAME + }; + Map<String, String> mdc = MDC.getMDCAdapter().getCopyOfContextMap(); + + assertTrue(checkMapKeys(mdc, keys)); + assertEquals(userName, + mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void testExistingLoggingUtils() { + // given + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + + // when + util.exiting("200", SERVICE_NAME, Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + + // then + Map<String, String> mdc = MDC.getMDCAdapter().getCopyOfContextMap(); + assertNull(mdc); + } + + @Test + public void testInvokeTestUtils() { + // given + final String targetEntity = "LoggingUtilsTest"; + final String targetServiceName = "testInvokeTestUtils"; + HttpsURLConnection secureConnection = Mockito.mock(HttpsURLConnection.class); + + // when + secureConnection = util.invokeHttps(secureConnection, targetEntity, targetServiceName); + + // then + assertNotNull(secureConnection); + String[] keys = {ONAPLogConstants.MDCs.TARGET_ENTITY, + ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, + ONAPLogConstants.MDCs.INVOCATIONID_OUT, + ONAPLogConstants.MDCs.INVOKE_TIMESTAMP + }; + Map<String, String> mdc = MDC.getMDCAdapter().getCopyOfContextMap(); + + assertTrue(checkMapKeys(mdc, keys)); + assertEquals(targetEntity, mdc.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(targetServiceName, mdc.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + private boolean checkMapKeys(Map map, String[] keys) { + return Arrays.stream(keys).allMatch(key -> map.get(key) != null); + } +} diff --git a/src/test/java/org/onap/clamp/clds/util/XmlToolsTest.java b/src/test/java/org/onap/clamp/clds/util/XmlToolsTest.java index 4351a80d4..a34ef3f94 100644 --- a/src/test/java/org/onap/clamp/clds/util/XmlToolsTest.java +++ b/src/test/java/org/onap/clamp/clds/util/XmlToolsTest.java @@ -5,6 +5,8 @@ * Copyright (C) 2019 Nokia. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -54,7 +56,20 @@ public class XmlToolsTest { Assert.assertNull(doc.getDoctype()); } - + /** + * Method to parse String into XmlDocument. + * + * @param res + * String to parse + * @return + * XmlDocument + * @throws ParserConfigurationException + * In case of issues with parse the document + * @throws SAXException + * In case of bad format of res + * @throws IOException + * In case of issues creating the document + */ public static Document parseStringToXmlDocument(String res) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -69,4 +84,4 @@ public class XmlToolsTest { return db.parse(is); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java index ff6e1b5d4..269ad42e1 100644 --- a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java +++ b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java @@ -5,6 +5,8 @@ * Copyright (C) 2019 Nokia. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -60,7 +62,7 @@ public class ClampGraphBuilderTest { MicroService ms2 = new MicroService("ms2", "", "", "ms2_jpa_id"); String policy = "OperationalPolicy"; - List<MicroService> microServices = Arrays.asList(ms1, ms2); + final List<MicroService> microServices = Arrays.asList(ms1, ms2); ClampGraphBuilder clampGraphBuilder = new ClampGraphBuilder(mockPainter); clampGraphBuilder.collector(collector).addMicroService(ms1).addMicroService(ms2).policy(policy).build(); @@ -91,4 +93,4 @@ public class ClampGraphBuilderTest { ClampGraphBuilder clampGraphBuilder = new ClampGraphBuilder(mockPainter); clampGraphBuilder.collector(collector).policy(policy).build(); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphTest.java b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphTest.java index 6bbebdfde..e46db1a2d 100644 --- a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphTest.java +++ b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphTest.java @@ -46,7 +46,7 @@ public class ClampGraphTest { private DocumentBuilder mockDocumentBuilder; @Test - public void getAsSVGTest() throws IOException, ParserConfigurationException, SAXException { + public void getAsSvgTest() throws IOException, ParserConfigurationException, SAXException { String expected = ResourceFileUtil.getResourceAsString("clds/util/file.xml"); Document document = XmlToolsTest.parseStringToXmlDocument(expected); @@ -57,7 +57,7 @@ public class ClampGraphTest { } @Test - public void getAsSVGLazyTest() throws IOException, ParserConfigurationException, SAXException { + public void getAsSvgLazyTest() throws IOException, ParserConfigurationException, SAXException { String expected = ResourceFileUtil.getResourceAsString("clds/util/file.xml"); Document document = XmlToolsTest.parseStringToXmlDocument(expected); @@ -74,4 +74,4 @@ public class ClampGraphTest { Assert.assertEquals(expected.trim(), actualSecond.trim()); } -}
\ No newline at end of file +} diff --git a/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java b/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java index 9a82ec097..78e0d2e3d 100644 --- a/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java +++ b/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java @@ -5,7 +5,9 @@ * Copyright (C) 2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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 * @@ -85,10 +87,10 @@ public class LoopRepositoriesItCase { private MicroServicePolicy getMicroServicePolicy(String name, String modelType, String jsonRepresentation, String policyTosca, String jsonProperties, boolean shared) { - MicroServicePolicy µService = new MicroServicePolicy(name, modelType, policyTosca, shared, + MicroServicePolicy microService = new MicroServicePolicy(name, modelType, policyTosca, shared, gson.fromJson(jsonRepresentation, JsonObject.class), new HashSet<>()); - µService.setProperties(new Gson().fromJson(jsonProperties, JsonObject.class)); - return µService; + microService.setProperties(new Gson().fromJson(jsonProperties, JsonObject.class)); + return microService; } private LoopLog getLoopLog(LogType type, String message, Loop loop) { @@ -97,7 +99,7 @@ public class LoopRepositoriesItCase { @Test @Transactional - public void CrudTest() { + public void crudTest() { Loop loopTest = getLoop("ControlLoopTest", "<xml></xml>", "yamlcontent", "{\"testname\":\"testvalue\"}", "123456789", "https://dcaetest.org", "UUID-blueprint"); OperationalPolicy opPolicy = this.getOperationalPolicy("{\"type\":\"GUARD\"}", "GuardOpPolicyTest"); diff --git a/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java b/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java index 8899a36c7..c9350c610 100644 --- a/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java +++ b/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java @@ -5,7 +5,9 @@ * Copyright (C) 2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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 * @@ -64,11 +66,11 @@ public class LoopToJsonTest { private MicroServicePolicy getMicroServicePolicy(String name, String modelType, String jsonRepresentation, String policyTosca, String jsonProperties, boolean shared) { - MicroServicePolicy µService = new MicroServicePolicy(name, modelType, policyTosca, shared, + MicroServicePolicy microService = new MicroServicePolicy(name, modelType, policyTosca, shared, gson.fromJson(jsonRepresentation, JsonObject.class), new HashSet<>()); - µService.setProperties(new Gson().fromJson(jsonProperties, JsonObject.class)); + microService.setProperties(new Gson().fromJson(jsonProperties, JsonObject.class)); - return µService; + return microService; } private LoopLog getLoopLog(LogType type, String message, Loop loop) { @@ -78,7 +80,7 @@ public class LoopToJsonTest { } @Test - public void LoopGsonTest() throws IOException { + public void loopGsonTest() throws IOException { Loop loopTest = getLoop("ControlLoopTest", "<xml></xml>", "yamlcontent", "{\"testname\":\"testvalue\"}", "123456789", "https://dcaetest.org", "UUID-blueprint"); OperationalPolicy opPolicy = this.getOperationalPolicy( diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml new file mode 100644 index 000000000..07e587855 --- /dev/null +++ b/src/test/resources/logback.xml @@ -0,0 +1,2 @@ +<!-- Empty Configuration to prevent creating log files by Units Tests (e.g LoggingUtilsTest) ! --> +<configuration /> |