diff options
author | sebdet <sebastien.determe@intl.att.com> | 2019-09-11 13:18:42 +0200 |
---|---|---|
committer | sebdet <sebastien.determe@intl.att.com> | 2019-09-11 14:21:46 +0200 |
commit | cf87afa1bbf19cdaf8b60f1e689c2b82625c14f8 (patch) | |
tree | 805af0faa4a23515a16f0d96f477e189c51f470e /src/main/java | |
parent | 58b44949714b002818d20ba40d01eb50c031614d (diff) |
Checkstyle fixes
Checkstyle fixes done to solve the Unstable build
Issue-ID: CLAMP-487
Change-Id: I694b13e03dd1e7220988fd0c08bfbf12a808f7f7
Signed-off-by: sebdet <sebastien.determe@intl.att.com>
Diffstat (limited to 'src/main/java')
29 files changed, 306 insertions, 225 deletions
diff --git a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java index f9e618c83..b49be86bb 100644 --- a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java +++ b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java @@ -30,10 +30,9 @@ import com.att.eelf.configuration.EELFManager; import java.util.Date; -import org.onap.clamp.clds.exception.NotAuthorizedException; - import org.apache.camel.Exchange; import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.exception.NotAuthorizedException; import org.onap.clamp.clds.service.SecureServiceBase; import org.onap.clamp.clds.service.SecureServicePermission; import org.onap.clamp.clds.util.LoggingUtils; @@ -49,9 +48,9 @@ import org.springframework.stereotype.Component; @Component public class AuthorizationController { - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SecureServiceBase.class); - protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); - protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SecureServiceBase.class); + protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); + protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); // By default we'll set it to a default handler @Autowired @@ -61,23 +60,19 @@ public class AuthorizationController { private static final String PERM_INSTANCE = "security.permission.instance"; /** - * Insert authorize the api based on the permission + * Insert authorize the api based on the permission. * - * @param camelExchange - * The Camel Exchange object containing the properties - * @param typeVar - * The type of the permissions - * @param instanceVar - * The instance of the permissions. e.g. dev - * @param action - * The action of the permissions. e.g. read + * @param camelExchange The Camel Exchange object containing the properties + * @param typeVar The type of the permissions + * @param instanceVar The instance of the permissions. e.g. dev + * @param action The action of the permissions. e.g. read */ public void authorize(Exchange camelExchange, String typeVar, String instanceVar, String action) { String type = refProp.getStringValue(PERM_PREFIX + typeVar); String instance = refProp.getStringValue(PERM_INSTANCE); if (null == type || type.isEmpty()) { - //authorization is turned off, since the permission is not defined + // authorization is turned off, since the permission is not defined return; } if (null != instanceVar && !instanceVar.isEmpty()) { @@ -90,7 +85,7 @@ public class AuthorizationController { LoggingUtils.setTimeContext(startTime, new Date()); securityLogger.debug("checking if {} has permission: {}", principalName, perm); - if (!isUserPermitted(perm)){ + if (!isUserPermitted(perm)) { String msg = principalName + " does not have permission: " + perm; LoggingUtils.setErrorContext("100", "Authorization Error"); securityLogger.warn(msg); @@ -98,14 +93,20 @@ public class AuthorizationController { } } + /** + * Insert authorize the api based on the permission. + * + * @param inPermission Security permission in input + * @return True if user is permitted + */ public boolean isUserPermitted(SecureServicePermission inPermission) { String principalName = PrincipalUtils.getPrincipalName(); // check if the user has the permission key or the permission key with a - // combination of all instance and/or all action. + // combination of all instance and/or all action. if (hasRole(inPermission.getKey()) || hasRole(inPermission.getKeyAllInstance())) { - auditLogger.info("{} authorized because user has permission with * for instance: {}", - principalName, inPermission.getKey()); + auditLogger.info("{} authorized because user has permission with * for instance: {}", principalName, + inPermission.getKey()); return true; // the rest of these don't seem to be required - isUserInRole method // appears to take * as a wildcard @@ -114,8 +115,8 @@ public class AuthorizationController { principalName, inPermission.getKey()); return true; } else if (hasRole(inPermission.getKeyAllAction())) { - auditLogger.info("{} authorized because user has permission with * for action: {}", - principalName, inPermission.getKey()); + auditLogger.info("{} authorized because user has permission with * for action: {}", principalName, + inPermission.getKey()); return true; } else { return false; diff --git a/src/main/java/org/onap/clamp/clds/config/AAFConfiguration.java b/src/main/java/org/onap/clamp/clds/config/AafConfiguration.java index 99d64fd87..b137378d3 100644 --- a/src/main/java/org/onap/clamp/clds/config/AAFConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/AafConfiguration.java @@ -33,7 +33,7 @@ import org.springframework.context.annotation.Profile; @Configuration @Profile("clamp-aaf-authentication") -public class AAFConfiguration { +public class AafConfiguration { /** * Method to return clamp cadi filter. diff --git a/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java b/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java index 9d4e7d0c7..6a539c7ef 100644 --- a/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java @@ -56,7 +56,8 @@ public class DefaultUserConfiguration extends WebSecurityConfigurerAdapter { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DefaultUserConfiguration.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - private static final String SETUP_WEB_USERS_EXCEPTION_MSG = "Exception occurred during the setup of the Web users in memory"; + private static final String SETUP_WEB_USERS_EXCEPTION_MSG = "Exception occurred during the " + + " setup of the Web users in memory"; @Autowired private ClampProperties refProp; @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") diff --git a/src/main/java/org/onap/clamp/clds/config/spring/CldsConfiguration.java b/src/main/java/org/onap/clamp/clds/config/spring/CldsConfiguration.java index cb6089417..fdac85232 100644 --- a/src/main/java/org/onap/clamp/clds/config/spring/CldsConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/spring/CldsConfiguration.java @@ -55,6 +55,11 @@ public class CldsConfiguration { return new EncodedPasswordBasicDataSource(); } + /** + * This loads the file system.properties. + * + * @return + */ @Bean(name = "mapper") public PropertiesFactoryBean mapper() { PropertiesFactoryBean bean = new PropertiesFactoryBean(); 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 06c77252c..c80441fa6 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 @@ -28,9 +28,9 @@ import org.onap.sdc.utils.DistributionStatusEnum; public class DistributionStatusMessage implements IDistributionStatusMessage { - private String artifactURL; - private String consumerID; - private String distributionID; + private String artifactUrl; + private String consumerId; + private String distributionId; private DistributionStatusEnum distributionStatus; private long timestamp; @@ -50,26 +50,26 @@ public class DistributionStatusMessage implements IDistributionStatusMessage { */ public DistributionStatusMessage(final String artifactUrl, final String consumerId, final String distributionId, final DistributionStatusEnum distributionStatusEnum, final long timestamp) { - this.artifactURL = artifactUrl; - this.consumerID = consumerId; - this.distributionID = distributionId; + this.artifactUrl = artifactUrl; + this.consumerId = consumerId; + this.distributionId = distributionId; this.distributionStatus = distributionStatusEnum; this.timestamp = timestamp; } @Override public String getArtifactURL() { - return artifactURL; + return artifactUrl; } @Override public String getConsumerID() { - return consumerID; + return consumerId; } @Override public String getDistributionID() { - return distributionID; + return distributionId; } @Override diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java index 3792c1720..0dd231f03 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java @@ -60,6 +60,12 @@ public class BlueprintParser { private static final String CLAMP_NODE_RELATIONSHIPS_GETS_INPUT_FROM = "clamp_node.relationships.gets_input_from"; private static final String TARGET = "target"; + /** + * Get all micro services from blueprint. + * + * @param blueprintString the blueprint in a String + * @return A set of MircoService + */ public Set<MicroService> getMicroServices(String blueprintString) { Set<MicroService> microServices = new HashSet<>(); JsonObject blueprintJson = BlueprintParser.convertToJson(blueprintString); @@ -77,6 +83,12 @@ public class BlueprintParser { return microServices; } + /** + * Does a fallback to TCA or Holmes. + * + * @param blueprintString the blueprint in a String + * @return The list of microservices + */ public List<MicroService> fallbackToOneMicroService(String blueprintString) { JsonObject jsonObject = BlueprintParser.convertToJson(blueprintString); JsonObject results = jsonObject.get(NODE_TEMPLATES).getAsJsonObject(); @@ -92,7 +104,7 @@ public class BlueprintParser { } String msName = theBiggestMicroServiceKey.toLowerCase().contains(HOLMES_PREFIX) ? HOLMES : TCA; return Collections - .singletonList(new MicroService(msName, "onap.policies.monitoring.cdap.tca.hi.lo.app", "", "")); + .singletonList(new MicroService(msName, "onap.policies.monitoring.cdap.tca.hi.lo.app", "", "")); } String getName(Entry<String, JsonElement> entry) { @@ -124,9 +136,9 @@ public class BlueprintParser { String findModelTypeInTargetArray(JsonArray jsonArray, JsonObject nodeTemplateList, JsonObject inputList) { for (JsonElement elem : jsonArray) { String modelType = getModelType( - new AbstractMap.SimpleEntry<String, JsonElement>(elem.getAsJsonObject().get(TARGET).getAsString(), - nodeTemplateList.get(elem.getAsJsonObject().get(TARGET).getAsString()).getAsJsonObject()), - nodeTemplateList, inputList); + new AbstractMap.SimpleEntry<String, JsonElement>(elem.getAsJsonObject().get(TARGET).getAsString(), + nodeTemplateList.get(elem.getAsJsonObject().get(TARGET).getAsString()).getAsJsonObject()), + nodeTemplateList, inputList); if (!modelType.isEmpty()) { return modelType; } @@ -143,7 +155,7 @@ public class BlueprintParser { if (properties.get(POLICY_MODELID).isJsonObject()) { // it's a blueprint parameter return inputList.get(properties.get(POLICY_MODELID).getAsJsonObject().get(GET_INPUT).getAsString()) - .getAsJsonObject().get("default").getAsString(); + .getAsJsonObject().get("default").getAsString(); } else { // It's a direct value return properties.get(POLICY_MODELID).getAsString(); @@ -158,7 +170,7 @@ public class BlueprintParser { } MicroService getNodeRepresentation(Entry<String, JsonElement> entry, JsonObject nodeTemplateList, - JsonObject inputList) { + JsonObject inputList) { String name = getName(entry); String getInputFrom = getInput(entry); String modelType = getModelType(entry, nodeTemplateList, inputList); @@ -167,7 +179,7 @@ public class BlueprintParser { private String getTarget(JsonObject elementObject) { if (elementObject.has(TYPE) && elementObject.has(TARGET) - && elementObject.get(TYPE).getAsString().equals(CLAMP_NODE_RELATIONSHIPS_GETS_INPUT_FROM)) { + && elementObject.get(TYPE).getAsString().equals(CLAMP_NODE_RELATIONSHIPS_GETS_INPUT_FROM)) { return elementObject.get(TARGET).getAsString(); } return ""; 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 8b555fca1..9e76cc938 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 @@ -36,6 +36,12 @@ public class ChainGenerator { ChainGenerator() { } + /** + * Get list of microservices chain. + * + * @param input A set of microservices + * @return The list of microservice chained + */ public List<MicroService> getChainOfMicroServices(Set<MicroService> input) { LinkedList<MicroService> returnList = new LinkedList<>(); if (preValidate(input)) { @@ -52,7 +58,7 @@ public class ChainGenerator { private boolean preValidate(Set<MicroService> input) { List<MicroService> noInputs = input.stream().filter(ms -> "".equals(ms.getInputFrom())) - .collect(Collectors.toList()); + .collect(Collectors.toList()); return noInputs.size() == 1; } @@ -68,7 +74,7 @@ public class ChainGenerator { } private void insertNodeTemplateIntoChain(MicroService microServicetoInsert, - LinkedList<MicroService> chainOfMicroServices) { + LinkedList<MicroService> chainOfMicroServices) { int insertIndex = 0; for (int i = 0; i < chainOfMicroServices.size(); i++) { MicroService current = chainOfMicroServices.get(i); 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 f78b9d32d..471415a37 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 @@ -75,6 +75,9 @@ public class CsarHandler { public static final String DATA_DEFINITION_NAME_SUFFIX = "Definitions/data.yml"; public static final String DATA_DEFINITION_KEY = "data_types:"; + /** + * Constructor for CsarHandler taking sdc notification in input. + */ public CsarHandler(INotificationData data, String controller, String clampCsarPath) throws CsarHandlerException { this.sdcNotification = data; this.controllerName = controller; @@ -96,8 +99,16 @@ public class CsarHandler { throw new CsarHandlerException("Unable to find a CSAR in the Sdc Notification"); } + /** + * This saves the notification to disk and database. + * + * @param resultArtifact The artifact to install + * @throws SdcArtifactInstallerException In case of issues with the installation + * @throws SdcToscaParserException In case of issues with the parsing of + * the CSAR + */ public synchronized void save(IDistributionClientDownloadResult resultArtifact) - throws SdcArtifactInstallerException, SdcToscaParserException { + throws SdcArtifactInstallerException, SdcToscaParserException { try { logger.info("Writing CSAR file to: " + csarFilePath + " UUID " + artifactElement.getArtifactUUID() + ")"); Path path = Paths.get(csarFilePath); @@ -110,12 +121,12 @@ public class CsarHandler { this.loadDcaeBlueprint(); } catch (IOException e) { throw new SdcArtifactInstallerException( - "Exception caught when trying to write the CSAR on the file system to " + csarFilePath, e); + "Exception caught when trying to write the CSAR on the file system to " + csarFilePath, e); } } private IResourceInstance searchForResourceByInstanceName(String blueprintResourceInstanceName) - throws SdcArtifactInstallerException { + throws SdcArtifactInstallerException { for (IResourceInstance resource : this.sdcNotification.getResources()) { String filteredString = resource.getResourceInstanceName().replaceAll("-", ""); filteredString = filteredString.replaceAll(" ", ""); @@ -124,7 +135,7 @@ public class CsarHandler { } } throw new SdcArtifactInstallerException("Error when searching for " + blueprintResourceInstanceName - + " as ResourceInstanceName in Sdc notification and did not find it"); + + " as ResourceInstanceName in Sdc notification and did not find it"); } private void loadDcaeBlueprint() throws IOException, SdcArtifactInstallerException { @@ -135,19 +146,20 @@ public class CsarHandler { if (!entry.isDirectory() && entry.getName().contains(BLUEPRINT_TYPE)) { BlueprintArtifact blueprintArtifact = new BlueprintArtifact(); blueprintArtifact.setBlueprintArtifactName( - entry.getName().substring(entry.getName().lastIndexOf('/') + 1, entry.getName().length())); + entry.getName().substring(entry.getName().lastIndexOf('/') + 1, entry.getName().length())); blueprintArtifact - .setBlueprintInvariantServiceUuid(this.getSdcNotification().getServiceInvariantUUID()); + .setBlueprintInvariantServiceUuid(this.getSdcNotification().getServiceInvariantUUID()); try (InputStream stream = zipFile.getInputStream(entry)) { blueprintArtifact.setDcaeBlueprint(IOUtils.toString(stream, StandardCharsets.UTF_8)); } blueprintArtifact.setResourceAttached(searchForResourceByInstanceName(entry.getName().substring( - entry.getName().indexOf(RESOURCE_INSTANCE_NAME_PREFIX) + RESOURCE_INSTANCE_NAME_PREFIX.length(), - entry.getName().indexOf(RESOURCE_INSTANCE_NAME_SUFFIX)))); + entry.getName().indexOf(RESOURCE_INSTANCE_NAME_PREFIX) + + RESOURCE_INSTANCE_NAME_PREFIX.length(), + entry.getName().indexOf(RESOURCE_INSTANCE_NAME_SUFFIX)))); this.mapOfBlueprints.put(blueprintArtifact.getBlueprintArtifactName(), blueprintArtifact); logger.info("Found a blueprint entry in the CSAR " + blueprintArtifact.getBlueprintArtifactName() - + " for resource instance Name " - + blueprintArtifact.getResourceAttached().getResourceInstanceName()); + + " for resource instance Name " + + blueprintArtifact.getResourceAttached().getResourceInstanceName()); } } logger.info(this.mapOfBlueprints.size() + " blueprint(s) will be converted to closed loop"); @@ -179,7 +191,9 @@ public class CsarHandler { } /** - * Get the whole policy model Yaml. It combines the content of policies.yaml and data.yaml. + * Get the whole policy model Yaml. It combines the content of policies.yaml and + * data.yaml. + * * @return The whole policy model yaml * @throws IOException The IO Exception */ 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 5bbc980c9..68ac842cf 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 @@ -32,6 +32,14 @@ public class MicroService { private final String inputFrom; private String mappedNameJpa; + /** + * The Micro service constructor. + * + * @param name The name in String + * @param modelType The model type + * @param inputFrom Comes from (single chained) + * @param mappedNameJpa Name in database + */ public MicroService(String name, String modelType, String inputFrom, String mappedNameJpa) { this.name = name; this.inputFrom = inputFrom; @@ -54,7 +62,7 @@ public class MicroService { @Override public String toString() { return "MicroService{" + "name='" + name + '\'' + ", modelType='" + modelType + '\'' + ", inputFrom='" - + inputFrom + '\'' + ", mappedNameJpa='" + mappedNameJpa + '\'' + '}'; + + inputFrom + '\'' + ", mappedNameJpa='" + mappedNameJpa + '\'' + '}'; } public String getMappedNameJpa() { @@ -66,14 +74,14 @@ public class MicroService { } @Override - public boolean equals(Object o) { - if (this == o) { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (o == null || getClass() != o.getClass()) { + if (obj == null || getClass() != obj.getClass()) { return false; } - MicroService that = (MicroService) o; + MicroService that = (MicroService) obj; return name.equals(that.name) && modelType.equals(that.modelType) && inputFrom.equals(that.inputFrom) && mappedNameJpa.equals(that.mappedNameJpa); } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java b/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java index 39c12c8f5..6203cdf86 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java @@ -29,7 +29,7 @@ import java.util.Date; import org.onap.clamp.clds.model.CldsHealthCheck; import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.clds.util.ONAPLogConstants; +import org.onap.clamp.clds.util.OnapLogConstants; import org.onap.clamp.loop.LoopController; import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; @@ -65,7 +65,7 @@ public class CldsHealthcheckService { cldsHealthCheck.setHealthCheckStatus("UP"); cldsHealthCheck.setDescription("OK"); LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName()); - util.exiting("200", "Healthcheck success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + util.exiting("200", "Healthcheck success", Level.INFO, OnapLogConstants.ResponseStatus.COMPLETED); } catch (Exception e) { logger.error("CLAMP application Heath check failed", e); LoggingUtils.setResponseContext("999", "Get healthcheck failed", this.getClass().getName()); @@ -73,7 +73,7 @@ public class CldsHealthcheckService { cldsHealthCheck.setHealthCheckStatus("DOWN"); cldsHealthCheck.setDescription("NOT-OK"); util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "Healthcheck failed", Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); + OnapLogConstants.ResponseStatus.ERROR); } return cldsHealthCheck; } 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 0e809112a..783ee7032 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -35,7 +35,7 @@ import javax.servlet.http.HttpServletRequest; import org.onap.clamp.clds.model.CldsInfo; import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.clds.util.ONAPLogConstants; +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; @@ -46,6 +46,7 @@ import org.springframework.stereotype.Component; */ @Component public class CldsService extends SecureServiceBase { + /** * The constant securityLogger. */ @@ -138,7 +139,7 @@ public class CldsService extends SecureServiceBase { // audit log LoggingUtils.setTimeContext(startTime, new Date()); securityLogger.info("GET cldsInfo completed"); - util.exiting("200", "Get cldsInfo success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + util.exiting("200", "Get cldsInfo success", Level.INFO, OnapLogConstants.ResponseStatus.COMPLETED); return cldsInfo; } 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 0e28a4b9d..debd687c5 100644 --- a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java +++ b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java @@ -30,7 +30,7 @@ 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.onap.clamp.clds.util.OnapLogConstants; import org.slf4j.event.Level; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; @@ -213,7 +213,7 @@ public abstract class SecureServiceBase { LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info(actionDescription + " completed"); util.exiting("200", actionDescription + " success", Level.INFO, - ONAPLogConstants.ResponseStatus.COMPLETED); + OnapLogConstants.ResponseStatus.COMPLETED); } protected void auditLogInfo(String actionDescription, Date startTime) { diff --git a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java index 85aae0a5d..f3ccbc850 100644 --- a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java @@ -65,12 +65,12 @@ public final class CryptoUtils { * Definition of encryption algorithm. */ private static final String ALGORITHM = "AES"; - + /** - * AES Encryption Key environment variable for external configuration + * AES Encryption Key environment variable for external configuration. */ private static final String AES_ENCRYPTION_KEY = "AES_ENCRYPTION_KEY"; - + /** * Detailed definition of encryption algorithm. */ @@ -99,13 +99,11 @@ public final class CryptoUtils { /** * Encrypt a value based on the Clamp Encryption Key. * - * @param value - * The value to encrypt + * @param value The value to encrypt * @return The encrypted string - * @throws GeneralSecurityException - * In case of issue with the encryption - * @throws UnsupportedEncodingException - * In case of issue with the charset conversion + * @throws GeneralSecurityException In case of issue with the encryption + * @throws UnsupportedEncodingException In case of issue with the charset + * conversion */ public static String encrypt(String value) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS, "SunJCE"); @@ -119,14 +117,11 @@ public final class CryptoUtils { /** * Decrypt a value based on the Clamp Encryption Key. * - * @param message - * The encrypted string that must be decrypted using the Clamp - * Encryption Key + * @param message The encrypted string that must be decrypted using the Clamp + * Encryption Key * @return The String decrypted - * @throws GeneralSecurityException - * In case of issue with the encryption - * @throws DecoderException - * In case of issue to decode the HexString + * @throws GeneralSecurityException In case of issue with the encryption + * @throws DecoderException In case of issue to decode the HexString */ public static String decrypt(String message) throws GeneralSecurityException, DecoderException { byte[] encryptedMessage = Hex.decodeHex(message.toCharArray()); @@ -141,11 +136,9 @@ public final class CryptoUtils { /** * Method used to generate the SecretKeySpec from a Base64 String. * - * @param keyString - * The key as a string in Base 64 + * @param keyString The key as a string in Base 64 * @return The SecretKeySpec created - * @throws DecoderException - * In case of issues with the decoding of Base64 + * @throws DecoderException In case of issues with the decoding of Base64 */ private static SecretKeySpec getSecretKeySpec(String keyString) throws DecoderException { byte[] key = Hex.decodeHex(keyString.toCharArray()); @@ -155,8 +148,7 @@ public final class CryptoUtils { /** * Reads SecretKeySpec from file specified by propertiesFileName. * - * @param propertiesFileName - * File name with properties + * @param propertiesFileName File name with properties * @return SecretKeySpec secret key spec read from propertiesFileName */ private static SecretKeySpec readSecretKeySpec(String propertiesFileName) { @@ -165,7 +157,7 @@ public final class CryptoUtils { // Workaround fix to make encryption key configurable // System environment variable takes precedence for over clds/key.properties String encryptionKey = System.getenv(AES_ENCRYPTION_KEY); - if(encryptionKey != null && encryptionKey.trim().length() > 0) { + if (encryptionKey != null && encryptionKey.trim().length() > 0) { return getSecretKeySpec(encryptionKey); } else { props.load(ResourceFileUtil.getResourceAsStream(propertiesFileName)); 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 163ab6913..1a6cca6b8 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -154,10 +154,10 @@ public class LoggingUtils { * @return A string with the request ID */ public static String getRequestId() { - String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + String requestId = MDC.get(OnapLogConstants.Mdcs.REQUEST_ID); if (requestId == null || requestId.isEmpty()) { requestId = UUID.randomUUID().toString(); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId); } return requestId; } @@ -182,13 +182,13 @@ public class LoggingUtils { MDC.clear(); checkNotNull(request); // Extract MDC values from standard HTTP headers. - final String requestId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID)); - final String invocationId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID)); - final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)); + final String requestId = defaultToUuid(request.getHeader(OnapLogConstants.Headers.REQUEST_ID)); + final String invocationId = defaultToUuid(request.getHeader(OnapLogConstants.Headers.INVOCATION_ID)); + final String partnerName = defaultToEmpty(request.getHeader(OnapLogConstants.Headers.PARTNER_NAME)); // Default the partner name to the user name used to login to clamp if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) { - MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler() + MDC.put(OnapLogConstants.Mdcs.PARTNER_NAME, new DefaultUserNameHandler() .retrieveUserName(SecurityContextHolder.getContext())); } @@ -196,25 +196,25 @@ public class LoggingUtils { // others, OR set them BEFORE or AFTER the invocation of #entering, // depending on where you need them to appear, OR extend the // ServiceDescriptor to add them. - MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + MDC.put(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_INSTANT)); - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); - MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr())); - MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, defaultToEmpty(request.getServerName())); - MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID)); + MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId); + MDC.put(OnapLogConstants.Mdcs.INVOCATION_ID, invocationId); + MDC.put(OnapLogConstants.Mdcs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr())); + MDC.put(OnapLogConstants.Mdcs.SERVER_FQDN, defaultToEmpty(request.getServerName())); + MDC.put(OnapLogConstants.Mdcs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID)); // Default the service name to the requestURI, in the event that // no value has been provided. if (serviceName == null || serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); + MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, request.getRequestURI()); } else { - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName); + MDC.put(OnapLogConstants.Mdcs.SERVICE_NAME, serviceName); } - this.mlogger.info(ONAPLogConstants.Markers.ENTRY); + this.mlogger.info(OnapLogConstants.Markers.ENTRY); } /** @@ -226,20 +226,20 @@ public class LoggingUtils { * @param severity response severity * @param status response status code */ - public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) { + public void exiting(String code, String descrption, Level severity, OnapLogConstants.ResponseStatus status) { try { - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code)); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption)); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity)); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status)); + MDC.put(OnapLogConstants.Mdcs.RESPONSE_CODE, defaultToEmpty(code)); + MDC.put(OnapLogConstants.Mdcs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption)); + MDC.put(OnapLogConstants.Mdcs.RESPONSE_SEVERITY, defaultToEmpty(severity)); + MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE, defaultToEmpty(status)); - ZonedDateTime startTime = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), + ZonedDateTime startTime = ZonedDateTime.parse(MDC.get(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP), DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC)); ZonedDateTime endTime = ZonedDateTime.now(ZoneOffset.UTC); - MDC.put(ONAPLogConstants.MDCs.END_TIMESTAMP, endTime.format(DateTimeFormatter.ISO_INSTANT)); + MDC.put(OnapLogConstants.Mdcs.END_TIMESTAMP, endTime.format(DateTimeFormatter.ISO_INSTANT)); long duration = ChronoUnit.MILLIS.between(startTime, endTime); - MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIMESTAMP, String.valueOf(duration)); - this.mlogger.info(ONAPLogConstants.Markers.EXIT); + MDC.put(OnapLogConstants.Mdcs.ELAPSED_TIMESTAMP, String.valueOf(duration)); + this.mlogger.info(OnapLogConstants.Markers.EXIT); } finally { MDC.clear(); @@ -284,8 +284,8 @@ public class LoggingUtils { // 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 + "}"); + this.mlogger.info(OnapLogConstants.Markers.INVOKE); + this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); } /** @@ -306,7 +306,7 @@ public class LoggingUtils { */ public void invokeReturn() { // Add the Invoke-return marker and clear the needed MDC - this.mlogger.info(ONAPLogConstants.Markers.INVOKE_RETURN); + this.mlogger.info(OnapLogConstants.Markers.INVOKE_RETURN); invokeReturnContext(); } @@ -343,7 +343,7 @@ public class LoggingUtils { * @param in to be filtered * @return input string or null */ - private static String defaultToUUID(final String in) { + private static String defaultToUuid(final String in) { if (in == null) { return UUID.randomUUID().toString(); } @@ -355,13 +355,13 @@ public class LoggingUtils { * * @param targetEntity Target entity (an external/sub component, for ex. "sdc") * @param targetServiceName Target service name (name of API invoked on target) - * @param invocationID The invocation ID + * @param invocationId The invocation ID */ - private void invokeContext(String targetEntity, String targetServiceName, String invocationID) { - MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, defaultToEmpty(targetEntity)); - MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName)); - MDC.put(ONAPLogConstants.MDCs.INVOCATIONID_OUT, invocationID); - MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + private void invokeContext(String targetEntity, String targetServiceName, String invocationId) { + MDC.put(OnapLogConstants.Mdcs.TARGET_ENTITY, defaultToEmpty(targetEntity)); + MDC.put(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName)); + MDC.put(OnapLogConstants.Mdcs.INVOCATIONID_OUT, invocationId); + MDC.put(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_INSTANT)); } @@ -370,30 +370,30 @@ public class LoggingUtils { * Clear target related logging variables in thread local data via MDC. */ private void invokeReturnContext() { - MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY); - MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); - MDC.remove(ONAPLogConstants.MDCs.INVOCATIONID_OUT); - MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP); + MDC.remove(OnapLogConstants.Mdcs.TARGET_ENTITY); + MDC.remove(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME); + 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, + 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))); + 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 + "}"); + this.mlogger.info(OnapLogConstants.Markers.INVOKE); + this.mlogger.info(OnapLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); return con; } } diff --git a/src/main/java/org/onap/clamp/clds/util/ONAPLogConstants.java b/src/main/java/org/onap/clamp/clds/util/OnapLogConstants.java index 906f8e033..3c896b907 100644 --- a/src/main/java/org/onap/clamp/clds/util/ONAPLogConstants.java +++ b/src/main/java/org/onap/clamp/clds/util/OnapLogConstants.java @@ -26,7 +26,7 @@ package org.onap.clamp.clds.util; /** * Constants for standard ONAP headers, MDCs, etc. */ -public final class ONAPLogConstants { +public final class OnapLogConstants { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @@ -37,7 +37,7 @@ public final class ONAPLogConstants { /** * Hide and forbid construction. */ - private ONAPLogConstants() { + private OnapLogConstants() { throw new UnsupportedOperationException(); } @@ -73,7 +73,7 @@ public final class ONAPLogConstants { /** * MDC name constants. */ - public static final class MDCs { + public static final class Mdcs { // Tracing. //////////////////////////////////////////////////////////// @@ -146,7 +146,7 @@ public final class ONAPLogConstants { /** * Hide and forbid construction. */ - private MDCs() { + private Mdcs() { throw new UnsupportedOperationException(); } } diff --git a/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java b/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java index e30107975..5deee4679 100644 --- a/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java +++ b/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java @@ -55,13 +55,11 @@ public final class ResourceFileUtil { * Return resource as a String. */ public static String getResourceAsString(String name) throws IOException { - InputStream is = getResourceAsStream(name); - Scanner scanner = new Scanner(is); - Scanner delimitedScanner = scanner.useDelimiter("\\A"); - String text = delimitedScanner.hasNext() ? delimitedScanner.next() : ""; - delimitedScanner.close(); - scanner.close(); - is.close(); - return text; + try (InputStream is = getResourceAsStream(name)) { + try (Scanner scanner = new Scanner(is)) { + Scanner delimitedScanner = scanner.useDelimiter("\\A"); + return delimitedScanner.hasNext() ? delimitedScanner.next() : ""; + } + } } } diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java b/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java index 7a1f122ed..a4a5a3847 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java @@ -40,7 +40,7 @@ public class AwtUtils { private static final int FONT_STYLE = Font.PLAIN; private static final String FONT_FACE = "SansSerif"; private static final Color TRANSPARENT = new Color(0.0f, 0.0f, 0.0f, 0.0f); - private static final int TEXT_PADDING = 5; + private static final int TEXT_PADDING = 5; private AwtUtils() { } @@ -58,12 +58,14 @@ public class AwtUtils { static void drawArrow(Graphics2D g2d, Point from, Point to, int lineThickness) { int x2 = to.x - lineThickness; g2d.drawLine(from.x, from.y, x2 - lineThickness, to.y); - g2d.drawPolygon(new int[]{x2 - ARROW_W, x2 - ARROW_W, x2}, new int[]{to.y - ARROW_H, to.y + ARROW_H, to.y}, 3); - g2d.fillPolygon(new int[]{x2 - ARROW_W, x2 - ARROW_W, x2}, new int[]{to.y - ARROW_H, to.y + ARROW_H, to.y}, 3); + g2d.drawPolygon(new int[] { x2 - ARROW_W, x2 - ARROW_W, x2 }, + new int[] { to.y - ARROW_H, to.y + ARROW_H, to.y }, 3); + g2d.fillPolygon(new int[] { x2 - ARROW_W, x2 - ARROW_W, x2 }, + new int[] { to.y - ARROW_H, to.y + ARROW_H, to.y }, 3); } private static void addText(Graphics2D g2d, String text, Rectangle rect) { - int textBoundingBoxLimit = rect.width - 2* TEXT_PADDING; + int textBoundingBoxLimit = rect.width - 2 * TEXT_PADDING; Font font = new Font(FONT_FACE, FONT_STYLE, FONT_SIZE); font = scaleFontToFit(text, textBoundingBoxLimit, g2d, font); Font oldFont = g2d.getFont(); @@ -71,21 +73,21 @@ public class AwtUtils { g2d.setFont(font); g2d.setColor(Color.BLACK); FontMetrics fm1 = g2d.getFontMetrics(); - float x1 = rect.x + (float)(rect.width - fm1.stringWidth(text)) / 2; - float y1 = rect.y + (float)(rect.height - fm1.getHeight()) / 2 + fm1.getAscent(); + float x1 = rect.x + (float) (rect.width - fm1.stringWidth(text)) / 2; + float y1 = rect.y + (float) (rect.height - fm1.getHeight()) / 2 + fm1.getAscent(); g2d.drawString(text, x1, y1); g2d.setFont(oldFont); } - private static Font scaleFontToFit(String text, int width, Graphics2D g2d, Font pFont) { - float fontSize = pFont.getSize(); - float fWidth = g2d.getFontMetrics(pFont).stringWidth(text); - if(fWidth <= width) { - return pFont; + private static Font scaleFontToFit(String text, int width, Graphics2D g2d, Font font) { + float fontSize = font.getSize(); + float stringWidth = g2d.getFontMetrics(font).stringWidth(text); + if (stringWidth <= width) { + return font; } - fontSize = ((float)width / fWidth) * fontSize; - return pFont.deriveFont(fontSize); + fontSize = (width / stringWidth) * fontSize; + return font.deriveFont(fontSize); } } diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraph.java b/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraph.java index 46aa67b7d..6b97de8e6 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraph.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraph.java @@ -39,7 +39,7 @@ public class ClampGraph { * * @return svg string */ - public String getAsSVG() { + public String getAsSvg() { if (Objects.isNull(svg) || svg.isEmpty()) { svg = XmlTools.exportXmlDocumentAsString(this.documentBuilder.getGroupingDocument()); } diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java b/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java index c4ced5ef6..8ded0cb87 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilder.java @@ -60,6 +60,11 @@ public class ClampGraphBuilder { return this; } + /** + * Build the SVG. + * + * @return Clamp graph (SVG) + */ public ClampGraph build() { if (microServices.isEmpty()) { throw new InvalidStateException("At least one microservice is required"); diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java b/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java index 5d37701fb..4b887e4d8 100644 --- a/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java @@ -29,6 +29,7 @@ import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.util.UUID; + import org.apache.batik.svggen.SVGGraphics2D; public class ImageBuilder { @@ -47,8 +48,8 @@ public class ImageBuilder { private static final int LINE_THICKNESS = 2; private static final int CIRCLE_RADIUS = 17; - ImageBuilder(SVGGraphics2D svgGraphics2D, DocumentBuilder documentBuilder, - Point startingPoint, int baseLength, int rectHeight) { + ImageBuilder(SVGGraphics2D svgGraphics2D, DocumentBuilder documentBuilder, Point startingPoint, int baseLength, + int rectHeight) { this.g2d = svgGraphics2D; this.documentBuilder = documentBuilder; this.currentPoint = new Point(startingPoint); @@ -69,7 +70,7 @@ public class ImageBuilder { ImageBuilder arrow() { String dataElementId = "Arrow-" + UUID.randomUUID().toString(); - Point to = new Point(currentPoint.x + (int)(baseLength*ARROW_TO_BASELINE_RATIO), currentPoint.y); + Point to = new Point(currentPoint.x + (int) (baseLength * ARROW_TO_BASELINE_RATIO), currentPoint.y); AwtUtils.drawArrow(g2d, currentPoint, to, LINE_THICKNESS); documentBuilder.pushChangestoDocument(g2d, dataElementId); currentPoint = to; @@ -77,16 +78,15 @@ public class ImageBuilder { } ImageBuilder circle(String dataElementId, int lineThickness) { - Point to = new Point(currentPoint.x + 2 * CIRCLE_RADIUS, currentPoint.y); - Shape circleStart = - new Ellipse2D.Double(currentPoint.x, currentPoint.y - CIRCLE_RADIUS, - 2 * CIRCLE_RADIUS, 2 * CIRCLE_RADIUS); + Shape circleStart = new Ellipse2D.Double(currentPoint.x, currentPoint.y - CIRCLE_RADIUS, 2 * CIRCLE_RADIUS, + 2 * CIRCLE_RADIUS); Stroke oldStroke = g2d.getStroke(); g2d.setStroke(new BasicStroke(lineThickness)); g2d.draw(circleStart); g2d.setStroke(oldStroke); documentBuilder.pushChangestoDocument(g2d, dataElementId); + Point to = new Point(currentPoint.x + 2 * CIRCLE_RADIUS, currentPoint.y); currentPoint = to; return this; } @@ -107,17 +107,18 @@ public class ImageBuilder { case POLICY: drawDiagonalLineForPolicy(point, width, height); break; + default: } } private void drawVerticalLineForCollector(Point point, int width, int height) { g2d.drawLine(point.x + width / COLLECTOR_LINE_RATIO, point.y, point.x + width / COLLECTOR_LINE_RATIO, - point.y + height); + point.y + height); } private void drawHorizontalLineForMicroService(Point point, int width, int height) { - int y = calculateMsHorizontalLineYCoordinate(point,height); - g2d.drawLine(point.x, y, point.x + width, y); + int pointY = calculateMsHorizontalLineYCoordinate(point, height); + g2d.drawLine(point.x, pointY, point.x + width, pointY); } private void drawDiagonalLineForPolicy(Point point, int width, int height) { @@ -125,13 +126,13 @@ public class ImageBuilder { } private int calculateMsHorizontalLineYCoordinate(Point point, int height) { - return (int)(point.y * height * MS_LINE_TO_HEIGHT_RATIO); + return (int) (point.y * height * MS_LINE_TO_HEIGHT_RATIO); } private Point coordinatesForRectangle(Point from, Point next) { - int x = from.x; - int y = from.y - next.y + LINE_THICKNESS / 2; - return new Point(x,y); + int pointX = from.x; + int pointY = from.y - next.y + LINE_THICKNESS / 2; + return new Point(pointX, pointY); } } diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java b/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java index ebb267f7b..af6caf932 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java @@ -48,7 +48,7 @@ public class Painter { /** * Constructor to create instance of Painter. * - * @param svgGraphics2D svg graphics + * @param svgGraphics2D svg graphics * @param documentBuilder document builder */ public Painter(SVGGraphics2D svgGraphics2D, DocumentBuilder documentBuilder) { @@ -61,7 +61,7 @@ public class Painter { int numOfRectangles = 2 + microServices.size(); int numOfArrows = numOfRectangles + 1; int baseLength = (canvasSize - 2 * CIRCLE_RADIUS) / (numOfArrows + numOfRectangles); - if(baseLength < MINIMUM_BASE_LENGTH) { + if (baseLength < MINIMUM_BASE_LENGTH) { baseLength = MINIMUM_BASE_LENGTH; } int rectHeight = (int) (baseLength / RECT_RATIO); @@ -77,7 +77,7 @@ public class Painter { } private void doTheActualDrawing(String collector, List<MicroService> microServices, String policy, - ImageBuilder ib) { + ImageBuilder ib) { ib.circle("start-circle", SLIM_LINE).arrow().rectangle(collector, RectTypes.COLECTOR, collector); for (MicroService ms : microServices) { diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java b/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java index f7bf92bfd..ae0c1729c 100644 --- a/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java @@ -34,15 +34,21 @@ import org.w3c.dom.Document; @Component public class SvgFacade { + /** + * Generate the SVG images from the microservice Chain. + * + * @param microServicesChain THe chain of microservices + * @return A String containing the SVG + */ public String getSvgImage(List<MicroService> microServicesChain) { SVGGraphics2D svgGraphics2D = new SVGGraphics2D(XmlTools.createEmptySvgDocument()); Document document = XmlTools.createEmptySvgDocument(); DocumentBuilder dp = new DocumentBuilder(document, svgGraphics2D.getDOMFactory()); - Painter p = new Painter(svgGraphics2D, dp); - ClampGraphBuilder cgp = new ClampGraphBuilder(p).collector("VES"); + Painter painter = new Painter(svgGraphics2D, dp); + ClampGraphBuilder cgp = new ClampGraphBuilder(painter).collector("VES"); cgp.addAllMicroServices(microServicesChain); ClampGraph cg = cgp.policy("OperationalPolicy").build(); - return cg.getAsSVG(); + return cg.getAsSvg(); } } diff --git a/src/main/java/org/onap/clamp/flow/log/FlowLogOperation.java b/src/main/java/org/onap/clamp/flow/log/FlowLogOperation.java index 3da93b26a..868e424e8 100644 --- a/src/main/java/org/onap/clamp/flow/log/FlowLogOperation.java +++ b/src/main/java/org/onap/clamp/flow/log/FlowLogOperation.java @@ -30,7 +30,7 @@ import javax.servlet.http.HttpServletRequest; import org.apache.camel.Exchange; import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.clds.util.ONAPLogConstants; +import org.onap.clamp.clds.util.OnapLogConstants; import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -57,18 +57,18 @@ public class FlowLogOperation { */ public void startLog(Exchange exchange, String serviceDesc) { util.entering(request, serviceDesc); - exchange.setProperty(ONAPLogConstants.Headers.REQUEST_ID, util.getProperties(ONAPLogConstants.MDCs.REQUEST_ID)); - exchange.setProperty(ONAPLogConstants.Headers.INVOCATION_ID, - util.getProperties(ONAPLogConstants.MDCs.INVOCATION_ID)); - exchange.setProperty(ONAPLogConstants.Headers.PARTNER_NAME, - util.getProperties(ONAPLogConstants.MDCs.PARTNER_NAME)); + exchange.setProperty(OnapLogConstants.Headers.REQUEST_ID, util.getProperties(OnapLogConstants.Mdcs.REQUEST_ID)); + exchange.setProperty(OnapLogConstants.Headers.INVOCATION_ID, + util.getProperties(OnapLogConstants.Mdcs.INVOCATION_ID)); + exchange.setProperty(OnapLogConstants.Headers.PARTNER_NAME, + util.getProperties(OnapLogConstants.Mdcs.PARTNER_NAME)); } /** * Generate the exiting log. */ public void endLog() { - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, OnapLogConstants.ResponseStatus.COMPLETED); } /** @@ -76,7 +76,7 @@ public class FlowLogOperation { */ public void errorLog() { util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "Failed", Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); + OnapLogConstants.ResponseStatus.ERROR); } /** diff --git a/src/main/java/org/onap/clamp/loop/components/external/DcaeComponent.java b/src/main/java/org/onap/clamp/loop/components/external/DcaeComponent.java index 35b3a454b..9b131299b 100644 --- a/src/main/java/org/onap/clamp/loop/components/external/DcaeComponent.java +++ b/src/main/java/org/onap/clamp/loop/components/external/DcaeComponent.java @@ -40,27 +40,27 @@ public class DcaeComponent extends ExternalComponent { private static final String DCAE_INPUTS = "inputs"; public static final ExternalComponentState BLUEPRINT_DEPLOYED = new ExternalComponentState("BLUEPRINT_DEPLOYED", - "The DCAE blueprint has been found in the DCAE inventory but not yet instancianted for this loop"); + "The DCAE blueprint has been found in the DCAE inventory but not yet instancianted for this loop"); public static final ExternalComponentState PROCESSING_MICROSERVICE_INSTALLATION = new ExternalComponentState( - "PROCESSING_MICROSERVICE_INSTALLATION", - "Clamp has requested DCAE to install the microservices defined in the DCAE blueprint and it's currently processing the request"); + "PROCESSING_MICROSERVICE_INSTALLATION", "Clamp has requested DCAE to install the microservices " + + "defined in the DCAE blueprint and it's currently processing the request"); public static final ExternalComponentState MICROSERVICE_INSTALLATION_FAILED = new ExternalComponentState( - "MICROSERVICE_INSTALLATION_FAILED", - "Clamp has requested DCAE to install the microservices defined in the DCAE blueprint and it failed"); + "MICROSERVICE_INSTALLATION_FAILED", + "Clamp has requested DCAE to install the microservices defined in the DCAE blueprint and it failed"); public static final ExternalComponentState MICROSERVICE_INSTALLED_SUCCESSFULLY = new ExternalComponentState( - "MICROSERVICE_INSTALLED_SUCCESSFULLY", - "Clamp has requested DCAE to install the DCAE blueprint and it has been installed successfully"); + "MICROSERVICE_INSTALLED_SUCCESSFULLY", + "Clamp has requested DCAE to install the DCAE blueprint and it has been installed successfully"); public static final ExternalComponentState PROCESSING_MICROSERVICE_UNINSTALLATION = new ExternalComponentState( - "PROCESSING_MICROSERVICE_UNINSTALLATION", - "Clamp has requested DCAE to uninstall the microservices defined in the DCAE blueprint and it's currently processing the request"); + "PROCESSING_MICROSERVICE_UNINSTALLATION", "Clamp has requested DCAE to uninstall the microservices " + + "defined in the DCAE blueprint and it's currently processing the request"); public static final ExternalComponentState MICROSERVICE_UNINSTALLATION_FAILED = new ExternalComponentState( - "MICROSERVICE_UNINSTALLATION_FAILED", - "Clamp has requested DCAE to uninstall the microservices defined in the DCAE blueprint and it failed"); + "MICROSERVICE_UNINSTALLATION_FAILED", + "Clamp has requested DCAE to uninstall the microservices defined in the DCAE blueprint and it failed"); public static final ExternalComponentState MICROSERVICE_UNINSTALLED_SUCCESSFULLY = new ExternalComponentState( - "MICROSERVICE_UNINSTALLED_SUCCESSFULLY", - "Clamp has requested DCAE to uninstall the DCAE blueprint and it has been uninstalled successfully"); + "MICROSERVICE_UNINSTALLED_SUCCESSFULLY", + "Clamp has requested DCAE to uninstall the DCAE blueprint and it has been uninstalled successfully"); public static final ExternalComponentState IN_ERROR = new ExternalComponentState("IN_ERROR", - "There was an error during the request done to DCAE, look at the logs or try again"); + "There was an error during the request done to DCAE, look at the logs or try again"); public DcaeComponent() { super(BLUEPRINT_DEPLOYED); @@ -71,6 +71,12 @@ public class DcaeComponent extends ExternalComponent { return "DCAE"; } + /** + * Convert the json response to a DcaeOperationStatusResponse. + * + * @param responseBody The DCAE response Json paylaod + * @return The dcae object provisioned + */ public static DcaeOperationStatusResponse convertDcaeResponse(String responseBody) { if (responseBody != null && !responseBody.isEmpty()) { return JsonUtils.GSON_JPA_MODEL.fromJson(responseBody, DcaeOperationStatusResponse.class); @@ -80,7 +86,7 @@ public class DcaeComponent extends ExternalComponent { } /** - * Generate the deployment id, it's random + * Generate the deployment id, it's random. * * @return The deployment id */ @@ -89,9 +95,10 @@ public class DcaeComponent extends ExternalComponent { } /** - * This method prepare the url returned by DCAE to check the status if fine. + * This method prepare the url returned by DCAE to check the status if fine. It + * extracts it from the dcaeResponse. * - * @param statusUrl + * @param dcaeResponse The dcae response object * @return the Right Url modified if needed */ public static String getStatusUrl(DcaeOperationStatusResponse dcaeResponse) { @@ -101,8 +108,7 @@ public class DcaeComponent extends ExternalComponent { /** * Return the deploy payload for DCAE. * - * @param loop - * The loop object + * @param loop The loop object * @return The payload used to send deploy closed loop request */ public static String getDeployPayload(Loop loop) { @@ -122,8 +128,7 @@ public class DcaeComponent extends ExternalComponent { /** * Return the uninstallation payload for DCAE. * - * @param loop - * The loop object + * @param loop The loop object * @return The payload in string (json) */ public static String getUndeployPayload(Loop loop) { @@ -136,7 +141,7 @@ public class DcaeComponent extends ExternalComponent { public ExternalComponentState computeState(Exchange camelExchange) { DcaeOperationStatusResponse dcaeResponse = (DcaeOperationStatusResponse) camelExchange.getIn().getExchange() - .getProperty("dcaeResponse"); + .getProperty("dcaeResponse"); if (dcaeResponse == null) { setState(BLUEPRINT_DEPLOYED); @@ -147,10 +152,10 @@ public class DcaeComponent extends ExternalComponent { } else if (dcaeResponse.getOperationType().equals("install") && dcaeResponse.getStatus().equals("failed")) { setState(MICROSERVICE_INSTALLATION_FAILED); } else if (dcaeResponse.getOperationType().equals("uninstall") - && dcaeResponse.getStatus().equals("succeeded")) { + && dcaeResponse.getStatus().equals("succeeded")) { setState(MICROSERVICE_UNINSTALLED_SUCCESSFULLY); } else if (dcaeResponse.getOperationType().equals("uninstall") - && dcaeResponse.getStatus().equals("processing")) { + && dcaeResponse.getStatus().equals("processing")) { setState(PROCESSING_MICROSERVICE_UNINSTALLATION); } else if (dcaeResponse.getOperationType().equals("uninstall") && dcaeResponse.getStatus().equals("failed")) { setState(MICROSERVICE_UNINSTALLATION_FAILED); diff --git a/src/main/java/org/onap/clamp/loop/components/external/ExternalComponentState.java b/src/main/java/org/onap/clamp/loop/components/external/ExternalComponentState.java index a220ee1d4..a57234af0 100644 --- a/src/main/java/org/onap/clamp/loop/components/external/ExternalComponentState.java +++ b/src/main/java/org/onap/clamp/loop/components/external/ExternalComponentState.java @@ -41,6 +41,14 @@ public class ExternalComponentState implements Comparable<ExternalComponentState private String description; private int stateLevel; + /** + * Constructor taking stateName, description and its level. + * + * @param stateName The stateName in string + * @param description The description in string + * @param level The level, higher value has higher priority and can't be + * down-graded + */ public ExternalComponentState(String stateName, String description, int level) { this.stateName = stateName; this.description = description; @@ -85,18 +93,23 @@ public class ExternalComponentState implements Comparable<ExternalComponentState @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } ExternalComponentState other = (ExternalComponentState) obj; if (stateName == null) { - if (other.stateName != null) + if (other.stateName != null) { return false; - } else if (!stateName.equals(other.stateName)) + } + } else if (!stateName.equals(other.stateName)) { return false; + } return true; } diff --git a/src/main/java/org/onap/clamp/loop/components/external/PolicyComponent.java b/src/main/java/org/onap/clamp/loop/components/external/PolicyComponent.java index 68d598b5f..9321423a9 100644 --- a/src/main/java/org/onap/clamp/loop/components/external/PolicyComponent.java +++ b/src/main/java/org/onap/clamp/loop/components/external/PolicyComponent.java @@ -53,6 +53,9 @@ public class PolicyComponent extends ExternalComponent { public static final ExternalComponentState SENT_AND_DEPLOYED = new ExternalComponentState("SENT_AND_DEPLOYED", "The policies defined have been created and deployed on the policy engine", 10); + /** + * Default constructor. + */ public PolicyComponent() { /* * We assume it's good by default as we will receive the state for each policy diff --git a/src/main/java/org/onap/clamp/loop/log/LoopLog.java b/src/main/java/org/onap/clamp/loop/log/LoopLog.java index 3feff254d..0e1153a32 100644 --- a/src/main/java/org/onap/clamp/loop/log/LoopLog.java +++ b/src/main/java/org/onap/clamp/loop/log/LoopLog.java @@ -87,6 +87,15 @@ public class LoopLog implements Serializable, Comparable<LoopLog> { public LoopLog() { } + /** + * Constructor For LoopLog taking message and logtype, logComponent and loop + * reference. + * + * @param message The message as string + * @param logType Type like INFO, WARN, DEBUG + * @param logComponent A String with DCAE, POLICY, CLAMP ,etc... + * @param loop The loop object that this log is about + */ public LoopLog(String message, LogType logType, String logComponent, Loop loop) { this.message = message; this.logType = logType; diff --git a/src/main/java/org/onap/clamp/policy/operational/LegacyOperationalPolicy.java b/src/main/java/org/onap/clamp/policy/operational/LegacyOperationalPolicy.java index 0b4040d0b..725bfe88b 100644 --- a/src/main/java/org/onap/clamp/policy/operational/LegacyOperationalPolicy.java +++ b/src/main/java/org/onap/clamp/policy/operational/LegacyOperationalPolicy.java @@ -155,16 +155,14 @@ public class LegacyOperationalPolicy { * @return The Yaml as string */ public static String createPolicyPayloadYamlLegacy(JsonElement operationalPolicyJsonElement) { - JsonElement opPolicy = fulfillPoliciesTreeField( - removeAllQuotes(reworkPayloadAttributes(operationalPolicyJsonElement.getAsJsonObject().deepCopy()))); - Map<?, ?> jsonMap = createMap(opPolicy); DumperOptions options = new DumperOptions(); options.setDefaultScalarStyle(ScalarStyle.PLAIN); options.setIndent(2); options.setPrettyFlow(true); // Policy can't support { } in the yaml options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - return (new Yaml(options)).dump(jsonMap); + return (new Yaml(options)).dump(createMap(fulfillPoliciesTreeField( + removeAllQuotes(reworkPayloadAttributes(operationalPolicyJsonElement.getAsJsonObject().deepCopy()))))); } /** diff --git a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java index 86f8ac391..c6ed49847 100644 --- a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java +++ b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java @@ -158,6 +158,11 @@ public class OperationalPolicy implements Serializable, Policy { return true; } + /** + * Create policy Yaml from json defined here. + * + * @return A string containing Yaml + */ public String createPolicyPayloadYaml() { JsonObject policyPayloadResult = new JsonObject(); @@ -184,21 +189,17 @@ public class OperationalPolicy implements Serializable, Policy { operationalPolicyDetails.add("properties", LegacyOperationalPolicy .reworkPayloadAttributes(this.configurationsJson.get("operational_policy").deepCopy())); - Gson gson = new GsonBuilder().create(); - - Map<?, ?> jsonMap = gson.fromJson(gson.toJson(policyPayloadResult), Map.class); - DumperOptions options = new DumperOptions(); options.setIndent(2); options.setPrettyFlow(true); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Gson gson = new GsonBuilder().create(); - return (new Yaml(options)).dump(jsonMap); + return (new Yaml(options)).dump(gson.fromJson(gson.toJson(policyPayloadResult), Map.class)); } @Override public String createPolicyPayload() throws UnsupportedEncodingException { - // Now using the legacy payload fo Dublin JsonObject payload = new JsonObject(); payload.addProperty("policy-id", this.getName()); |