diff options
Diffstat (limited to 'adapters')
48 files changed, 1118 insertions, 1318 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java index 4479a7f6c2..9212fbcc6c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java @@ -6,6 +6,8 @@ * ================================================================================ * Copyright (C) 2018 Nokia. * ================================================================================ + * 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 @@ -84,7 +86,6 @@ import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.CloudifyManager; import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; @@ -94,13 +95,15 @@ import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.utils.MsoCommonUtils; import org.onap.so.utils.CryptoUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ - + private static final String CLOUDIFY_ERROR = "CloudifyError"; private static final String CLOUDIFY = "Cloudify"; private static final String CREATE_DEPLOYMENT = "CreateDeployment"; @@ -111,14 +114,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Fetch cloud configuration each time (may be cached in CloudConfig class) @Autowired protected CloudConfig cloudConfig; - + @Autowired private Environment environment; - + @Autowired private PoConfig poConfig; - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoCloudifyUtils.class); + private static final Logger logger = LoggerFactory.getLogger(MsoCloudifyUtils.class); // Properties names and variables (with default values) protected String createPollIntervalProp = "org.onap.so.adapters.po.pollInterval"; @@ -126,7 +129,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ protected String createPollIntervalDefault = "15"; private String deletePollIntervalDefault = "15"; - + private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); /** @@ -134,7 +137,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * cloud location and tenant. The blueprint identifier and parameter map are passed in * as arguments, along with the cloud access credentials. The blueprint should have been * previously uploaded to Cloudify. - * + * * It is expected that parameters have been validated and contain at minimum the required * parameters for the given template with no extra (undefined) parameters.. * @@ -176,17 +179,17 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); - LOGGER.debug ("Ready to Create Deployment (" + deploymentId + ") with input params: " + inputs); + logger.debug("Ready to Create Deployment ({}) with input params: {}", deploymentId, inputs); // Build up the inputs, including: // - from provided "environment" file // - passed in by caller // - special input for cloud-specific Credentials Map<String,Object> expandedInputs = new HashMap<> (inputs); - + String platform = cloudSite.get().getPlatform(); if (platform == null || platform.equals("") || platform.equalsIgnoreCase("OPENSTACK")) { // Create the Cloudify OpenstackConfig with the credentials @@ -197,7 +200,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ AzureConfig azureConfig = getAzureConfig (cloudSite.get(), tenantId); expandedInputs.put("azure_config", azureConfig); } - + // Build up the parameters to create a new deployment CreateDeploymentParams deploymentParams = new CreateDeploymentParams(); deploymentParams.setBlueprintId(blueprintId); @@ -206,8 +209,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ Deployment deployment = null; try { CreateDeployment createDeploymentRequest = cloudify.deployments().create(deploymentId, deploymentParams); - LOGGER.debug (createDeploymentRequest.toString()); - + logger.debug(createDeploymentRequest.toString()); + deployment = executeAndRecordCloudifyRequest (createDeploymentRequest); } catch (CloudifyResponseException e) { @@ -220,7 +223,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw me; } else { // Convert the CloudifyResponseException to an MsoException - LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage()); + logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage()); MsoException me = cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT); me.setCategory (MsoExceptionCategory.OPENSTACK); throw me; @@ -246,9 +249,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ */ int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault)); int pollTimeout = (timeoutMinutes * 60) + createPollInterval; - + Execution installWorkflow = null; - + try { installWorkflow = executeWorkflow (cloudify, deploymentId, "install", null, pollForCompletion, pollTimeout, createPollInterval); @@ -267,17 +270,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // The workflow completed with errors. Must try to back it out. if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Deployment installation failed, backout deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Deployment Installation, backout suppressed"); - } + logger.warn("{} Deployment installation failed, backout deletion suppressed {} {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + "Exception in Deployment Installation, backout suppressed"); + } else { // Poll on delete if we rollback - use same values for now int deletePollInterval = createPollInterval; int deletePollTimeout = pollTimeout; - + try { // Run the uninstall to undo the install Execution uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval); - + if (uninstallWorkflow.getStatus().equals(TERMINATED)) { // The uninstall completed. Delete the deployment itself @@ -286,16 +291,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } else { // Didn't uninstall successfully. Log this error - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Deployment: Cloudify error rolling back deployment install: " + installWorkflow.getError(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Cloudify error rolling back deployment installation"); - } + logger.error("{} Create Deployment: Cloudify error rolling back deployment install: {} {}", + MessageEnum.RA_CREATE_STACK_ERR, installWorkflow.getError(), + MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } } catch (Exception e) { // Catch-all for backout errors trying to uninstall/delete // Log this error, and return the original exception - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back deployment install: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back deployment installation"); - } + logger.error("{} Create Stack: Nested exception rolling back deployment install: {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); + } } - + MsoCloudifyException me = new MsoCloudifyException (0, "Workflow Execution Failed", installWorkflow.getError()); me.addContext (CREATE_DEPLOYMENT); @@ -307,18 +315,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Deployment installation failed, backout deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Deployment Installation, backout suppressed"); - } + logger.warn("{} Deployment installation failed, backout deletion suppressed {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } else { // Poll on delete if we rollback - use same values for now int deletePollInterval = createPollInterval; int deletePollTimeout = pollTimeout; - + try { // Run the uninstall to undo the install. // Always try to run it, as it should be idempotent executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval); - + // Delete the deployment itself DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId); executeAndRecordCloudifyRequest (deleteRequest); @@ -326,9 +335,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ catch (Exception e) { // Catch-all for backout errors trying to uninstall/delete // Log this error, and return the original exception - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back deployment install: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back deployment installation"); - - } + logger.error("{} Create Stack: Nested exception rolling back deployment install: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); + } } // Propagate the original exception from Stack Query. @@ -350,14 +359,15 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ DeploymentOutputs deploymentOutputs = null; try { GetDeploymentOutputs queryDeploymentOutputs = cloudify.deployments().outputsById(deploymentId); - LOGGER.debug (queryDeploymentOutputs.toString()); - + logger.debug(queryDeploymentOutputs.toString()); + deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs); } catch (CloudifyConnectException ce) { // Couldn't connect to Cloudify - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "QueryDeploymentOutputs: Cloudify connection failure: " + ce, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "QueryDeploymentOutputs: Cloudify connection failure"); - throw new MsoIOException (ce.getMessage(), ce); + logger.error("{} QueryDeploymentOutputs: Cloudify connection failure: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), ce); + throw new MsoIOException (ce.getMessage(), ce); } catch (CloudifyResponseException re) { if (re.getStatus () == 404) { @@ -370,10 +380,10 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Catch-all throw new MsoAdapterException (e.getMessage(), e); } - + return deploymentOutputs; } - + /* * Execute a workflow on a deployment. Handle polling for completion with timeout. * Return the final Execution object with status. @@ -383,22 +393,22 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ private Execution executeWorkflow (Cloudify cloudify, String deploymentId, String workflowId, Map<String,Object> workflowParams, boolean pollForCompletion, int timeout, int pollInterval) throws MsoCloudifyException { - LOGGER.debug("Executing '" + workflowId + "' workflow on deployment '" + deploymentId + "'"); + logger.debug("Executing '{}' workflow on deployment '{}'", workflowId, deploymentId); StartExecutionParams executeParams = new StartExecutionParams(); executeParams.setWorkflowId(workflowId); executeParams.setDeploymentId(deploymentId); executeParams.setParameters(workflowParams); - + Execution execution = null; String executionId = null; String command = "start"; Exception savedException = null; - + try { StartExecution executionRequest = cloudify.executions().start(executeParams); - LOGGER.debug (executionRequest.toString()); - execution = executeAndRecordCloudifyRequest (executionRequest); + logger.debug(executionRequest.toString()); + execution = executeAndRecordCloudifyRequest (executionRequest); executionId = execution.getId(); if (!pollForCompletion) { @@ -409,27 +419,28 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Enter polling loop boolean timedOut = false; int pollTimeout = timeout; - + String status = execution.getStatus(); - + // Create a reusable cloudify query request GetExecution queryExecution = cloudify.executions().byId(executionId); command = "query"; - + while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED))) { // workflow is still running; check for timeout if (pollTimeout <= 0) { - LOGGER.debug ("workflow " + execution.getWorkflowId() + " timed out on deployment " + execution.getDeploymentId()); - timedOut = true; + logger.debug("workflow {} timed out on deployment {}", execution.getWorkflowId(), + execution.getDeploymentId()); + timedOut = true; continue; } - + sleep(pollInterval * 1000L); pollTimeout -= pollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); - + logger.debug("pollTimeout remaining: " + pollTimeout); + execution = queryExecution.execute(); status = execution.getStatus(); } @@ -437,105 +448,112 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Broke the loop. Check again for a terminal state if (status.equals(TERMINATED)){ // Success! - LOGGER.debug ("Workflow '" + workflowId + "' completed successfully on deployment '" + deploymentId + "'"); - return execution; + logger.debug("Workflow '{}' completed successfully on deployment '{}'", workflowId, deploymentId); + return execution; } else if (status.equals("failed")){ // Workflow failed. Log it and return the execution object (don't throw exception here) - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow failure: " + execution.getError(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow: Failed: " + execution.getError()); - return execution; + logger.error("{} Cloudify workflow failure: {} {} Execute Workflow: Failed: {}", + MessageEnum.RA_CREATE_STACK_ERR, execution.getError(), + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), execution.getError()); + return execution; } else if (status.equals(CANCELLED)){ // Workflow was cancelled, leaving the deployment in an indeterminate state. Log it and return the execution object (don't throw exception here) - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow cancelled. Deployment is in an indeterminate state", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow cancelled: " + workflowId); - return execution; + logger.error("{} Cloudify workflow cancelled. Deployment is in an indeterminate state {} {} {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + "Execute Workflow cancelled: ", workflowId); + return execution; } else { // Can only get here after a timeout - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow timeout", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow: Timed Out"); - } + logger.error("{} Cloudify workflow timeout {} Execute Workflow: Timed Out", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } } catch (CloudifyConnectException ce) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Cloudify connection failure: " + ce, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Cloudify connection failure"); - savedException = ce; + logger.error("{} {} Execute Workflow ({} {}): Cloudify connection failure {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), command, ce); + savedException = ce; } catch (CloudifyResponseException re) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Cloudify response error: " + re, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Cloudify error" + re.getMessage()); - savedException = re; + logger.error("{} {} Execute Workflow ({}): Cloudify response error {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), command, re.getMessage(), re); + savedException = re; } catch (RuntimeException e) { // Catch-all - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Unexpected error: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Internal error" + e.getMessage()); - savedException = e; + logger.error("{} {} Execute Workflow ({}): Internal error {}", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), command, e.getMessage(), e); + savedException = e; } - + // Get to this point ONLY on an error or timeout // The cloudify execution is still running (we've not received a terminal status), // so try to Cancel it. CancelExecutionParams cancelParams = new CancelExecutionParams(); cancelParams.setAction("cancel"); // TODO: Use force_cancel? - + Execution cancelExecution = null; - + try { CancelExecution cancelRequest = cloudify.executions().cancel(executionId, cancelParams); - LOGGER.debug (cancelRequest.toString()); - cancelExecution = cancelRequest.execute(); + logger.debug(cancelRequest.toString()); + cancelExecution = cancelRequest.execute(); // Enter polling loop boolean timedOut = false; int cancelTimeout = timeout; // TODO: For now, just use same timeout - + String status = cancelExecution.getStatus(); - + // Poll for completion. Create a reusable cloudify query request GetExecution queryExecution = cloudify.executions().byId(executionId); - + while (!timedOut && !status.equals(CANCELLED)) { // workflow is still running; check for timeout if (cancelTimeout <= 0) { - LOGGER.debug ("Cancel timeout for workflow " + workflowId + " on deployment " + deploymentId); - timedOut = true; + logger.debug("Cancel timeout for workflow {} on deployment {}", workflowId, deploymentId); + timedOut = true; continue; } - + sleep(pollInterval * 1000L); cancelTimeout -= pollInterval; - LOGGER.debug("pollTimeout remaining: " + cancelTimeout); - - execution = queryExecution.execute(); + logger.debug("pollTimeout remaining: {}", cancelTimeout); + + execution = queryExecution.execute(); status = execution.getStatus(); } // Broke the loop. Check again for a terminal state if (status.equals(CANCELLED)){ // Finished cancelling. Return the original exception - LOGGER.debug ("Cancel workflow " + workflowId + " completed on deployment " + deploymentId); - throw new MsoCloudifyException (-1, "", "", savedException); + logger.debug("Cancel workflow {} completed on deployment {}", workflowId, deploymentId); + throw new MsoCloudifyException (-1, "", "", savedException); } else { // Can only get here after a timeout - LOGGER.debug ("Cancel workflow " + workflowId + " timeout out on deployment " + deploymentId); - MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); + logger.debug("Cancel workflow {} timeout out on deployment {}", workflowId, deploymentId); + MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); exception.setPendingWorkflow(true); throw exception; } } catch (Exception e) { // Catch-all. Log the message and throw the original exception -// LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Unexpected error: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Internal error" + e.getMessage()); - LOGGER.debug ("Cancel workflow " + workflowId + " failed for deployment " + deploymentId + ": " + e.getMessage()); - MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); + logger.debug("Cancel workflow {} failed for deployment : {} {}", workflowId, deploymentId, e); + MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); exception.setPendingWorkflow(true); throw exception; } - } - + } + + - /** * Query for a Cloudify Deployment (by Name). This call will always return a * DeploymentInfo object. If the deployment does not exist, an "empty" DeploymentInfo will be @@ -549,23 +567,23 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ public DeploymentInfo queryDeployment (String cloudSiteId, String tenantId, String deploymentId) throws MsoException { - LOGGER.debug ("Query Cloudify Deployment: " + deploymentId + " in tenant " + tenantId); + logger.debug ("Query Cloudify Deployment: {} in tenant {}", deploymentId, tenantId); // Obtain the cloud site information where we will create the stack Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId); if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); - + // Build and send the Cloudify request Deployment deployment = new Deployment(); DeploymentOutputs outputs = null; try { GetDeployment queryDeployment = cloudify.deployments().byId(deploymentId); - LOGGER.debug (queryDeployment.toString()); - + logger.debug(queryDeployment.toString()); + // deployment = queryDeployment.execute(); deployment = executeAndRecordCloudifyRequest(queryDeployment); @@ -574,7 +592,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Next look for the latest execution ListExecutions listExecutions = cloudify.executions().listFiltered ("deployment_id=" + deploymentId, "-created_at"); Executions executions = listExecutions.execute(); - + // If no executions, does this give NOT_FOUND or empty set? if (executions.getItems().isEmpty()) { return new DeploymentInfoBuilder() @@ -593,8 +611,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } catch (CloudifyConnectException ce) { // Couldn't connect to Cloudify - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "QueryDeployment: Cloudify connection failure: " + ce, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "QueryDeployment: Cloudify connection failure"); - throw new MsoIOException (ce.getMessage(), ce); + logger.error("{} QueryDeployment: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), ce); + throw new MsoIOException (ce.getMessage(), ce); } catch (CloudifyResponseException re) { if (re.getStatus () == 404) { @@ -618,7 +637,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw new MsoAdapterException (e.getMessage(), e); } } - + /** * Delete a Cloudify deployment (by ID). If the deployment is not found, it will be @@ -645,17 +664,17 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); - LOGGER.debug ("Ready to Uninstall/Delete Deployment (" + deploymentId + ")"); + logger.debug ("Ready to Uninstall/Delete Deployment ({})", deploymentId); // Query first to save the trouble if deployment not found Deployment deployment = null; try { GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId); - LOGGER.debug (queryDeploymentRequest.toString()); - + logger.debug(queryDeploymentRequest.toString()); + deployment = executeAndRecordCloudifyRequest (queryDeploymentRequest); } catch (CloudifyResponseException e) { @@ -664,15 +683,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (e.getStatus () == 404) { // Deployment doesn't exist. Return a "NOTFOUND" DeploymentInfo object // TODO: Should return NULL? - LOGGER.debug("Deployment requested for deletion does not exist: " + deploymentId); - return new DeploymentInfoBuilder() + logger.debug("Deployment requested for deletion does not exist: {}", deploymentId); + return new DeploymentInfoBuilder() .withId(deploymentId) .withStatus(DeploymentStatus.NOTFOUND) .build(); } else { // Convert the CloudifyResponseException to an MsoOpenstackException - LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage()); - MsoException me = cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT); + logger.debug("ERROR STATUS = {}, \n {}\n {}\n {}", e.getStatus(), e.getMessage(), + e.getLocalizedMessage(), e); + MsoException me = cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT); me.setCategory (MsoExceptionCategory.INTERNAL); throw me; } @@ -696,16 +716,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // TODO: No deletePollInterval that I'm aware of. Use the create interval int deletePollInterval = Integer.parseInt(this.environment.getProperty (deletePollIntervalProp, deletePollIntervalDefault)); int pollTimeout = (timeoutMinutes * 60) + deletePollInterval; - + Execution uninstallWorkflow = null; - + try { uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval); if (uninstallWorkflow.getStatus().equals(TERMINATED)) { // Successful uninstall. - LOGGER.debug("Uninstall successful for deployment " + deploymentId); - } + logger.debug("Uninstall successful for deployment {}", deploymentId); + } else { // The uninstall workflow completed with an error. Must fail the request, but will // leave the deployment in an indeterminate state, as cloud resources may still exist. @@ -727,11 +747,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Next step is to delete the deployment itself try { DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId); - LOGGER.debug(deleteRequest.toString()); - + logger.debug(deleteRequest.toString()); + // The delete request returns the deleted deployment deployment = deleteRequest.execute(); - + } catch (CloudifyConnectException ce) { // Failed to delete. Must fail the request, but will leave the (uninstalled) @@ -766,12 +786,12 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ .build(); } - + /** * Check if a blueprint is available for use at a targeted cloud site. * This requires checking the Cloudify Manager which is servicing that * cloud site to see if the specified blueprint has been loaded. - * + * * @param cloudSiteId The cloud site where the blueprint is needed * @param blueprintId The ID for the blueprint in Cloudify */ @@ -783,14 +803,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId); try { Blueprint bp = getRequest.execute(); - LOGGER.debug("Blueprint exists: " + bp.getId()); - return true; + logger.debug("Blueprint exists: {}", bp.getId()); + return true; } catch (CloudifyResponseException ce) { if (ce.getStatus() == 404) { @@ -802,14 +822,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw e; } } - + /** * Upload a blueprint to the Cloudify Manager that is servicing a Cloud Site. * The blueprint currently must be structured as a single directory with all * of the required files. One of those files is designated the "main file" * for the blueprint. Files are provided as byte arrays, though expect only * text files will be distributed from ASDC and stored by MSO. - * + * * Cloudify requires a single root directory in its blueprint zip files. * The requested blueprint ID will also be used as the directory. * All of the files will be added to this directory in the zip file. @@ -826,16 +846,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); boolean blueprintUploaded = uploadBlueprint (cloudify, blueprintId, mainFileName, blueprintFiles); - + if (!blueprintUploaded && failIfExists) { throw new MsoAdapterException ("Blueprint already exists"); } } - + /* * Common method to load a blueprint. May be called from */ @@ -846,20 +866,20 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId); try { Blueprint bp = getRequest.execute(); - LOGGER.debug("Blueprint " + bp.getId() + " already exists."); - return false; + logger.debug("Blueprint {} already exists.", bp.getId()); + return false; } catch (CloudifyResponseException ce) { if (ce.getStatus() == 404) { // This is the expected result. - LOGGER.debug("Verified that Blueprint doesn't exist yet"); - } else { + logger.debug("Verified that Blueprint doesn't exist yet"); + } else { throw ce; } } catch (Exception e) { throw e; } - + // Create a blueprint ZIP file in memory ByteArrayOutputStream zipBuffer = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(zipBuffer); @@ -869,7 +889,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ String rootDir = blueprintId + ((blueprintId.endsWith("/") ? "" : "/")); zipOut.putNextEntry(new ZipEntry (rootDir)); zipOut.closeEntry(); - + for (String fileName : blueprintFiles.keySet()) { ZipEntry ze = new ZipEntry (rootDir + fileName); zipOut.putNextEntry (ze); @@ -881,15 +901,15 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ catch (IOException e) { // Since we're writing to a byte array, this should never happen } - LOGGER.debug ("Blueprint zip file size: " + zipBuffer.size()); - - // Ready to upload the blueprint zip - + logger.debug("Blueprint zip file size: {}", zipBuffer.size()); + + // Ready to upload the blueprint zip + try (InputStream blueprintStream = new ByteArrayInputStream (zipBuffer.toByteArray())) { UploadBlueprint uploadRequest = cloudify.blueprints().uploadFromStream(blueprintId, mainFileName, blueprintStream); Blueprint blueprint = uploadRequest.execute(); - System.out.println("Successfully uploaded blueprint " + blueprint.getId()); - } + logger.debug("Successfully uploaded blueprint {}", blueprint.getId()); + } catch (CloudifyResponseException | CloudifyConnectException e) { throw cloudifyExceptionToMsoException (e, "UPLOAD_BLUEPRINT"); } @@ -903,8 +923,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ return true; } - - + + // --------------------------------------------------------------- // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS @@ -957,7 +977,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ return executeAndRecordCloudifyRequest (request); } catch (CloudifyResponseException e) { if (e.getStatus () == 404) { - LOGGER.debug ("queryDeployment - not found: " + deploymentId); + logger.debug ("queryDeployment - not found: {}", deploymentId); return null; } else { // Convert the CloudifyResponseException to an MsoCloudifyException @@ -974,34 +994,34 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ Map<String, Object> otherStackOutputs, boolean overWrite) { if (inputs == null || otherStackOutputs == null) return; - + for (Map.Entry<String, Object> entry : otherStackOutputs.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); - + if (value instanceof JsonNode) { // This is a bit of mess - but I think it's the least impacting // let's convert it BACK to a string - then it will get converted back later try { inputs.put(key, this.convertNode((JsonNode) value)); } catch (Exception e) { - LOGGER.debug("WARNING: unable to convert JsonNode output value for "+ key); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("WARNING: unable to convert JsonNode output value for {}", key); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } else if (value instanceof java.util.LinkedHashMap) { - LOGGER.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); - try { + logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); + try { inputs.put(key, JSON_MAPPER.writeValueAsString(value)); } catch (Exception e) { - LOGGER.debug("WARNING: unable to convert LinkedHashMap output value for "+ key); - } + logger.debug("WARNING: unable to convert LinkedHashMap output value for {}", key); + } } else { // just try to cast it - could be an integer or some such try { inputs.put(key, (String) value); } catch (Exception e) { - LOGGER.debug("WARNING: unable to convert output value for "+ key); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("WARNING: unable to convert output value for {}", key); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } } @@ -1015,42 +1035,42 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ public Object convertInputValue (String inputValue, HeatTemplateParam templateParam) { String type = templateParam.getParamType(); - LOGGER.debug("Parameter: " + templateParam.getParamName() + " is of type " + type); - - if (type.equalsIgnoreCase("number")) { + logger.debug("Parameter: {} is of type {}", templateParam.getParamName(), type); + + if (type.equalsIgnoreCase("number")) { try { return Integer.valueOf(inputValue); } catch (Exception e) { - LOGGER.debug("Unable to convert " + inputValue + " to an integer!"); - return null; + logger.debug("Unable to convert {} to an integer!", inputValue); + return null; } } else if (type.equalsIgnoreCase("json")) { try { return new ObjectMapper().readTree(inputValue); } catch (Exception e) { - LOGGER.debug("Unable to convert " + inputValue + " to a JsonNode!"); - return null; + logger.debug("Unable to convert {} to a JsonNode!", inputValue); + return null; } } else if (type.equalsIgnoreCase("boolean")) { return new Boolean(inputValue); } - + // Nothing else matched. Return the original string return inputValue; } - - + + private String convertNode(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); return JSON_MAPPER.writeValueAsString(obj); } catch (JsonParseException jpe) { - LOGGER.debug("Error converting json to string " + jpe.getMessage()); - } catch (Exception e) { - LOGGER.debug("Error converting json to string " + e.getMessage()); - } + logger.debug("Error converting json to string {}", jpe); + } catch (Exception e) { + logger.debug("Error converting json to string {}", e); + } return "[Error converting json to string]"; } @@ -1061,7 +1081,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * sub-category that identifies the specific call (using the real * cloudify-client classname of the CloudifyRequest<T> parameter). */ - + protected <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request) { @@ -1072,11 +1092,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } else { requestType = request.getClass ().getSimpleName (); } - + int retryDelay = poConfig.getRetryDelay(); int retryCount = poConfig.getRetryCount(); String retryCodes = poConfig.getRetryCodes(); - + // Run the actual command. All exceptions will be propagated while (true) { @@ -1087,19 +1107,23 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ boolean retry = false; if (retryCodes != null ) { int code = e.getStatus(); - LOGGER.debug ("Config values RetryDelay:" + retryDelay + " RetryCount:" + retryCount + " RetryCodes:" + retryCodes + " ResponseCode:" + code); - for (String rCode : retryCodes.split (",")) { + logger.debug("Config values RetryDelay: {} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay, + retryCount, retryCodes, code); + for (String rCode : retryCodes.split (",")) { try { if (retryCount > 0 && code == Integer.parseInt (rCode)) { retryCount--; retry = true; - LOGGER.debug ("CloudifyResponseException ResponseCode:" + code + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); - break; + logger.debug( + "CloudifyResponseException ResponseCode:{} request:{} Retry indicated. Attempts remaining:{}", + code, requestType, retryCount); + break; } } catch (NumberFormatException e1) { - LOGGER.error (MessageEnum.RA_CONFIG_EXC, "No retries. Exception in parsing retry code in config:" + rCode, "", "", MsoLogger.ErrorCode.SchemaError, "Exception in parsing retry code in config"); - throw e; + logger.error("{} No retries. Exception in parsing retry code in config:{} {}", + MessageEnum.RA_CONFIG_EXC, rCode, MsoLogger.ErrorCode.SchemaError.getValue()); + throw e; } } } @@ -1115,12 +1139,12 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (retryCount > 0) { retryCount--; - LOGGER.debug (" request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); - sleep(retryDelay * 1000L); + logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount); + sleep(retryDelay * 1000L); } else throw e; - + } } } @@ -1137,16 +1161,18 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ try { // Failed Cloudify calls return an error entity body. CloudifyError error = re.getResponse ().getErrorEntity (CloudifyError.class); - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "Cloudify Error on " + context + ": " + error.getErrorCode(), CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Exception - Cloudify Error on " + context); + logger.error("{} {} {} Exception - Cloudify Error on {}: {}", MessageEnum.RA_CONNECTION_EXCEPTION, + CLOUDIFY, MsoLogger.ErrorCode.DataError.getValue(), context, error.getErrorCode()); String fullError = error.getErrorCode() + ": " + error.getMessage(); - LOGGER.debug(fullError); + logger.debug(fullError); me = new MsoCloudifyException (re.getStatus(), re.getMessage(), fullError); } catch (Exception e2) { // Couldn't parse the body as a "CloudifyError". Report the original HTTP error. - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); - me = new MsoCloudifyException (re.getStatus (), re.getMessage (), ""); + logger.error("{} {} {} Exception - HTTP Error on {}: {}, {} ", MessageEnum.RA_CONNECTION_EXCEPTION, + CLOUDIFY, MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2); + me = new MsoCloudifyException (re.getStatus (), re.getMessage (), ""); } // Add the context of the error @@ -1164,8 +1190,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Generate an alarm for all connection errors. - LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "Cloudify connection error on " + context + ": " + e, CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Cloudify connection error on " + context); - } + logger.error("{} {} {} Cloudify connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, + MsoLogger.ErrorCode.DataError.getValue(), context, e); + } return me; } @@ -1173,17 +1200,17 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ /******************************************************************************* - * + * * Methods (and associated utilities) to implement the VduPlugin interface - * + * *******************************************************************************/ - + /** * VduPlugin interface for instantiate function. - * + * * This one is a bit more complex, in that it will first upload the blueprint if needed, * then create the Cloudify deployment and execute the install workflow. - * + * * This implementation also merges any parameters defined in the ENV file with the other * other input parameters for any undefined parameters). * The basic MsoCloudifyUtils separates blueprint management from deploument actions, @@ -1200,40 +1227,40 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { String cloudSiteId = cloudInfo.getCloudSiteId(); String tenantId = cloudInfo.getTenantId(); - + // Translate the VDU ModelInformation structure to that which is needed for // creating and uploading a blueprint. Use the model customization UUID as // the blueprint identifier. - + String blueprintId = vduModel.getModelCustomizationUUID(); - + try { - + if (! isBlueprintLoaded (cloudSiteId, blueprintId)) { - LOGGER.debug ("Blueprint " + blueprintId + " is not loaded. Will upload it now."); - + logger.debug("Blueprint {} is not loaded. Will upload it now.", blueprintId); + // Prepare the blueprint inputs. Need the set of blueprint templates and files, // plus the main blueprint name. Map<String,byte[]> blueprintFiles = new HashMap<>(); String mainTemplate = ""; - + // Add all of the blueprint artifacts from the VDU model List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); for (VduArtifact vduArtifact: vduArtifacts) { // Add all artifacts to the blueprint, with one exception. // ENVIRONMENT files will be processed later as additional parameters. - + ArtifactType artifactType = vduArtifact.getType(); if (artifactType != ArtifactType.ENVIRONMENT) { blueprintFiles.put(vduArtifact.getName(), vduArtifact.getContent()); - + if (artifactType == ArtifactType.MAIN_TEMPLATE) { mainTemplate = vduArtifact.getName(); } } } - + // Upload the blueprint package uploadBlueprint(cloudSiteId, blueprintId, mainTemplate, blueprintFiles, false); } @@ -1241,12 +1268,12 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ catch (Exception e) { throw new VduException ("CloudifyUtils (instantiateVDU): blueprint Exception", e); } - - + + // Next, create and install a new deployment based on the blueprint. // For Cloudify, the deploymentId is specified by the client. Just use the instance name // as the ID. - + try { // Query the Cloudify Deployment object and populate a VduInstance DeploymentInfo deployment = createAndInstallDeployment (cloudSiteId, @@ -1257,15 +1284,15 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ true, // (poll for completion) vduModel.getTimeoutMinutes(), rollbackOnFailure); - + return deploymentInfoToVduInstance(deployment); } catch (Exception e) { throw new VduException ("CloudifyUtils (instantiateVDU): Create-and-install-deployment Exception", e); } } - - + + /** * VduPlugin interface for query function. */ @@ -1275,19 +1302,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { String cloudSiteId = cloudInfo.getCloudSiteId(); String tenantId = cloudInfo.getTenantId(); - + try { // Query the Cloudify Deployment object and populate a VduInstance DeploymentInfo deployment = queryDeployment (cloudSiteId, tenantId, instanceId); - + return deploymentInfoToVduInstance(deployment); } catch (Exception e) { throw new VduException ("Query VDU Exception", e); } } - - + + /** * VduPlugin interface for delete function. */ @@ -1297,11 +1324,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { String cloudSiteId = cloudInfo.getCloudSiteId(); String tenantId = cloudInfo.getTenantId(); - + try { // Uninstall and delete the Cloudify Deployment DeploymentInfo deployment = uninstallAndDeleteDeployment (cloudSiteId, tenantId, instanceId, timeoutMinutes); - + // Populate a VduInstance based on the deleted Cloudify Deployment object return deploymentInfoToVduInstance(deployment); } @@ -1309,14 +1336,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw new VduException ("Delete VDU Exception", e); } } - - + + /** * VduPlugin interface for update function. - * + * * Update is currently not supported in the MsoCloudifyUtils implementation. * Just return a VduException. - * + * */ @Override public VduInstance updateVdu ( @@ -1329,37 +1356,37 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { throw new VduException ("CloudifyUtils: updateVDU interface not supported"); } - - + + /* * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object */ protected VduInstance deploymentInfoToVduInstance (DeploymentInfo deployment) { VduInstance vduInstance = new VduInstance(); - + // only one ID in Cloudify, use for both VDU name and ID vduInstance.setVduInstanceId(deployment.getId()); vduInstance.setVduInstanceName(deployment.getId()); - + // Copy inputs and outputs vduInstance.setInputs(deployment.getInputs()); vduInstance.setOutputs(deployment.getOutputs()); - + // Translate the status elements vduInstance.setStatus(deploymentStatusToVduStatus (deployment)); - + return vduInstance; } - + protected VduStatus deploymentStatusToVduStatus (DeploymentInfo deployment) { VduStatus vduStatus = new VduStatus(); - + // Determine the status based on last action & status // DeploymentInfo object should be enhanced to report a better status internally. DeploymentStatus status = deployment.getStatus(); - + if (status == null) { vduStatus.setState(VduStateType.UNKNOWN); } @@ -1384,13 +1411,13 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } else { vduStatus.setState(VduStateType.UNKNOWN); } - + vduStatus.setErrorMessage(deployment.getErrorMessage()); vduStatus.setLastAction(new PluginAction(deployment.getLastAction(), deployment.getActionStatus(), deployment.getErrorMessage())); - + return vduStatus; } - + /* * Return an OpenstackConfig object as expected by Cloudify Openstack Plug-in. * Base the values on the CloudSite definition. @@ -1404,7 +1431,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ openstackConfig.setTenantName (tenantId); return openstackConfig; } - + /* * Return an Azure object as expected by Cloudify Azure Plug-in. * Base the values on the CloudSite definition. @@ -1418,13 +1445,13 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ azureConfig.setClientSecret (cloudSite.getIdentityService().getMsoPass()); return azureConfig; } - + private void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { - LOGGER.debug("Thread interrupted while sleeping!", e); - Thread.currentThread().interrupt(); + logger.debug("Thread interrupted while sleeping!", e); + Thread.currentThread().interrupt(); } } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java index 75b9fc94f6..8cd6b0f65e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 Intel Corp. All rights reserved. * Copyright (C) 2017 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 @@ -22,38 +24,37 @@ package org.onap.so.openstack.utils; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.heat.model.CreateStackParam; +import com.woorea.openstack.heat.model.Explanation; +import com.woorea.openstack.keystone.model.Error; +import com.woorea.openstack.quantum.model.NeutronError; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; - import org.onap.so.config.beans.PoConfig; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.heat.model.CreateStackParam; -import com.woorea.openstack.heat.model.Explanation; -import com.woorea.openstack.keystone.model.Error; -import com.woorea.openstack.quantum.model.NeutronError; - @Component("CommonUtils") public class MsoCommonUtils { - private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, MsoCommonUtils.class); + private static Logger logger = LoggerFactory.getLogger(MsoCommonUtils.class); @Autowired @@ -92,19 +93,24 @@ public class MsoCommonUtils { boolean retry = false; if (retryCodes != null ) { int code = e.getStatus(); - logger.debug ("Config values RetryDelay:" + retryDelay + " RetryCount:" + retryCount + " RetryCodes:" + retryCodes + " ResponseCode:" + code); - for (String rCode : retryCodes.split (",")) { + logger.debug("Config values RetryDelay:{} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay, + retryCount, retryCodes, code); + for (String rCode : retryCodes.split (",")) { try { if (retryCount > 0 && code == Integer.parseInt (rCode)) { retryCount--; retry = true; - logger.debug ("OpenStackResponseException ResponseCode:" + code + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); - break; + logger.debug( + "OpenStackResponseException ResponseCode: {} request:{} Retry indicated. Attempts remaining:{}", + code, requestType, retryCount); + break; } } catch (NumberFormatException e1) { - logger.error (MessageEnum.RA_CONFIG_EXC, "No retries. Exception in parsing retry code in config:" + rCode, "", "", MsoLogger.ErrorCode.SchemaError, "Exception in parsing retry code in config"); - throw e; + logger.error("{} No retries. Exception in parsing retry code in config:{} {} {}", + MessageEnum.RA_CONFIG_EXC, rCode, MsoLogger.ErrorCode.SchemaError.getValue(), + "Exception in parsing retry code in config"); + throw e; } } } @@ -125,7 +131,7 @@ public class MsoCommonUtils { if (retryCount > 0) { retryCount--; - logger.debug (" request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + logger.debug (" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount); try { Thread.sleep (retryDelay * 1000L); } catch (InterruptedException e1) { @@ -153,12 +159,14 @@ public class MsoCommonUtils { try { // Failed Keystone calls return an Error entity body. Error error = re.getResponse ().getErrorEntity (Error.class); - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Keystone Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone Error on " + context); - me = new MsoOpenstackException (error.getCode (), error.getTitle (), error.getMessage ()); + logger.error("{} {} Openstack Keystone Error on {}: {}", + MessageEnum.RA_CONNECTION_EXCEPTION, MsoLogger.ErrorCode.DataError.getValue(), context, error); + me = new MsoOpenstackException (error.getCode (), error.getTitle (), error.getMessage ()); } catch (Exception e2) { // Can't parse the body as an "Error". Report the HTTP error - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "HTTP Error on " + context + ": " + re.getStatus() + "," + re.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "HTTP Error on " + context, e2); - me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); + logger.error("{} {} HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), re.getMessage(), e2); + me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); } // Add the context of the error @@ -175,8 +183,8 @@ public class MsoCommonUtils { me.addContext (context); // Generate an alarm for all connection errors. - logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "Openstack Keystone connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone connection error on " + context); - + logger.error("{} {} Openstack Keystone connection error on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, + MsoLogger.ErrorCode.DataError.getValue(), context, e); } return me; @@ -195,7 +203,8 @@ public class MsoCommonUtils { try { // Failed Heat calls return an Explanation entity body. Explanation explanation = re.getResponse ().getErrorEntity (Explanation.class); - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error on " + context + ": " + explanation.toString(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - Openstack Error on " + context); + logger.error("{} {} Exception - Openstack Error on {} : {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, explanation.toString()); String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType() + ", error.message=" + explanation.getError().getMessage(); logger.debug(fullError); me = new MsoOpenstackException (explanation.getCode (), @@ -204,8 +213,9 @@ public class MsoCommonUtils { fullError); } catch (Exception e2) { // Couldn't parse the body as an "Explanation". Report the original HTTP error. - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); - me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); + logger.error("{} {} Exception - HTTP Error on {}: {}, ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2); + me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); } // Add the context of the error @@ -223,8 +233,9 @@ public class MsoCommonUtils { // Generate an alarm for all connection errors. - logger.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Heat connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Heat connection error on " + context); - } + logger.error("{} {} Openstack Heat connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, e); + } return me; } @@ -242,12 +253,14 @@ public class MsoCommonUtils { try { // Failed Neutron calls return an NeutronError entity body NeutronError error = re.getResponse ().getErrorEntity (NeutronError.class); - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Error on " + context); - me = new MsoOpenstackException (re.getStatus (), error.getType (), error.getMessage ()); + logger.error("{} {} Openstack Neutron Error on {} {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, error); + me = new MsoOpenstackException (re.getStatus (), error.getType (), error.getMessage ()); } catch (Exception e2) { // Couldn't parse body as a NeutronError. Report the HTTP error. - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack HTTP Error on " + context, e2); - me = new MsoOpenstackException (re.getStatus (), re.getMessage (), null); + logger.error("{} {} Openstack HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2); + me = new MsoOpenstackException (re.getStatus (), re.getMessage (), null); } // Add the context of the error @@ -265,8 +278,9 @@ public class MsoCommonUtils { // Generate an alarm for all connection errors. - logger.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Connection error on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Connection error on "+ context); - } + logger.error("{} {} Openstack Neutron Connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, e); + } return me; } @@ -283,8 +297,8 @@ public class MsoCommonUtils { me.setCategory (MsoExceptionCategory.INTERNAL); // Always generate an alarm for internal exceptions - logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "An exception occured on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "An exception occured on "+ context); - + logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, + MsoLogger.ErrorCode.DataError.getValue(), context, e); return me; } @@ -295,8 +309,8 @@ public class MsoCommonUtils { me.setCategory (MsoExceptionCategory.INTERNAL); // Always generate an alarm for internal exceptions - logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "An exception occured on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "An exception occured on "+ context); - + logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, + MsoLogger.ErrorCode.DataError.getValue(), context, e); return me; } @@ -321,7 +335,7 @@ public class MsoCommonUtils { haveEnvtVariable = false; logger.debug ("createStackParam called with no environment variable"); } else { - logger.debug ("createStackParam called with an environment variable: " + environment); + logger.debug("createStackParam called with an environment variable: {}", environment); } boolean haveFiles = true; @@ -329,7 +343,7 @@ public class MsoCommonUtils { haveFiles = false; logger.debug ("createStackParam called with no files / child template ids"); } else { - logger.debug ("createStackParam called with " + files.size () + " files / child template ids"); + logger.debug("createStackParam called with {} files / child template ids", files.size()); } boolean haveHeatFiles = true; @@ -337,7 +351,7 @@ public class MsoCommonUtils { haveHeatFiles = false; logger.debug ("createStackParam called with no heatFiles"); } else { - logger.debug ("createStackParam called with " + heatFiles.size () + " heatFiles"); + logger.debug("createStackParam called with {} heatFiles", heatFiles.size()); } //force entire stackInput object to generic Map<String, Object> for openstack compatibility @@ -359,8 +373,8 @@ public class MsoCommonUtils { stack.setDisableRollback (true); // TJM New for PO Adapter - add envt variable if (haveEnvtVariable) { - logger.debug ("Found an environment variable - value: " + environment); - stack.setEnvironment (environment); + logger.debug("Found an environment variable - value: {}", environment); + stack.setEnvironment (environment); } // Now handle nested templates or get_files - have to combine if we have both // as they're both treated as "files:" on the stack. @@ -396,11 +410,11 @@ public class MsoCommonUtils { inputs.put(entry.getKey(), entry.getValue()); } } - logger.debug("stack request:" + stack.toString()); - } catch (Exception e) { + logger.debug("stack request: {}", stack.toString()); + } catch (Exception e) { // that's okay - this is a nice-to-have - logger.debug("(had an issue printing nicely formatted request to debuglog) " + e.getMessage()); - } + logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e.getMessage()); + } return stack; } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java index c95e62dad0..4b53006c21 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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 @@ -22,17 +24,16 @@ package org.onap.so.openstack.utils; - import java.util.ArrayList; import java.util.HashSet; import java.util.Set; - import org.onap.so.db.catalog.beans.HeatTemplateParam; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MsoHeatEnvironmentEntry { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatEnvironmentEntry.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentEntry.class); private Set<MsoHeatEnvironmentParameter> parameters = null; private Set<MsoHeatEnvironmentResource> resources = null; @@ -66,8 +67,8 @@ public class MsoHeatEnvironmentEntry { this.resourceRegistryEntryRaw = sb; } } catch (Exception e) { - LOGGER.debug("Exception:", e); - this.valid = false; + logger.debug("Exception:", e); + this.valid = false; this.errorString = e.getMessage(); //e.printStackTrace(); } @@ -249,7 +250,7 @@ public class MsoHeatEnvironmentEntry { } } } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); this.errorString = e.getMessage(); //e.printStackTrace(); } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java index c174b58f95..56bab31880 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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 @@ -21,11 +23,12 @@ package org.onap.so.openstack.utils; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MsoHeatEnvironmentResource { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatEnvironmentResource.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentResource.class); private String name; private String value; @@ -87,8 +90,8 @@ public class MsoHeatEnvironmentResource { try { result = this.name.hashCode(); } catch (Exception e) { - LOGGER.debug("Exception:", e); - } + logger.debug("Exception:", e); + } return result; } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index ddc725188f..efc232e79e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -23,6 +23,21 @@ package org.onap.so.openstack.utils; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.heat.Heat; +import com.woorea.openstack.heat.model.CreateStackParam; +import com.woorea.openstack.heat.model.Resources; +import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.heat.model.Stack.Output; +import com.woorea.openstack.heat.model.Stacks; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.utils.KeystoneUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -31,7 +46,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.PluginAction; import org.onap.so.adapters.vdu.VduArtifact; @@ -53,7 +67,6 @@ import org.onap.so.db.catalog.beans.HeatTemplate; import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.onap.so.db.catalog.beans.ServerType; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; @@ -66,27 +79,13 @@ import org.onap.so.openstack.exceptions.MsoStackAlreadyExists; import org.onap.so.openstack.exceptions.MsoTenantNotFound; import org.onap.so.openstack.mappers.StackInfoMapper; import org.onap.so.utils.CryptoUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.heat.Heat; -import com.woorea.openstack.heat.model.CreateStackParam; -import com.woorea.openstack.heat.model.Resources; -import com.woorea.openstack.heat.model.Stack; -import com.woorea.openstack.heat.model.Stack.Output; -import com.woorea.openstack.heat.model.Stacks; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.utils.KeystoneUtils; - @Primary @Component public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ @@ -117,7 +116,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ @Autowired private KeystoneV3Authentication keystoneV3Authentication; - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtils.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtils.class); // Properties names and variables (with default values) protected String createPollIntervalProp = "org.onap.so.adapters.po.pollInterval"; @@ -292,13 +291,13 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Obtain the cloud site information where we will create the stack CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); - LOGGER.debug("Found: " + cloudSite.toString()); + logger.debug("Found: {}", cloudSite); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated) Heat heatClient = getHeatClient (cloudSite, tenantId); - LOGGER.debug("Found: " + heatClient.toString()); + logger.debug("Found: {}", heatClient); - LOGGER.debug ("Ready to Create Stack (" + heatTemplate + ") with input params: " + stackInputs); + logger.debug ("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs); Stack heatStack = null; try { @@ -313,7 +312,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ me.addContext (CREATE_STACK); throw me; } else { - LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage()); + logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage()); throw heatExceptionToMsoException (e, CREATE_STACK); } } catch (OpenStackConnectException e) { @@ -333,7 +332,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } else { // Get initial status, since it will have been null after the create. heatStack = queryHeatStack (heatClient, canonicalName); - LOGGER.debug (heatStack.getStackStatus ()); + logger.debug (heatStack.getStackStatus ()); } return new StackInfoMapper(heatStack).map(); } @@ -347,28 +346,30 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ int deletePollTimeout = pollTimeout; boolean createTimedOut = false; StringBuilder stackErrorStatusReason = new StringBuilder(""); - LOGGER.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout); + logger.debug("createPollInterval={}, pollTimeout={}", createPollInterval, pollTimeout); while (true) { try { heatStack = queryHeatStack (heatClient, canonicalName); - LOGGER.debug (heatStack.getStackStatus () + " (" + canonicalName + ")"); - try { - LOGGER.debug("Current stack " + this.getOutputsAsStringBuilder(heatStack).toString()); - } catch (Exception e) { - LOGGER.debug("an error occurred trying to print out the current outputs of the stack", e); + logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName); + try { + logger.debug("Current stack {}", this.getOutputsAsStringBuilder(heatStack).toString()); + } catch (Exception e) { + logger.debug("an error occurred trying to print out the current outputs of the stack", e); } if ("CREATE_IN_PROGRESS".equals (heatStack.getStackStatus ())) { if (pollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Create stack timeout"); - createTimedOut = true; + logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Create stack timeout", + MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); + createTimedOut = true; break; } sleep(createPollInterval * 1000L); pollTimeout -= createPollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); - } else { + logger.debug("pollTimeout remaining: {}", pollTimeout); + } else { stackErrorStatusReason.append("Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason()); break; } @@ -377,33 +378,38 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Try to roll back the stack if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack, stack deletion suppressed"); - } + logger.warn("{} Exception in Create Stack, stack deletion suppressed {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } else { try { - LOGGER.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + canonicalName + " - This will likely fail and/or we won't be able to query to see if delete worked"); - OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); + logger.debug( + "Create Stack error - unable to query for stack status - attempting to delete stack: {}" + + " - This will likely fail and/or we won't be able to query to see if delete worked", + canonicalName); + OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); executeAndRecordOpenstackRequest (request); boolean deleted = false; while (!deleted) { try { heatStack = queryHeatStack(heatClient, canonicalName); if (heatStack != null) { - LOGGER.debug(heatStack.getStackStatus()); - if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { + logger.debug(heatStack.getStackStatus()); + if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { if (deletePollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, - heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, - "Rollback: DELETE stack timeout"); - break; + logger.error( + "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout", + MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); + break; } else { sleep(deletePollInterval * 1000L); deletePollTimeout -= deletePollInterval; } } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){ - LOGGER.debug("DELETE_COMPLETE for " + canonicalName); - deleted = true; + logger.debug("DELETE_COMPLETE for {}", canonicalName); + deleted = true; continue; } else { //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate @@ -411,21 +417,22 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } } else { // assume if we can't find it - it's deleted - LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted"); - deleted = true; + logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName); + deleted = true; continue; } } catch (Exception e3) { // Just log this one. We will report the original exception. - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e3, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back stack on error on query"); - + logger.error("{} Create Stack: Nested exception rolling back stack: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e3); } } } catch (Exception e2) { // Just log this one. We will report the original exception. - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back stack"); - } + logger.error("{} Create Stack: Nested exception rolling back stack: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e2); + } } // Propagate the original exception from Stack Query. @@ -435,63 +442,73 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } if (!"CREATE_COMPLETE".equals (heatStack.getStackStatus ())) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack error: Polling complete with non-success status: " - + heatStack.getStackStatus () + ", " + heatStack.getStackStatusReason (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error"); + logger.error("{} Create Stack error: Polling complete with non-success status: {}, {} {} ", + MessageEnum.RA_CREATE_STACK_ERR, heatStack.getStackStatus(), heatStack.getStackStatusReason(), + MsoLogger.ErrorCode.BusinessProcesssError.getValue()); // Rollback the stack creation, since it is in an indeterminate state. if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error, stack deletion suppressed"); - } + logger.warn( + "{} Create Stack errored, stack deletion suppressed {} Create Stack error, stack deletion suppressed", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } else { try { - LOGGER.debug("Create Stack errored - attempting to DELETE stack: " + canonicalName); - LOGGER.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout); - OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); + logger.debug("Create Stack errored - attempting to DELETE stack: {}", canonicalName); + logger.debug("deletePollInterval={}, deletePollTimeout={}", deletePollInterval, deletePollTimeout); + OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); executeAndRecordOpenstackRequest (request); boolean deleted = false; while (!deleted) { try { heatStack = queryHeatStack(heatClient, canonicalName); if (heatStack != null) { - LOGGER.debug(heatStack.getStackStatus() + " (" + canonicalName + ")"); - if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { + logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName); + if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { if (deletePollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, - heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, - "Rollback: DELETE stack timeout"); - break; + logger.error( + "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout", + MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); + break; } else { sleep(deletePollInterval * 1000L); deletePollTimeout -= deletePollInterval; - LOGGER.debug("deletePollTimeout remaining: " + deletePollTimeout); - } + logger.debug("deletePollTimeout remaining: {}", deletePollTimeout); + } } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){ - LOGGER.debug("DELETE_COMPLETE for " + canonicalName); - deleted = true; + logger.debug("DELETE_COMPLETE for {}", canonicalName); + deleted = true; continue; } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) { // Warn about this (?) - but still throw the original exception - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion FAILED", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error, stack deletion FAILED"); - LOGGER.debug("Stack deletion FAILED on a rollback of a create - " + canonicalName + ", status=" + heatStack.getStackStatus() + ", reason=" + heatStack.getStackStatusReason()); - break; + logger.warn( + "{} Create Stack errored, stack deletion FAILED {} Create Stack error, stack deletion FAILED", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + logger.debug("Stack deletion FAILED on a rollback of a create - {}, status={}, reason={}", + canonicalName, heatStack.getStackStatus(), heatStack.getStackStatusReason()); + break; } else { //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate break; } } else { // assume if we can't find it - it's deleted - LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted"); - deleted = true; + logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName); + deleted = true; continue; } } catch (MsoException me2) { // We got an exception on the delete - don't throw this exception - throw the original - just log. - LOGGER.debug("Exception thrown trying to delete " + canonicalName + " on a create->rollback: " + me2.getContextMessage(), me2); - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", MsoLogger.ErrorCode.BusinessProcesssError, me2.getContextMessage()); - } + logger.debug("Exception thrown trying to delete {} on a create->rollback: {} ", canonicalName, + me2.getContextMessage(), me2); + logger.warn("{} Create Stack errored, then stack deletion FAILED - exception thrown {} {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + me2.getContextMessage()); + } } // end while !deleted StringBuilder errorContextMessage; @@ -507,8 +524,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } } catch (Exception e2) { // shouldn't happen - but handle - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack: rolling back stack"); - } + logger.error("{} Create Stack: Nested exception rolling back stack: {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e2); + } } MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString()); me.addContext(CREATE_STACK); @@ -529,27 +547,28 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception. */ public StackInfo queryStack (String cloudSiteId, String tenantId, String stackName) throws MsoException { - LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId); + logger.debug ("Query HEAT stack: {} in tenant {}", stackName, tenantId); // Obtain the cloud site information where we will create the stack CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); - LOGGER.debug("Found: " + cloudSite.toString()); + logger.debug("Found: {}", cloudSite.toString()); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) Heat heatClient = null; try { heatClient = getHeatClient (cloudSite, tenantId); if (heatClient != null) { - LOGGER.debug("Found: " + heatClient.toString()); + logger.debug("Found: {}", heatClient.toString()); } } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either - LOGGER.debug ("Tenant with id " + tenantId + "not found.", e); + logger.debug ("Tenant with id " + tenantId + "not found.", e); return new StackInfo (stackName, HeatStatus.NOTFOUND); } catch (MsoException me) { // Got an Openstack error. Propagate it - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception"); + logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.AvailabilityError.getValue(), me); me.addContext ("QueryStack"); throw me; } @@ -595,22 +614,23 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Obtain the cloud site information where we will create the stack CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); - LOGGER.debug("Found: " + cloudSite.toString()); + logger.debug("Found: {}", cloudSite.toString()); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) Heat heatClient = null; try { heatClient = getHeatClient (cloudSite, tenantId); if (heatClient != null) { - LOGGER.debug("Found: " + heatClient.toString()); + logger.debug("Found: {}", heatClient.toString()); } } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either - LOGGER.debug ("Tenant with id " + tenantId + "not found.", e); + logger.debug ("Tenant with id " + tenantId + "not found.", e); return new StackInfo (stackName, HeatStatus.NOTFOUND); } catch (MsoException me) { // Got an Openstack error. Propagate it - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception"); + logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.AvailabilityError.getValue(), me); me.addContext (DELETE_STACK); throw me; } @@ -635,7 +655,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ request = heatClient.getStacks ().deleteByName (canonicalName); } else { - LOGGER.debug ("Heat Client is NULL" ); + logger.debug ("Heat Client is NULL" ); } executeAndRecordOpenstackRequest (request); @@ -668,7 +688,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // When querying by canonical name, Openstack returns DELETE_COMPLETE status // instead of "404" (which would result from query by stack name). while (heatStack != null && !"DELETE_COMPLETE".equals (heatStack.getStackStatus ())) { - LOGGER.debug ("Stack status: " + heatStack.getStackStatus ()); + logger.debug ("Stack status: {}", heatStack.getStackStatus ()); if ("DELETE_FAILED".equals (heatStack.getStackStatus ())) { // Throw a 'special case' of MsoOpenstackException to report the Heat status @@ -685,7 +705,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } if (pollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Delete Stack Timeout"); + logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Delete Stack Timeout", + MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); // Throw a 'special case' of MsoOpenstackException to report the Heat status MsoOpenstackException me = new MsoOpenstackException (0, "", "Stack Deletion Timeout"); @@ -700,7 +722,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ sleep(pollInterval * 1000L); pollTimeout -= pollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); + logger.debug("pollTimeout remaining: {}", pollTimeout); heatStack = queryHeatStack (heatClient, canonicalName); } @@ -753,7 +775,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { // Not sure if this can happen, but return an empty list - LOGGER.debug ("queryAllStacks - stack not found: "); + logger.debug ("queryAllStacks - stack not found: "); return new ArrayList <> (); } else { // Convert the OpenStackResponseException to an MsoOpenstackException @@ -803,7 +825,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ if (missingParams != null) { // Problem - missing one or more required parameters String error = "Missing Required inputs for HEAT Template: " + missingParams; - LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams + " for HEAT Template", "", "", MsoLogger.ErrorCode.SchemaError, "Missing Required inputs for HEAT Template: " + missingParams); + logger.error("{} for HEAT Template {} Missing Required inputs for HEAT Template: {}", + MessageEnum.RA_MISSING_PARAM, MsoLogger.ErrorCode.SchemaError.getValue(), missingParams); throw new IllegalArgumentException (error); } @@ -821,9 +844,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } if (!extraParams.isEmpty ()) { - LOGGER.warn (MessageEnum.RA_GENERAL_WARNING, "Heat Stack (" + heatTemplate.getTemplateName () - + ") extra input params received: " - + extraParams, "", "", MsoLogger.ErrorCode.DataError, "Heat Stack (" + heatTemplate.getTemplateName () + ") extra input params received: "+ extraParams); + logger.warn("{} Heat Stack ({}) extra input params received: {} {}", MessageEnum.RA_GENERAL_WARNING, + heatTemplate.getTemplateName(), extraParams, MsoLogger.ErrorCode.DataError.getValue()); } return updatedParams; @@ -851,10 +873,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Obtain an MSO token for the tenant CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - LOGGER.debug("Found: " + cloudIdentity.toString()); + logger.debug("Found: {}", cloudIdentity.toString()); MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); - LOGGER.debug("keystoneUrl=" + keystoneUrl); + logger.debug("keystoneUrl={}", keystoneUrl); String heatUrl = null; String tokenId = null; Calendar expiration = null; @@ -873,19 +895,20 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { // Isolate trying to printout the region IDs try { - LOGGER.debug("access=" + access.toString()); - for (Access.Service service : access.getServiceCatalog()) { + logger.debug("access={}", access.toString()); + for (Access.Service service : access.getServiceCatalog()) { List<Access.Service.Endpoint> endpoints = service.getEndpoints(); for (Access.Service.Endpoint endpoint : endpoints) { - LOGGER.debug("AIC returned region=" + endpoint.getRegion()); - } + logger.debug("AIC returned region={}", endpoint.getRegion()); + } } } catch (Exception e) { - LOGGER.debug("Encountered an error trying to printout Access object returned from AIC. " + e.getMessage()); - } + logger.debug("Encountered an error trying to printout Access object returned from AIC. {}", + e.getMessage(), e); + } heatUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "orchestration", region, "public"); - LOGGER.debug("heatUrl=" + heatUrl + ", region=" + region); - } catch (RuntimeException e) { + logger.debug("heatUrl={}, region={}", heatUrl, region); + } catch (RuntimeException e) { // This comes back for not found (probably an incorrect region ID) String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl(); throw new MsoAdapterException (error, e); @@ -959,7 +982,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ return executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { - LOGGER.debug ("queryHeatStack - stack not found: " + stackName); + logger.debug ("queryHeatStack - stack not found: {}", stackName); return null; } else { // Convert the OpenStackResponseException to an MsoOpenstackException @@ -974,8 +997,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ public Map<String, Object> queryStackForOutputs(String cloudSiteId, String tenantId, String stackName) throws MsoException { - LOGGER.debug("MsoHeatUtils.queryStackForOutputs)"); - StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName); + logger.debug("MsoHeatUtils.queryStackForOutputs)"); + StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName); if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) { return null; } @@ -998,31 +1021,31 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String str = this.convertNode((JsonNode) obj); inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key, e); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode {} ", key, e); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } else if (obj instanceof java.util.LinkedHashMap) { - LOGGER.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); - try { + logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); + try { String str = JSON_MAPPER.writeValueAsString(obj); inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key, e); - } + logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap {} ", key, e); + } } else if (obj instanceof Integer) { try { String str = "" + obj; inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key, e); - } + logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer {} ", key, e); + } } else { try { String str = obj.toString(); inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Other "+ key +" (" + e.getMessage() + ")", e); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("DANGER WILL ROBINSON: unable to convert value for Other {} ({}) ", key, e.getMessage(), e); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } } @@ -1057,8 +1080,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String str = params.get(key).toString(); sb.append("\n").append(key).append("=").append(str); } catch (Exception e) { - LOGGER.debug("Exception :",e); - } + logger.debug("Exception :", e); + } } } } @@ -1071,8 +1094,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ final String json = JSON_MAPPER.writeValueAsString(obj); return json; } catch (Exception e) { - LOGGER.debug("Error converting json to string " + e.getMessage(), e); - } + logger.debug("Error converting json to string {} ", e.getMessage(), e); + } return "[Error converting json to string]"; } @@ -1108,7 +1131,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String str = JSON_MAPPER.writeValueAsString(obj); sb.append(str).append(" (a java.util.LinkedHashMap)"); } catch (Exception e) { - LOGGER.debug("Exception :",e); + logger.debug("Exception :", e); sb.append("(a LinkedHashMap value that would not convert nicely)"); } } else if (obj instanceof Integer) { @@ -1116,8 +1139,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (an Integer)\n"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(an Integer unable to call .toString() on)"; + logger.debug("Exception :", e); + str = "(an Integer unable to call .toString() on)"; } sb.append(str); } else if (obj instanceof ArrayList) { @@ -1125,8 +1148,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (an ArrayList)"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(an ArrayList unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an ArrayList unable to call .toString() on?)"; } sb.append(str); } else if (obj instanceof Boolean) { @@ -1134,8 +1157,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (a Boolean)"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(an Boolean unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an Boolean unable to call .toString() on?)"; } sb.append(str); } @@ -1144,8 +1167,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (unknown Object type)"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(a value unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(a value unable to call .toString() on?)"; } sb.append(str); } @@ -1163,44 +1186,44 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ for (String key : otherStackOutputs.keySet()) { if (paramNames != null) { if (!paramNames.contains(key) && !aliases.containsKey(key)) { - LOGGER.debug("\tParameter " + key + " is NOT defined to be in the template - do not copy to inputs"); - continue; + logger.debug("\tParameter {} is NOT defined to be in the template - do not copy to inputs", key); + continue; } if (aliases.containsKey(key)) { - LOGGER.debug("Found an alias! Will move " + key + " to " + aliases.get(key)); - Object obj = otherStackOutputs.get(key); + logger.debug("Found an alias! Will move {} to {}", key, aliases.get(key)); + Object obj = otherStackOutputs.get(key); key = aliases.get(key); otherStackOutputs.put(key, obj); } } if (!inputs.containsKey(key)) { Object obj = otherStackOutputs.get(key); - LOGGER.debug("\t**Adding " + key + " to inputs (.toString()=" + obj.toString()); - if (obj instanceof String) { - LOGGER.debug("\t\t**A String"); - inputs.put(key, obj); + logger.debug("\t**Adding {} to inputs (.toString()={}", key, obj.toString()); + if (obj instanceof String) { + logger.debug("\t\t**A String"); + inputs.put(key, obj); } else if (obj instanceof Integer) { - LOGGER.debug("\t\t**An Integer"); - inputs.put(key, obj); + logger.debug("\t\t**An Integer"); + inputs.put(key, obj); } else if (obj instanceof JsonNode) { - LOGGER.debug("\t\t**A JsonNode"); - inputs.put(key, obj); + logger.debug("\t\t**A JsonNode"); + inputs.put(key, obj); } else if (obj instanceof Boolean) { - LOGGER.debug("\t\t**A Boolean"); - inputs.put(key, obj); + logger.debug("\t\t**A Boolean"); + inputs.put(key, obj); } else if (obj instanceof java.util.LinkedHashMap) { - LOGGER.debug("\t\t**A java.util.LinkedHashMap **"); - inputs.put(key, obj); + logger.debug("\t\t**A java.util.LinkedHashMap **"); + inputs.put(key, obj); } else if (obj instanceof java.util.ArrayList) { - LOGGER.debug("\t\t**An ArrayList"); - inputs.put(key, obj); + logger.debug("\t\t**An ArrayList"); + inputs.put(key, obj); } else { - LOGGER.debug("\t\t**UNKNOWN OBJECT TYPE"); - inputs.put(key, obj); + logger.debug("\t\t**UNKNOWN OBJECT TYPE"); + inputs.put(key, obj); } } else { - LOGGER.debug("key=" + key + " is already in the inputs - will not overwrite"); - } + logger.debug("key={} is already in the inputs - will not overwrite", key); + } } return; } @@ -1239,51 +1262,52 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>(); if (inputs == null) { - LOGGER.debug("convertInputMap - inputs is null - nothing to do here"); - return new HashMap<>(); + logger.debug("convertInputMap - inputs is null - nothing to do here"); + return new HashMap<>(); } - LOGGER.debug("convertInputMap in MsoHeatUtils called, with " + inputs.size() + " inputs, and template " + template.getArtifactUuid()); - try { - LOGGER.debug(template.toString()); - Set<HeatTemplateParam> paramSet = template.getParameters(); - LOGGER.debug("paramSet has " + paramSet.size() + " entries"); - } catch (Exception e) { - LOGGER.debug("Exception occurred in convertInputMap:" + e.getMessage(), e); - } + logger.debug("convertInputMap in MsoHeatUtils called, with {} inputs, and template {}", inputs.size(), + template.getArtifactUuid()); + try { + logger.debug(template.toString()); + Set<HeatTemplateParam> paramSet = template.getParameters(); + logger.debug("paramSet has {} entries", paramSet.size()); + } catch (Exception e) { + logger.debug("Exception occurred in convertInputMap:" + e.getMessage(), e); + } for (HeatTemplateParam htp : template.getParameters()) { - LOGGER.debug("Adding " + htp.getParamName()); - params.put(htp.getParamName(), htp); + logger.debug("Adding {}", htp.getParamName()); + params.put(htp.getParamName(), htp); if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) { - LOGGER.debug("\tFound ALIAS " + htp.getParamName() + "->" + htp.getParamAlias()); - paramAliases.put(htp.getParamAlias(), htp); + logger.debug("\tFound ALIAS {} -> {}", htp.getParamName(), htp.getParamAlias()); + paramAliases.put(htp.getParamAlias(), htp); } } - LOGGER.debug("Now iterate through the inputs..."); - for (String key : inputs.keySet()) { - LOGGER.debug("key=" + key); - boolean alias = false; + logger.debug("Now iterate through the inputs..."); + for (String key : inputs.keySet()) { + logger.debug("key={}", key); + boolean alias = false; String realName = null; if (!params.containsKey(key)) { - LOGGER.debug(key + " is not a parameter in the template! - check for an alias"); - // add check here for an alias + logger.debug("{} is not a parameter in the template! - check for an alias", key); + // add check here for an alias if (!paramAliases.containsKey(key)) { - LOGGER.debug("The parameter " + key + " is in the inputs, but it's not a parameter for this template - omit"); - continue; + logger.debug("The parameter {} is in the inputs, but it's not a parameter for this template - omit", key); + continue; } else { alias = true; realName = paramAliases.get(key).getParamName(); - LOGGER.debug("FOUND AN ALIAS! Will use " + realName + " in lieu of give key/alias " + key); - } + logger.debug("FOUND AN ALIAS! Will use {} in lieu of give key/alias {}", realName, key); + } } String type = params.get(key).getParamType(); if (type == null || "".equals(type)) { - LOGGER.debug("**PARAM_TYPE is null/empty for " + key + ", will default to string"); - type = "string"; + logger.debug("**PARAM_TYPE is null/empty for {}, will default to string", key); + type = "string"; } - LOGGER.debug("Parameter: " + key + " is of type " + type); - if ("string".equalsIgnoreCase(type)) { + logger.debug("Parameter: {} is of type {}", key, type); + if ("string".equalsIgnoreCase(type)) { // Easiest! String str = inputs.get(key); if (alias) @@ -1296,8 +1320,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { anInteger = Integer.parseInt(integerString); } catch (Exception e) { - LOGGER.debug("Unable to convert " + integerString + " to an integer!!", e); - anInteger = null; + logger.debug("Unable to convert {} to an integer!!", integerString, e); + anInteger = null; } if (anInteger != null) { if (alias) @@ -1314,8 +1338,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } else if ("json".equalsIgnoreCase(type)) { // MSO-1475 - Leave this as a string now String jsonString = inputs.get(key); - LOGGER.debug("Skipping conversion to jsonNode..."); - if (alias) + logger.debug("Skipping conversion to jsonNode..."); + if (alias) newInputs.put(realName, jsonString); else newInputs.put(key, jsonString); @@ -1329,8 +1353,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ else newInputs.put(key, anArrayList); } catch (Exception e) { - LOGGER.debug("Unable to convert " + commaSeparated + " to an ArrayList!!", e); - if (alias) + logger.debug("Unable to convert {} to an ArrayList!!", commaSeparated, e); + if (alias) newInputs.put(realName, commaSeparated); else newInputs.put(key, commaSeparated); @@ -1671,7 +1695,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { Thread.sleep(time); } catch (InterruptedException e) { - LOGGER.debug ("Thread interrupted while sleeping", e); + logger.debug ("Thread interrupted while sleeping", e); Thread.currentThread().interrupt(); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java index e68a8e764a..cbbabc79b3 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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 @@ -22,12 +24,20 @@ package org.onap.so.openstack.utils; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.heat.Heat; +import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.heat.model.Stack.Output; +import com.woorea.openstack.heat.model.UpdateStackParam; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; @@ -37,28 +47,20 @@ import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.exceptions.MsoStackNotFound; import org.onap.so.openstack.mappers.StackInfoMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.heat.Heat; -import com.woorea.openstack.heat.model.Stack; -import com.woorea.openstack.heat.model.Stack.Output; -import com.woorea.openstack.heat.model.UpdateStackParam; - @Component public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { private static final String UPDATE_STACK = "UpdateStack"; - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtilsWithUpdate.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtilsWithUpdate.class); private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - + @Autowired private Environment environment; /* @@ -204,15 +206,15 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { // NOTE: This is specific to the v1 Orchestration API. String canonicalName = heatStack.getStackName () + "/" + heatStack.getId (); - LOGGER.debug ("Ready to Update Stack (" + canonicalName + ") with input params: " + stackInputs); + logger.debug ("Ready to Update Stack ({}) with input params: {}", canonicalName, stackInputs); //force entire stackInput object to generic Map<String, Object> for openstack compatibility ObjectMapper mapper = new ObjectMapper(); Map<String, Object> normalized = new HashMap<>(); try { normalized = mapper.readValue(mapper.writeValueAsString(stackInputs), new TypeReference<HashMap<String,Object>>() {}); } catch (IOException e1) { - LOGGER.debug("could not map json", e1); - } + logger.debug("could not map json", e1); + } // Build up the stack update parameters // Disable auto-rollback, because error reason is lost. Always rollback in the code. UpdateStackParam stack = new UpdateStackParam (); @@ -229,7 +231,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { // and then add to stack (both are part of "files:" being added to stack) if (haveFiles && haveHeatFiles) { // Let's do this here - not in the bean - LOGGER.debug ("Found files AND heatFiles - combine and add!"); + logger.debug ("Found files AND heatFiles - combine and add!"); Map <String, Object> combinedFiles = new HashMap<>(); for (String keyString : files.keySet ()) { combinedFiles.put (keyString, files.get (keyString)); @@ -275,11 +277,12 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { while (loopAgain) { try { updateStack = queryHeatStack (heatClient, canonicalName); - LOGGER.debug (updateStack.getStackStatus () + " (" + canonicalName + ")"); + logger.debug("{} ({}) ", updateStack.getStackStatus(), canonicalName); try { - LOGGER.debug("Current stack " + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString()); + logger + .debug("Current stack {}" + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString()); } catch (Exception e) { - LOGGER.debug("an error occurred trying to print out the current outputs of the stack", e); + logger.debug("an error occurred trying to print out the current outputs of the stack", e); } @@ -289,7 +292,10 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { if (pollTimeout <= 0) { // Note that this should not occur, since there is a timeout specified // in the Openstack call. - LOGGER.error (MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, updateStack.getStackStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError, "Update stack timeout"); + logger.error( + "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Update stack timeout", + MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + updateStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); loopAgain = false; } else { try { @@ -302,7 +308,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { } } pollTimeout -= createPollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); + logger.debug("pollTimeout remaining: {}", pollTimeout); } else { loopAgain = false; } @@ -316,7 +322,9 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { } if (!"UPDATE_COMPLETE".equals (updateStack.getStackStatus ())) { - LOGGER.error (MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(), updateStack.getStackStatusReason(), "", "", MsoLogger.ErrorCode.DataError, "Update Stack error"); + logger.error("{} Stack status: {} Stack status reason: {} {} Update Stack error", + MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(), updateStack.getStackStatusReason(), + MsoLogger.ErrorCode.DataError.getValue()); // TODO: No way to roll back the stack at this point. What to do? // Throw a 'special case' of MsoOpenstackException to report the Heat status @@ -337,14 +345,14 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { // Return the current status. updateStack = queryHeatStack (heatClient, canonicalName); if (updateStack != null) { - LOGGER.debug ("UpdateStack, status = " + updateStack.getStackStatus ()); + logger.debug("UpdateStack, status = {}", updateStack.getStackStatus()); } else { - LOGGER.debug ("UpdateStack, stack not found"); + logger.debug("UpdateStack, stack not found"); } } return new StackInfoMapper(updateStack).map(); } - + private StringBuilder getOutputsAsStringBuilderWithUpdate(Stack heatStack) { // This should only be used as a utility to print out the stack outputs // to the log @@ -376,16 +384,16 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { String str = JSON_MAPPER.writeValueAsString(obj); sb.append(str).append(" (a java.util.LinkedHashMap)"); } catch (Exception e) { - LOGGER.debug("Exception :", e); - sb.append("(a LinkedHashMap value that would not convert nicely)"); - } + logger.debug("Exception :", e); + sb.append("(a LinkedHashMap value that would not convert nicely)"); + } } else if (obj instanceof Integer) { String str = ""; try { str = obj.toString() + " (an Integer)\n"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(an Integer unable to call .toString() on)"; + logger.debug("Exception :", e); + str = "(an Integer unable to call .toString() on)"; } sb.append(str); } else if (obj instanceof ArrayList) { @@ -393,8 +401,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (an ArrayList)"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(an ArrayList unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an ArrayList unable to call .toString() on?)"; } sb.append(str); } else if (obj instanceof Boolean) { @@ -402,8 +410,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (a Boolean)"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(an Boolean unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an Boolean unable to call .toString() on?)"; } sb.append(str); } @@ -412,8 +420,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (unknown Object type)"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(a value unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(a value unable to call .toString() on?)"; } sb.append(str); } @@ -422,16 +430,16 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { sb.append("[END]"); return sb; } - + private String convertNodeWithUpdate(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); final String json = JSON_MAPPER.writeValueAsString(obj); return json; } catch (Exception e) { - LOGGER.debug("Error converting json to string " + e.getMessage(), e); - } + logger.debug("Error converting json to string {} ", e.getMessage(), e); + } return "[Error converting json to string]"; } - + } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java index 0bd2a3931f..56a42e986f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -21,17 +23,26 @@ package org.onap.so.openstack.utils; -import java.io.Serializable; -import java.util.Calendar; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.model.Metadata; +import com.woorea.openstack.keystone.model.Role; +import com.woorea.openstack.keystone.model.Roles; +import com.woorea.openstack.keystone.model.Tenant; +import com.woorea.openstack.keystone.model.User; +import com.woorea.openstack.keystone.utils.KeystoneUtils; import java.util.HashMap; import java.util.Map; import java.util.Optional; - +import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; -import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.exceptions.MsoAdapterException; @@ -39,30 +50,17 @@ import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.exceptions.MsoTenantAlreadyExists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.model.Metadata; -import com.woorea.openstack.keystone.model.Role; -import com.woorea.openstack.keystone.model.Roles; -import com.woorea.openstack.keystone.model.Tenant; -import com.woorea.openstack.keystone.model.User; -import com.woorea.openstack.keystone.utils.KeystoneUtils; - @Component public class MsoKeystoneUtils extends MsoTenantUtils { + private static Logger logger = LoggerFactory.getLogger(MsoKeystoneUtils.class); - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoKeystoneUtils.class); - - @Autowired + @Autowired private AuthenticationMethodFactory authenticationMethodFactory; @Autowired @@ -98,7 +96,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Obtain the cloud site information where we will create the tenant Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); if (!cloudSiteOpt.isPresent()) { - LOGGER.error(MessageEnum.RA_CREATE_TENANT_ERR, "MSOCloudSite not found", "", "", MsoLogger.ErrorCode.DataError, "MSOCloudSite not found"); + logger.error("{} MSOCloudSite {} not found {} ", MessageEnum.RA_CREATE_TENANT_ERR, cloudSiteId, + MsoLogger.ErrorCode.DataError.getValue()); throw new MsoCloudSiteNotFound (cloudSiteId); } Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get()); @@ -109,7 +108,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (tenant != null) { // Tenant already exists. Throw an exception - LOGGER.error(MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant already exists"); + logger.error("{} Tenant name {} already exists on Cloud site id {}, {}", + MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, MsoLogger.ErrorCode.DataError.getValue()); throw new MsoTenantAlreadyExists (tenantName, cloudSiteId); } @@ -158,8 +158,9 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // so roll back the tenant. if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_TENANT_ERR, "Create Tenant errored, Tenant deletion suppressed", "Openstack", "", MsoLogger.ErrorCode.DataError, "Create Tenant error, Tenant deletion suppressed"); - } + logger.warn("{} Create Tenant errored, Tenant deletion suppressed {} ", MessageEnum.RA_CREATE_TENANT_ERR, + MsoLogger.ErrorCode.DataError.getValue()); + } else { try { @@ -167,8 +168,9 @@ public class MsoKeystoneUtils extends MsoTenantUtils { executeAndRecordOpenstackRequest (request); } catch (Exception e2) { // Just log this one. We will report the original exception. - LOGGER.error (MessageEnum.RA_CREATE_TENANT_ERR, "Nested exception rolling back tenant", "Openstack", "", MsoLogger.ErrorCode.DataError, "Create Tenant error, Nested exception rolling back tenant", e2); - } + logger.error("{} Nested exception rolling back tenant {} ", MessageEnum.RA_CREATE_TENANT_ERR, + MsoLogger.ErrorCode.DataError.getValue(), e2); + } } @@ -303,13 +305,14 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Check that the tenant exists. Also, need the ID to delete Tenant tenant = findTenantById (keystoneAdminClient, tenantId); if (tenant == null) { - LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantId, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found"); + logger.error("{} Tenant id {} not found on cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND, + tenantId, cloudSiteId, MsoLogger.ErrorCode.DataError.getValue()); return false; } OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); executeAndRecordOpenstackRequest (request); - LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")"); + logger.debug ("Deleted Tenant {} ({})", tenant.getId(), tenant.getName()); } catch (OpenStackBaseException e) { // Convert Keystone OpenStackResponseException to MsoOpenstackException throw keystoneErrorToMsoException (e, "Delete Tenant"); @@ -349,7 +352,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { Tenant tenant = findTenantByName (keystoneAdminClient, tenantName); if (tenant == null) { // OK if tenant already doesn't exist. - LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found"); + logger.error("{} Tenant {} not found on Cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND, + tenantName, cloudSiteId, MsoLogger.ErrorCode.DataError.getValue()); return false; } @@ -357,7 +361,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); executeAndRecordOpenstackRequest (request); - LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")"); + logger.debug("Deleted Tenant {} ({})", tenant.getId(), tenant.getName()); } catch (OpenStackBaseException e) { // Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown. @@ -431,7 +435,9 @@ public class MsoKeystoneUtils extends MsoTenantUtils { } catch (RuntimeException e) { String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId (); - LOGGER.error(MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in findEndpointURL"); + logger.error("{} Region: {} Cloud identity {} {} Exception in findEndpointURL ", + MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(), + MsoLogger.ErrorCode.DataError.getValue(), e); throw new MsoAdapterException (error, e); } @@ -486,7 +492,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (e.getStatus () == 404) { return null; } else { - LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET Tenant by Id (" + tenantId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET tenant by Id"); + logger.error("{} {} Openstack Error, GET Tenant by Id ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), tenantId, e); throw e; } } @@ -514,7 +521,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (e.getStatus () == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET Tenant By Name (" + tenantName + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET Tenant By Name"); + logger.error("{} {} Openstack Error, GET Tenant By Name ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), tenantName, e); throw e; } } @@ -543,7 +551,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Not found by ID. Search for name return findUserByName (adminClient, userNameOrId); } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET User (" + userNameOrId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET User"); + logger.error("{} {} Openstack Error, GET User ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), userNameOrId, e); throw e; } } @@ -571,7 +580,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (e.getStatus () == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET User By Name (" + userName + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET User By Name"); + logger.error("{} {} Openstack Error, GET User By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), userName, e); throw e; } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java index 785e8606d3..b904a59ee1 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -21,12 +23,21 @@ package org.onap.so.openstack.utils; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.utils.KeystoneUtils; +import com.woorea.openstack.quantum.Quantum; +import com.woorea.openstack.quantum.model.Network; +import com.woorea.openstack.quantum.model.Networks; +import com.woorea.openstack.quantum.model.Segment; import java.util.ArrayList; import java.util.Calendar; -import java.util.HashMap; import java.util.List; -import java.util.Map; - import org.onap.so.cloud.CloudConfig; import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.cloud.authentication.KeystoneAuthHolder; @@ -36,10 +47,8 @@ import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.ServerType; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.NetworkInfo; -import org.onap.so.openstack.beans.NeutronCacheEntry; import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; @@ -48,22 +57,11 @@ import org.onap.so.openstack.exceptions.MsoNetworkAlreadyExists; import org.onap.so.openstack.exceptions.MsoNetworkNotFound; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.mappers.NetworkInfoMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.utils.KeystoneUtils; -import com.woorea.openstack.quantum.Quantum; -import com.woorea.openstack.quantum.model.Network; -import com.woorea.openstack.quantum.model.Networks; -import com.woorea.openstack.quantum.model.Segment; - @Component public class MsoNeutronUtils extends MsoCommonUtils { @@ -80,10 +78,10 @@ public class MsoNeutronUtils extends MsoCommonUtils @Autowired private KeystoneV3Authentication keystoneV3Authentication; - - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoNeutronUtils.class); - - public enum NetworkType { + + private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class); + + public enum NetworkType { BASIC, PROVIDER, MULTI_PROVIDER }; @@ -119,8 +117,10 @@ public class MsoNeutronUtils extends MsoCommonUtils if (network != null) { // Network already exists. Throw an exception - LOGGER.error(MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId, "Openstack", "", MsoLogger.ErrorCode.DataError, "Network already exists"); - throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId); + logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}", + MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId, + MsoLogger.ErrorCode.DataError.getValue()); + throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId); } // Does not exist, create a new one @@ -183,7 +183,7 @@ public class MsoNeutronUtils extends MsoCommonUtils */ public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException { - LOGGER.debug("In queryNetwork"); + logger.debug("In queryNetwork"); // Obtain the cloud site information CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( @@ -195,8 +195,8 @@ public class MsoNeutronUtils extends MsoCommonUtils try { Network network = findNetworkByNameOrId (neutronClient, networkNameOrId); if (network == null) { - LOGGER.debug ("Query Network: " + networkNameOrId + " not found in tenant " + tenantId); - return null; + logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId); + return null; } return new NetworkInfoMapper(network).map(); } @@ -235,15 +235,16 @@ public class MsoNeutronUtils extends MsoCommonUtils // Check that the network exists. Network network = findNetworkById (neutronClient, networkId); if (network == null) { - LOGGER.info(MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId, "Openstack", ""); - return false; + logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ", + MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId); + return false; } OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId()); executeAndRecordOpenstackRequest(request); - LOGGER.debug ("Deleted Network " + network.getId() + " (" + network.getName() + ")"); - } + logger.debug("Deleted Network {} ({})", network.getId(), network.getName()); + } catch (OpenStackBaseException e) { // Convert Neutron exception to an MsoOpenstackException MsoException me = neutronExceptionToMsoException (e, "Delete Network"); @@ -294,7 +295,8 @@ public class MsoNeutronUtils extends MsoCommonUtils if (network == null) { // Network not found. Throw an exception - LOGGER.error(MessageEnum.RA_NETWORK_NOT_FOUND, networkId, cloudSiteId, tenantId, "Openstack", "", MsoLogger.ErrorCode.DataError, "Network not found"); + logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND, + networkId, cloudSiteId, tenantId, MsoLogger.ErrorCode.DataError.getValue()); throw new MsoNetworkNotFound (networkId, tenantId, cloudSiteId); } @@ -480,8 +482,9 @@ public class MsoNeutronUtils extends MsoCommonUtils if (e.getStatus() == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error, GET Network By ID (" + networkId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack"); - throw e; + logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), networkId, e); + throw e; } } } @@ -515,19 +518,20 @@ public class MsoNeutronUtils extends MsoCommonUtils Networks networks = executeAndRecordOpenstackRequest(request); for (Network network : networks.getList()) { if (network.getName().equals(networkName)) { - LOGGER.debug ("Found match on network name: " + networkName); - return network; + logger.debug("Found match on network name: {}", networkName); + return network; } } - LOGGER.debug ("findNetworkByName - no match found for " + networkName); - return null; + logger.debug("findNetworkByName - no match found for {}", networkName); + return null; } catch (OpenStackResponseException e) { if (e.getStatus() == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error, GET Network By Name (" + networkName + "): " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Exception in OpenStack"); - throw e; + logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), networkName, e); + throw e; } } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java index 383409f810..7cf41dbac9 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -22,10 +24,8 @@ package org.onap.so.openstack.utils; import java.util.Map; - import org.onap.so.cloud.CloudConfig; import org.onap.so.db.catalog.beans.CloudIdentity; -import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; @@ -35,9 +35,7 @@ import org.springframework.stereotype.Component; @Component public abstract class MsoTenantUtils extends MsoCommonUtils { - protected static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoTenantUtils.class); - - @Autowired + @Autowired protected CloudConfig cloudConfig; public abstract String createTenant (String tenantName, String cloudSiteId, Map <String, String> metadata, boolean backout) diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java index 08c98f3167..c5b93d9fbe 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -23,16 +25,17 @@ package org.onap.so.openstack.utils; import org.onap.so.cloud.CloudConfig; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.ServerType; -import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MsoTenantUtilsFactory { - protected static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, MsoTenantUtilsFactory.class); - @Autowired + protected static Logger logger = LoggerFactory.getLogger(MsoTenantUtilsFactory.class); + @Autowired protected CloudConfig cloudConfig; @Autowired protected MsoKeystoneUtils keystoneUtils; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java index 649eb6b07c..5f26449f0f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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 @@ -22,25 +24,22 @@ package org.onap.so.openstack.utils; - +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import org.onap.so.db.catalog.beans.HeatTemplateParam; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; -import com.fasterxml.jackson.databind.ObjectMapper; - public class MsoYamlEditorWithEnvt { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoYamlEditorWithEnvt.class); + private static final Logger logger = LoggerFactory.getLogger(MsoYamlEditorWithEnvt.class); private Map <String, Object> yml; private Yaml yaml = new Yaml (); @@ -68,8 +67,8 @@ public class MsoYamlEditorWithEnvt { try { resourceMap = (Map<String,Object>) yml.get("parameters"); } catch (Exception e) { - LOGGER.debug("Exception:", e); - return paramSet; + logger.debug("Exception:", e); + return paramSet; } if (resourceMap == null) { return paramSet; @@ -89,7 +88,7 @@ public class MsoYamlEditorWithEnvt { try { value = JSON_MAPPER.writeValueAsString(obj); } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); value = "_BAD_JSON_MAPPING"; } } else { @@ -117,8 +116,8 @@ public class MsoYamlEditorWithEnvt { } return resourceList; } catch (Exception e) { - LOGGER.debug("Exception:", e); - } + logger.debug("Exception:", e); + } return null; } public synchronized Set <HeatTemplateParam> getParameterList () { @@ -135,7 +134,7 @@ public class MsoYamlEditorWithEnvt { try { value = resourceEntry.get("default"); } catch (ClassCastException cce) { - LOGGER.debug("Exception:", cce); + logger.debug("Exception:", cce); // This exception only - the value is an integer. For what we're doing // here - we don't care - so set value to something - and it will // get marked as not being required - which is correct. diff --git a/adapters/mso-catalog-db-adapter/pom.xml b/adapters/mso-catalog-db-adapter/pom.xml index 390c775cb2..dbfc5b7f6b 100644 --- a/adapters/mso-catalog-db-adapter/pom.xml +++ b/adapters/mso-catalog-db-adapter/pom.xml @@ -153,6 +153,10 @@ </dependency> <dependency> <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-jdbc</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml b/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml index aa9317c920..0977bf95fb 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml +++ b/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml @@ -16,7 +16,7 @@ mso: spring: datasource: - url: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb + jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb username: ${DB_USERNAME} password: ${DB_PASSWORD} driver-class-name: org.mariadb.jdbc.Driver diff --git a/adapters/mso-catalog-db-adapter/src/test/resources/application-test.yaml b/adapters/mso-catalog-db-adapter/src/test/resources/application-test.yaml index 954e41aa68..09262f9f58 100644 --- a/adapters/mso-catalog-db-adapter/src/test/resources/application-test.yaml +++ b/adapters/mso-catalog-db-adapter/src/test/resources/application-test.yaml @@ -14,7 +14,7 @@ mso: spring: datasource: - jdbc-url: jdbc:mariadb://localhost:3307/catalogdb + url: jdbc:mariadb://localhost:3307/catalogdb username: root password: password driver-class-name: org.mariadb.jdbc.Driver diff --git a/adapters/mso-openstack-adapters/pom.xml b/adapters/mso-openstack-adapters/pom.xml index 46e73246a0..12aee67a74 100644 --- a/adapters/mso-openstack-adapters/pom.xml +++ b/adapters/mso-openstack-adapters/pom.xml @@ -188,6 +188,10 @@ </exclusions> </dependency> <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-jdbc</artifactId> + </dependency> + <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version>${cxf.version}</version> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/BpelRestClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/BpelRestClient.java deleted file mode 100644 index 6c646f3e63..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/BpelRestClient.java +++ /dev/null @@ -1,298 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.so.adapters.network; - - -import java.security.GeneralSecurityException; -import java.util.Set; -import java.util.TreeSet; - -import javax.annotation.PostConstruct; -import javax.xml.bind.DatatypeConverter; - -import org.apache.http.HttpEntity; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoLogger; -import org.onap.so.utils.CryptoUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -/** - * This is the class that is used to POST replies from the MSO adapters to the BPEL engine. - * It can be configured via property file, or modified using the member methods. - * The properties to use are: - * org.onap.so.adapters.vnf.bpelauth encrypted authorization string to send to BEPL engine - * org.onap.so.adapters.vnf.sockettimeout socket timeout value - * org.onap.so.adapters.vnf.connecttimeout connect timeout value - * org.onap.so.adapters.vnf.retrycount number of times to retry failed connections - * org.onap.so.adapters.vnf.retryinterval interval (in seconds) between retries - * org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code - * 900 means "connection was not established") - */ -@Component("NetworkBpel") -@Scope("prototype") -public class BpelRestClient { - public static final String MSO_PROP_NETWORK_ADAPTER = "MSO_PROP_NETWORK_ADAPTER"; - private static final String PROPERTY_DOMAIN = "org.onap.so.adapters.network"; - private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN+".bpelauth"; - private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".sockettimeout"; - private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".connecttimeout"; - private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN+".retrycount"; - private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN+".retryinterval"; - private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN+".retrylist"; - private static final String ENCRYPTION_KEY_PROP = PROPERTY_DOMAIN + ".encryptionKey"; - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, BpelRestClient.class); - - @Autowired - private Environment env; - /** Default socket timeout (in seconds) */ - public static final int DEFAULT_SOCKET_TIMEOUT = 5; - /** Default connect timeout (in seconds) */ - public static final int DEFAULT_CONNECT_TIMEOUT = 5; - /** By default, retry up to five times */ - public static final int DEFAULT_RETRY_COUNT = 5; - /** Default interval to wait between retries (in seconds), negative means use backoff algorithm */ - public static final int DEFAULT_RETRY_INTERVAL = -15; - /** Default list of response codes to trigger a retry */ - public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed" - /** Default credentials */ - public static final String DEFAULT_CREDENTIALS = ""; - - // Properties of the BPEL client -- all are configurable - private int socketTimeout; - private int connectTimeout; - private int retryCount; - private int retryInterval; - private Set<Integer> retryList; - private String credentials; - - // last response from BPEL engine - private int lastResponseCode; - private String lastResponse; - - /** - * Create a client to send results to the BPEL engine, using configuration from the - * MSO_PROP_NETWORK_ADAPTER properties. - */ - public BpelRestClient() { - socketTimeout = DEFAULT_SOCKET_TIMEOUT; - connectTimeout = DEFAULT_CONNECT_TIMEOUT; - retryCount = DEFAULT_RETRY_COUNT; - retryInterval = DEFAULT_RETRY_INTERVAL; - setRetryList(DEFAULT_RETRY_LIST); - credentials = DEFAULT_CREDENTIALS; - lastResponseCode = 0; - lastResponse = ""; - - } - - @PostConstruct - protected void init() { - - socketTimeout = env.getProperty(SOCKET_TIMEOUT_PROPERTY, Integer.class, DEFAULT_SOCKET_TIMEOUT); - connectTimeout = env.getProperty(CONN_TIMEOUT_PROPERTY, Integer.class, DEFAULT_CONNECT_TIMEOUT); - retryCount = env.getProperty(RETRY_COUNT_PROPERTY, Integer.class, DEFAULT_RETRY_COUNT); - retryInterval = env.getProperty(RETRY_INTERVAL_PROPERTY, Integer.class, DEFAULT_RETRY_INTERVAL); - setRetryList(env.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST)); - credentials = getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, env.getProperty(ENCRYPTION_KEY_PROP)); - } - - public int getSocketTimeout() { - return socketTimeout; - } - - public void setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } - - public int getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public int getRetryCount() { - return retryCount; - } - - public void setRetryCount(int retryCount) { - int retCnt = 0; - if (retryCount < 0) - retCnt = DEFAULT_RETRY_COUNT; - this.retryCount = retCnt; - } - - public int getRetryInterval() { - return retryInterval; - } - - public void setRetryInterval(int retryInterval) { - this.retryInterval = retryInterval; - } - - public String getCredentials() { - return credentials; - } - - public void setCredentials(String credentials) { - this.credentials = credentials; - } - - public String getRetryList() { - if (retryList.isEmpty()) - return ""; - String t = retryList.toString(); - return t.substring(1, t.length()-1); - } - - public void setRetryList(String retryList) { - Set<Integer> s = new TreeSet<>(); - for (String t : retryList.split("[, ]")) { - try { - s.add(Integer.parseInt(t)); - } catch (NumberFormatException x) { - LOGGER.debug("Exception while parsing", x); - } - } - this.retryList = s; - } - - public int getLastResponseCode() { - return lastResponseCode; - } - - public String getLastResponse() { - return lastResponse; - } - - /** - * Post a response to the URL of the BPEL engine. As long as the response code is one of those in - * the retryList, the post will be retried up to "retrycount" times with an interval (in seconds) - * of "retryInterval". If retryInterval is negative, then each successive retry interval will be - * double the previous one. - * @param toBpelStr the content (XML or JSON) to post - * @param bpelUrl the URL to post to - * @param isxml true if the content is XML, otherwise assumed to be JSON - * @return true if the post succeeded, false if all retries failed - */ - public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) { - debug("Sending response to BPEL: " + toBpelStr); - int totalretries = 0; - int retryint = retryInterval; - while (true) { - sendOne(toBpelStr, bpelUrl, isxml); - // Note: really should handle response code 415 by switching between content types if needed - if (!retryList.contains(lastResponseCode)) { - debug("Got response code: " + lastResponseCode + ": returning."); - return true; - } - if (totalretries >= retryCount) { - debug("Retried " + totalretries + " times, giving up."); - LOGGER.error(MessageEnum.RA_SEND_VNF_NOTIF_ERR, "Could not deliver response to BPEL after "+totalretries+" tries: "+toBpelStr, "Camunda", "", MsoLogger.ErrorCode.DataError, "Could not deliver response to BPEL"); - return false; - } - totalretries++; - int sleepinterval = retryint; - if (retryint < 0) { - // if retry interval is negative double the retry on each pass - sleepinterval = -retryint; - retryint *= 2; - } - debug("Sleeping for " + sleepinterval + " seconds."); - try { - Thread.sleep(sleepinterval * 1000L); - } catch (InterruptedException e) { - LOGGER.debug("Exception while Thread sleep", e); - Thread.currentThread().interrupt(); - } - } - } - private void debug(String m) { - LOGGER.debug(m); - } - private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) { - LOGGER.debug("Sending to BPEL server: "+bpelUrl); - LOGGER.debug("Content is: "+toBpelStr); - - //POST - HttpPost post = new HttpPost(bpelUrl); - if (credentials != null && !credentials.isEmpty()) - post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes())); - - //ContentType - ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON; - post.setEntity(new StringEntity(toBpelStr, ctype)); - - //Timeouts - RequestConfig requestConfig = RequestConfig - .custom() - .setSocketTimeout(socketTimeout * 1000) - .setConnectTimeout(connectTimeout * 1000) - .build(); - post.setConfig(requestConfig); - - //Client 4.3+ - //Execute & GetResponse - try (CloseableHttpClient client = HttpClients.createDefault()) { - CloseableHttpResponse response = client.execute(post); - if (response != null) { - lastResponseCode = response.getStatusLine().getStatusCode(); - HttpEntity entity = response.getEntity(); - lastResponse = (entity != null) ? EntityUtils.toString(entity) : ""; - } else { - lastResponseCode = 900; - lastResponse = ""; - } - } catch (Exception e) { - String error = "Error sending Bpel notification:" + toBpelStr; - LOGGER.error (MessageEnum.RA_SEND_VNF_NOTIF_ERR, error, "Camunda", "", MsoLogger.ErrorCode.AvailabilityError, "Exception sending Bpel notification", e); - lastResponseCode = 900; - lastResponse = ""; - } - LOGGER.debug("Response code from BPEL server: "+lastResponseCode); - LOGGER.debug("Response body is: "+lastResponse); - } - - private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) { - if (env.getProperty(key) != null) { - try { - return CryptoUtils.decrypt(env.getProperty(key), encryptionKey); - } catch (GeneralSecurityException e) { - LOGGER.debug("Exception while decrypting property: " + env.getProperty(key), e); - } - } - return defaultValue; - } - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java index 8d08b3b52c..fd658244ee 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java @@ -59,6 +59,7 @@ import org.onap.so.adapters.nwrest.RollbackNetworkResponse; import org.onap.so.adapters.nwrest.UpdateNetworkError; import org.onap.so.adapters.nwrest.UpdateNetworkRequest; import org.onap.so.adapters.nwrest.UpdateNetworkResponse; +import org.onap.so.adapters.vnf.BpelRestClient; import org.onap.so.entity.MsoRequest; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java index 2f688dbf48..5645759b02 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java @@ -6,6 +6,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -23,6 +24,11 @@ package org.onap.so.adapters.valet; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import javax.annotation.PostConstruct; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; import org.onap.so.adapters.valet.beans.HeatRequest; import org.onap.so.adapters.valet.beans.ValetConfirmRequest; import org.onap.so.adapters.valet.beans.ValetConfirmResponse; @@ -34,16 +40,8 @@ import org.onap.so.adapters.valet.beans.ValetRollbackRequest; import org.onap.so.adapters.valet.beans.ValetRollbackResponse; import org.onap.so.adapters.valet.beans.ValetUpdateRequest; import org.onap.so.adapters.valet.beans.ValetUpdateResponse; - -import java.net.URI; - -import javax.annotation.PostConstruct; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.adapters.valet.GenericValetResponse; - -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.HttpEntity; @@ -52,14 +50,13 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.web.client.RestTemplate; @Component public class ValetClient { - private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ValetClient.class); + + private static Logger logger = LoggerFactory.getLogger(ValetClient.class); @Autowired private Environment environment; @@ -93,8 +90,8 @@ public class ValetClient { this.basePath = this.environment.getProperty(ValetClient.VALET_BASE_PATH, ValetClient.DEFAULT_BASE_PATH); this.authString = this.environment.getProperty(ValetClient.VALET_AUTH, ValetClient.DEFAULT_AUTH_STRING); } catch (Exception e) { - LOGGER.debug("Error retrieving valet properties. " + e.getMessage()); - } + logger.debug("Error retrieving valet properties. {}", e.getMessage()); + } } /* @@ -117,8 +114,8 @@ public class ValetClient { response = getRestTemplate().exchange(uri, HttpMethod.POST, entity, ValetCreateResponse.class); gvr = this.getGVRFromResponse(response); } catch (Exception e) { - LOGGER.error("An exception occurred in callValetCreateRequest", e); - throw e; + logger.error("An exception occurred in callValetCreateRequest", e); + throw e; } return gvr; } @@ -150,8 +147,8 @@ public class ValetClient { response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetUpdateResponse.class); gvr = this.getGVRFromResponse(response); } catch (Exception e) { - LOGGER.error("An exception occurred in callValetUpdateRequest", e); - throw e; + logger.error("An exception occurred in callValetUpdateRequest", e); + throw e; } return gvr; } @@ -177,8 +174,8 @@ public class ValetClient { response = getRestTemplate().exchange(uri, HttpMethod.DELETE, entity, ValetDeleteResponse.class); gvr = this.getGVRFromResponse(response); } catch (Exception e) { - LOGGER.error("An exception occurred in callValetDeleteRequest", e); - throw e; + logger.error("An exception occurred in callValetDeleteRequest", e); + throw e; } return gvr; } @@ -199,12 +196,12 @@ public class ValetClient { String body = mapper.writeValueAsString(vcr); HttpHeaders headers = generateHeaders(requestId); HttpEntity<String> entity = new HttpEntity<>(body, headers); - LOGGER.debug("valet confirm req: " + uri.toString() + HEADERS + headers.toString() + BODY + body); - + logger.debug("valet confirm req: {} {} {} {} {}", uri, HEADERS, headers, BODY, body); + response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetConfirmResponse.class); gvr = this.getGVRFromResponse(response); } catch (Exception e) { - LOGGER.error("An exception occurred in callValetConfirmRequest", e); + logger.error("An exception occurred in callValetConfirmRequest", e); throw e; } return gvr; @@ -231,7 +228,7 @@ public class ValetClient { response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetRollbackResponse.class); gvr = this.getGVRFromResponse(response); } catch (Exception e) { - LOGGER.error("An exception occurred in callValetRollbackRequest", e); + logger.error("An exception occurred in callValetRollbackRequest", e); throw e; } return gvr; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java index 5fa21c64b1..4b02b73786 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java @@ -57,7 +57,7 @@ import org.springframework.stereotype.Component; * org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code * 900 means "connection was not established") */ -@Component("VnfBpel") +@Component() @Scope("prototype") public class BpelRestClient { public static final String MSO_PROP_VNF_ADAPTER = "MSO_PROP_VNF_ADAPTER"; @@ -249,6 +249,8 @@ public class BpelRestClient { if (credentials != null && !credentials.isEmpty()) post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes())); + LOGGER.debug("HTTPPost Headers: " + post.getAllHeaders()); + //ContentType ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON; post.setEntity(new StringEntity(toBpelStr, ctype)); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java index cbdd29d83c..7913a6d827 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java @@ -6,6 +6,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -24,9 +25,13 @@ package org.onap.so.adapters.vnf; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import java.util.HashMap; import java.util.Map; - import javax.inject.Provider; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -41,7 +46,6 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; - import org.apache.http.HttpStatus; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; @@ -61,16 +65,12 @@ import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; import org.onap.so.openstack.exceptions.MsoExceptionCategory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - /** * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. @@ -81,7 +81,8 @@ import io.swagger.annotations.ApiResponses; @Api(value = "/v1/volume-groups", description = "root of volume-groups adapters restful web service") @Component public class VolumeAdapterRest { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, VolumeAdapterRest.class); + + private static final Logger logger = LoggerFactory.getLogger(VolumeAdapterRest.class); private static final String TESTING_KEYWORD = "___TESTING___"; private static final String EXCEPTION="Exception :"; private static final String RESP=", resp="; @@ -108,7 +109,7 @@ public class VolumeAdapterRest { @ApiParam(value = "CreateVolumeGroupRequest", required = true) final CreateVolumeGroupRequest req ) { - LOGGER.debug("createVNFVolumes enter: " + req.toJsonString()); + logger.debug("createVNFVolumes enter: {}", req.toJsonString()); CreateVNFVolumesTask task = new CreateVNFVolumesTask(req); if (req.isSynchronous()) { // This is a synchronous request @@ -124,11 +125,12 @@ public class VolumeAdapterRest { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_CREATE_VNF_ERR, "", "createVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - createVNFVolumes", e); + logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug ("createVNFVolumes exit"); + logger.debug("createVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -160,14 +162,14 @@ public class VolumeAdapterRest { } @Override public void run() { - LOGGER.debug ("CreateVFModule VolumesTask start"); + logger.debug("CreateVFModule VolumesTask start"); try { // Synchronous Web Service Outputs Holder<String> stackId = new Holder<>(); Holder<Map<String, String>> outputs = new Holder<>(); Holder<VnfRollback> vnfRollback = new Holder<>(); String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - LOGGER.debug("in createVfModuleVolumes - completeVnfVfModuleType=" + completeVnfVfModuleType); + logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); String cloudsite = req.getCloudSiteId(); if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) { @@ -231,7 +233,7 @@ public class VolumeAdapterRest { rb, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse( e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } @@ -240,7 +242,7 @@ public class VolumeAdapterRest { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug ("CreateVFModule VolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("CreateVFModule VolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -262,7 +264,7 @@ public class VolumeAdapterRest { final DeleteVolumeGroupRequest req ) { - LOGGER.debug("deleteVNFVolumes enter: " + req.toJsonString()); + logger.debug("deleteVNFVolumes enter: {}", req.toJsonString()); if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { return Response .status(HttpStatus.SC_BAD_REQUEST) @@ -285,11 +287,12 @@ public class VolumeAdapterRest { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_DELETE_VNF_ERR, "", "deleteVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - deleteVNFVolumes", e); + logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug ("deleteVNFVolumes exit"); + logger.debug("deleteVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -321,14 +324,14 @@ public class VolumeAdapterRest { } @Override public void run() { - LOGGER.debug("DeleteVNFVolumesTask start"); + logger.debug("DeleteVNFVolumesTask start"); try { if (!req.getCloudSiteId().equals(TESTING_KEYWORD)) { vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getTenantId(), req.getVolumeGroupStackId(), req.getMsoRequest()); } response = new DeleteVolumeGroupResponse(true, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } if (!req.isSynchronous()) { @@ -336,7 +339,7 @@ public class VolumeAdapterRest { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug("DeleteVNFVolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -358,7 +361,7 @@ public class VolumeAdapterRest { final RollbackVolumeGroupRequest req ) { - LOGGER.debug("rollbackVNFVolumes enter: " + req.toJsonString()); + logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString()); if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) { return Response .status(HttpStatus.SC_BAD_REQUEST) @@ -381,11 +384,12 @@ public class VolumeAdapterRest { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_ROLLBACK_VNF_ERR, "", "rollbackVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - rollbackVNFVolumes", e); + logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug("rollbackVNFVolumes exit"); + logger.debug("rollbackVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -417,7 +421,7 @@ public class VolumeAdapterRest { } @Override public void run() { - LOGGER.debug("DeleteVNFVolumesTask start"); + logger.debug("DeleteVNFVolumesTask start"); try { VolumeGroupRollback vgr = req.getVolumeGroupRollback(); VnfRollback vrb = new VnfRollback( @@ -426,7 +430,7 @@ public class VolumeAdapterRest { vnfAdapter.rollbackVnf(vrb); response = new RollbackVolumeGroupResponse(true, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } if (!req.isSynchronous()) { @@ -434,7 +438,7 @@ public class VolumeAdapterRest { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug("DeleteVNFVolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -457,7 +461,7 @@ public class VolumeAdapterRest { final UpdateVolumeGroupRequest req ) { - LOGGER.debug("updateVNFVolumes enter: " + req.toJsonString()); + logger.debug("updateVNFVolumes enter: {}", req.toJsonString()); if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { return Response .status(HttpStatus.SC_BAD_REQUEST) @@ -480,11 +484,12 @@ public class VolumeAdapterRest { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_UPDATE_VNF_ERR, "", "updateVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - updateVNFVolumes", e); + logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug ("updateVNFVolumes exit"); + logger.debug("updateVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -516,12 +521,12 @@ public class VolumeAdapterRest { } @Override public void run() { - LOGGER.debug("UpdateVNFVolumesTask start"); + logger.debug("UpdateVNFVolumesTask start"); try { Holder<Map<String, String>> outputs = new Holder<> (); Holder<VnfRollback> vnfRollback = new Holder<> (); String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - LOGGER.debug("in updateVfModuleVolume - completeVnfVfModuleType=" + completeVnfVfModuleType); + logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType); if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { outputs.value = testMap(); @@ -558,7 +563,7 @@ public class VolumeAdapterRest { req.getVolumeGroupId(), req.getVolumeGroupStackId(), outputs.value, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } if (!req.isSynchronous()) { @@ -566,7 +571,7 @@ public class VolumeAdapterRest { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug("UpdateVNFVolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("UpdateVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -597,7 +602,7 @@ public class VolumeAdapterRest { ) { //This request responds synchronously only - LOGGER.debug ("queryVNFVolumes enter:" + aaiVolumeGroupId + " " + volumeGroupStackId); + logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId); MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); try { @@ -619,23 +624,24 @@ public class VolumeAdapterRest { vnfAdapter.queryVnf(cloudSiteId, tenantId, volumeGroupStackId, msoRequest, vnfExists, vfModuleId, status, outputs); } if (!vnfExists.value) { - LOGGER.debug ("VNFVolumes not found"); + logger.debug("VNFVolumes not found"); qryResp.setVolumeGroupStatus(status.value); respStatus = HttpStatus.SC_NOT_FOUND; } else { - LOGGER.debug ("VNFVolumes found " + vfModuleId.value + ", status=" + status.value); + logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value); qryResp.setVolumeGroupStatus(status.value); qryResp.setVolumeGroupOutputs(outputs.value); } - LOGGER.debug("Query queryVNFVolumes exit"); + logger.debug("Query queryVNFVolumes exit"); return Response .status(respStatus) .entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}) .build(); } catch (VnfException e) { - LOGGER.error(MessageEnum.RA_QUERY_VNF_ERR, aaiVolumeGroupId, "", "queryVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "VnfException - queryVNFVolumes", e); + logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes", MessageEnum.RA_QUERY_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e); VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); - LOGGER.debug("Query queryVNFVolumes exit"); + logger.debug("Query queryVNFVolumes exit"); return Response .status(HttpStatus.SC_INTERNAL_SERVER_ERROR) .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}) diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java index 445f0071a7..3dc223f5c7 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -23,9 +24,13 @@ package org.onap.so.adapters.vnf; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import java.util.HashMap; import java.util.Map; - import javax.inject.Provider; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -40,7 +45,6 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; - import org.apache.http.HttpStatus; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; @@ -60,16 +64,12 @@ import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; import org.onap.so.openstack.exceptions.MsoExceptionCategory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - /** * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. @@ -83,7 +83,8 @@ import io.swagger.annotations.ApiResponses; @Api(value = "/v2/volume-groups", description = "root of volume-groups adapters restful web service v2") @Component public class VolumeAdapterRestV2 { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, VolumeAdapterRestV2.class); + + private static final Logger logger = LoggerFactory.getLogger(VolumeAdapterRestV2.class); private static final String TESTING_KEYWORD = "___TESTING___"; private static final String RESP=", resp="; private static final String EXCEPTION="Exception :"; @@ -113,7 +114,7 @@ public class VolumeAdapterRestV2 { @ApiParam(value = "CreateVolumeGroupRequest", required = true) final CreateVolumeGroupRequest req) { - LOGGER.debug("createVNFVolumes enter: " + req.toJsonString()); + logger.debug("createVNFVolumes enter: {}", req.toJsonString()); CreateVNFVolumesTask task = new CreateVNFVolumesTask(req, mode); if (req.isSynchronous()) { // This is a synchronous request @@ -129,11 +130,12 @@ public class VolumeAdapterRestV2 { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_CREATE_VNF_ERR, "", "createVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - createVNFVolumes", e); + logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug ("createVNFVolumes exit"); + logger.debug("createVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -167,14 +169,14 @@ public class VolumeAdapterRestV2 { } @Override public void run() { - LOGGER.debug ("CreateVFModule VolumesTask start"); + logger.debug("CreateVFModule VolumesTask start"); try { // Synchronous Web Service Outputs Holder<String> stackId = new Holder<>(); Holder<Map<String, String>> outputs = new Holder<>(); Holder<VnfRollback> vnfRollback = new Holder<>(); String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - LOGGER.debug("in createVfModuleVolumes - completeVnfVfModuleType=" + completeVnfVfModuleType); + logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); String cloudsiteId = req.getCloudSiteId(); if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) { @@ -226,7 +228,7 @@ public class VolumeAdapterRestV2 { rb, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse( e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } @@ -235,7 +237,7 @@ public class VolumeAdapterRestV2 { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug ("CreateVFModule VolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("CreateVFModule VolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -259,7 +261,7 @@ public class VolumeAdapterRestV2 { final DeleteVolumeGroupRequest req ) { - LOGGER.debug("deleteVNFVolumes enter: " + req.toJsonString()); + logger.debug("deleteVNFVolumes enter: {}", req.toJsonString()); if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { return Response .status(HttpStatus.SC_BAD_REQUEST) @@ -282,11 +284,12 @@ public class VolumeAdapterRestV2 { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_DELETE_VNF_ERR, "", "deleteVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - deleteVNFVolumes", e); + logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug ("deleteVNFVolumes exit"); + logger.debug("deleteVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -320,7 +323,7 @@ public class VolumeAdapterRestV2 { } @Override public void run() { - LOGGER.debug("DeleteVNFVolumesTask start"); + logger.debug("DeleteVNFVolumesTask start"); String cloudSiteId = req.getCloudSiteId(); try { if (! cloudSiteId.equals(TESTING_KEYWORD)) { @@ -330,7 +333,7 @@ public class VolumeAdapterRestV2 { } response = new DeleteVolumeGroupResponse(true, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } if (!req.isSynchronous()) { @@ -338,7 +341,7 @@ public class VolumeAdapterRestV2 { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug("DeleteVNFVolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("DeleteVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -360,7 +363,7 @@ public class VolumeAdapterRestV2 { final RollbackVolumeGroupRequest req ) { - LOGGER.debug("rollbackVNFVolumes enter: " + req.toJsonString()); + logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString()); if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) { return Response .status(HttpStatus.SC_BAD_REQUEST) @@ -383,11 +386,12 @@ public class VolumeAdapterRestV2 { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_ROLLBACK_VNF_ERR, "", "rollbackVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - rollbackVNFVolumes", e); + logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug("rollbackVNFVolumes exit"); + logger.debug("rollbackVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -419,7 +423,7 @@ public class VolumeAdapterRestV2 { } @Override public void run() { - LOGGER.debug("RollbackVNFVolumesTask start"); + logger.debug("RollbackVNFVolumesTask start"); try { VolumeGroupRollback vgr = req.getVolumeGroupRollback(); VnfRollback vrb = new VnfRollback( @@ -431,7 +435,7 @@ public class VolumeAdapterRestV2 { vnfAdapter.rollbackVnf(vrb); response = new RollbackVolumeGroupResponse(true, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } if (!req.isSynchronous()) { @@ -439,7 +443,7 @@ public class VolumeAdapterRestV2 { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug("RollbackVNFVolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("RollbackVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -464,7 +468,7 @@ public class VolumeAdapterRestV2 { final UpdateVolumeGroupRequest req ) { - LOGGER.debug("updateVNFVolumes enter: " + req.toJsonString()); + logger.debug("updateVNFVolumes enter: {}", req.toJsonString()); if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { return Response .status(HttpStatus.SC_BAD_REQUEST) @@ -487,11 +491,12 @@ public class VolumeAdapterRestV2 { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - LOGGER.error (MessageEnum.RA_UPDATE_VNF_ERR, "", "updateVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - updateVNFVolumes", e); + logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); return Response.serverError().build(); } // send sync response (ACK) to caller - LOGGER.debug ("updateVNFVolumes exit"); + logger.debug("updateVNFVolumes exit"); return Response.status(HttpStatus.SC_ACCEPTED).build(); } } @@ -525,12 +530,12 @@ public class VolumeAdapterRestV2 { } @Override public void run() { - LOGGER.debug("UpdateVNFVolumesTask start"); + logger.debug("UpdateVNFVolumesTask start"); try { Holder<Map<String, String>> outputs = new Holder<> (); Holder<VnfRollback> vnfRollback = new Holder<> (); String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - LOGGER.debug("in updateVfModuleVolume - completeVnfVfModuleType=" + completeVnfVfModuleType); + logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType); if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { outputs.value = testMap(); @@ -557,7 +562,7 @@ public class VolumeAdapterRestV2 { req.getVolumeGroupId(), req.getVolumeGroupStackId(), outputs.value, req.getMessageId()); } catch (VnfException e) { - LOGGER.debug(EXCEPTION,e); + logger.debug(EXCEPTION, e); eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); } if (!req.isSynchronous()) { @@ -565,7 +570,7 @@ public class VolumeAdapterRestV2 { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - LOGGER.debug("UpdateVNFVolumesTask exit: code=" + getStatusCode() + RESP+ getResponse()); + logger.debug("UpdateVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); } } @@ -598,7 +603,7 @@ public class VolumeAdapterRestV2 { ) { //This request responds synchronously only - LOGGER.debug ("queryVNFVolumes enter:" + aaiVolumeGroupId + " " + volumeGroupStackId); + logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId); MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); try { @@ -622,23 +627,24 @@ public class VolumeAdapterRestV2 { vnfAdapter.queryVnf(cloudSiteId, tenantId, volumeGroupStackId, msoRequest, vnfExists, vfModuleId, status, outputs); } if (!vnfExists.value) { - LOGGER.debug ("VNFVolumes not found"); + logger.debug("VNFVolumes not found"); qryResp.setVolumeGroupStatus(status.value); respStatus = HttpStatus.SC_NOT_FOUND; } else { - LOGGER.debug ("VNFVolumes found " + vfModuleId.value + ", status=" + status.value); + logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value); qryResp.setVolumeGroupStatus(status.value); qryResp.setVolumeGroupOutputs(outputs.value); } - LOGGER.debug("Query queryVNFVolumes exit"); + logger.debug("Query queryVNFVolumes exit"); return Response .status(respStatus) .entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}) .build(); } catch (VnfException e) { - LOGGER.error(MessageEnum.RA_QUERY_VNF_ERR, aaiVolumeGroupId, "", "queryVNFVolumes", MsoLogger.ErrorCode.BusinessProcesssError, "VnfException - queryVNFVolumes", e); + logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes: ", MessageEnum.RA_QUERY_VNF_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e); VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); - LOGGER.debug("Query queryVNFVolumes exit"); + logger.debug("Query queryVNFVolumes exit"); return Response .status(HttpStatus.SC_INTERNAL_SERVER_ERROR) .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}) diff --git a/adapters/mso-openstack-adapters/src/main/resources/application.yaml b/adapters/mso-openstack-adapters/src/main/resources/application.yaml index 4e8d389998..a68372f833 100644 --- a/adapters/mso-openstack-adapters/src/main/resources/application.yaml +++ b/adapters/mso-openstack-adapters/src/main/resources/application.yaml @@ -18,7 +18,7 @@ mso: retryMultiplier: 60000 spring: datasource: - url: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb + jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb username: ${DB_USERNAME} password: ${DB_PASSWORD} driver-class-name: org.mariadb.jdbc.Driver diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/BpelRestClientTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/BpelRestClientTest.java deleted file mode 100644 index 02a5f25b41..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/BpelRestClientTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.network; - -import static org.junit.Assert.assertEquals; - -import javax.inject.Provider; - -import org.junit.Test; -import org.onap.so.adapters.vnf.BaseRestTestUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.web.server.LocalServerPort; - -public class BpelRestClientTest extends BaseRestTestUtils { - - - @LocalServerPort - private int port; - @Autowired - @Qualifier("NetworkBpel") - private Provider<BpelRestClient> clientProvider; - - @Test - public void verifyPropertiesRead() { - BpelRestClient client = clientProvider.get(); - - assertEquals(5, client.getRetryCount()); - assertEquals(5, client.getConnectTimeout()); - assertEquals("test:test", client.getCredentials()); - assertEquals(5, client.getSocketTimeout()); - assertEquals("408, 429, 500, 502, 503, 504, 900", client.getRetryList()); - assertEquals(-15, client.getRetryInterval()); - - } - -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java index 20a3e62ade..4b2fa8138a 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java @@ -35,7 +35,6 @@ public class BpelRestClientTest extends BaseRestTestUtils{ @LocalServerPort private int port; @Autowired - @Qualifier("VnfBpel") private Provider<BpelRestClient> clientProvider; @Test diff --git a/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml b/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml index 781d49f908..051884d60d 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml +++ b/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml @@ -77,7 +77,7 @@ mso: queue-capacity: 500 spring: datasource: - jdbc-url: jdbc:mariadb://localhost:3307/catalogdb + jdbcUrl: jdbc:mariadb://localhost:3307/catalogdb username: root password: password driver-class-name: org.mariadb.jdbc.Driver diff --git a/adapters/mso-requests-db-adapter/src/main/resources/application.yaml b/adapters/mso-requests-db-adapter/src/main/resources/application.yaml index 5a0ef6df74..645a6e9e38 100644 --- a/adapters/mso-requests-db-adapter/src/main/resources/application.yaml +++ b/adapters/mso-requests-db-adapter/src/main/resources/application.yaml @@ -18,7 +18,7 @@ mso: # H2 spring: datasource: - url: jdbc:mariadb://${DB_HOST}:${DB_PORT}/requestdb + jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/requestdb username: ${DB_USERNAME} password: ${DB_PASSWORD} driver-class-name: org.mariadb.jdbc.Driver diff --git a/adapters/mso-requests-db-adapter/src/test/resources/application-test.yaml b/adapters/mso-requests-db-adapter/src/test/resources/application-test.yaml index 94a132664e..522e6bb7a3 100644 --- a/adapters/mso-requests-db-adapter/src/test/resources/application-test.yaml +++ b/adapters/mso-requests-db-adapter/src/test/resources/application-test.yaml @@ -19,7 +19,7 @@ mso: period: 0
spring:
datasource:
- url: jdbc:mariadb://localhost:3307/requestdb
+ jdbcUrl: jdbc:mariadb://localhost:3307/requestdb
username: root
password: password
driver-class-name: org.mariadb.jdbc.Driver
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java index e74dd64bb3..5deec41d94 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -33,6 +34,8 @@ import javax.xml.ws.WebServiceFeature; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This class was generated by Apache CXF 2.7.11.redhat-3 @@ -46,7 +49,7 @@ import org.onap.so.logger.MsoLogger; targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1") public class SDNCAdapterService extends Service { - private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, SDNCAdapterService.class); + private static Logger logger = LoggerFactory.getLogger(SDNCAdapterService.class); private static final String SDNC_ADAPTER_WSDL="SDNCAdapter.wsdl"; public static final URL WSDL_LOCATION; @@ -58,16 +61,19 @@ public class SDNCAdapterService extends Service { try { wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCAdapter.wsdl"); } catch (Exception e) { - logger.error(MessageEnum.RA_WSDL_NOT_FOUND, SDNC_ADAPTER_WSDL, "", "", MsoLogger.ErrorCode.DataError, "Exception - WSDL not found", e); + logger.error("{} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL, + MsoLogger.ErrorCode.DataError.getValue(), "Exception - WSDL not found", e); } if(wsdlUrl == null) { - logger.error(MessageEnum.RA_WSDL_NOT_FOUND, SDNC_ADAPTER_WSDL, "", "", MsoLogger.ErrorCode.DataError, "WSDL not found"); - } else { + logger.error("{} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL, + MsoLogger.ErrorCode.DataError.getValue(), "WSDL not found"); + } else { try { - logger.info(MessageEnum.RA_PRINT_URL, SDNC_ADAPTER_WSDL, wsdlUrl.toURI().toString(), ""); + logger.info("{} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_ADAPTER_WSDL, wsdlUrl.toURI().toString()); } catch (Exception e) { - logger.error(MessageEnum.RA_WSDL_URL_CONVENTION_EXC, SDNC_ADAPTER_WSDL, "", "", MsoLogger.ErrorCode.DataError, "Exception - print URL", e); - } + logger.error("{} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_ADAPTER_WSDL, + MsoLogger.ErrorCode.DataError.getValue(), "Exception - print URL", e); + } } WSDL_LOCATION = wsdlUrl; } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java index 7ec20afffd..3dcd008ba5 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -33,6 +35,9 @@ import javax.xml.bind.annotation.XmlType; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * <p>Java class for anonymous complex type. * @@ -67,7 +72,7 @@ public class SDNCAdapterCallbackRequest { @XmlElement(name = "RequestData") protected Object requestData; - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, SDNCAdapterCallbackRequest.class); + private static Logger logger = LoggerFactory.getLogger(SDNCAdapterCallbackRequest.class); /** * Gets the value of the callbackHeader property. @@ -130,8 +135,9 @@ public class SDNCAdapterCallbackRequest { } catch (Exception e) { - msoLogger.error(MessageEnum.RA_MARSHING_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception - MARSHING_ERROR", e); - } + logger.error("{} {} {}", MessageEnum.RA_MARSHING_ERROR.toString(), MsoLogger.ErrorCode.DataError.getValue(), + "Exception - MARSHING_ERROR", e); + } return ""; } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java index e4882090bf..fd288c6a04 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -31,6 +33,8 @@ import javax.xml.ws.WebServiceFeature; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This class was generated by Apache CXF 2.7.11.redhat-3 @@ -44,7 +48,7 @@ import org.onap.so.logger.MsoLogger; targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1") public class SDNCCallbackAdapterService extends Service { - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, SDNCCallbackAdapterService.class); + private static Logger logger = LoggerFactory.getLogger(SDNCCallbackAdapterService.class); private static final String SDNC_CALLBACK_ADAPTER_WSDL="SDNCCallbackAdapter.wsdl"; public static final URL WSDL_LOCATION; public static final QName SERVICE = new QName("http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterService"); @@ -54,16 +58,20 @@ public class SDNCCallbackAdapterService extends Service { try { wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCCallbackAdapter.wsdl"); } catch (Exception e) { - msoLogger.error(MessageEnum.RA_WSDL_NOT_FOUND, SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - WSDL not found", e); + logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Exception - WSDL not found", e); } if(wsdlUrl == null) { - msoLogger.error(MessageEnum.RA_WSDL_NOT_FOUND, SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", "", MsoLogger.ErrorCode.DataError, "WSDL not found"); - } else { + logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "WSDL not found"); + } else { try { - msoLogger.info(MessageEnum.RA_PRINT_URL, SDNC_CALLBACK_ADAPTER_WSDL, wsdlUrl.toURI().toString(), "SDNC"); - } catch (Exception e) { - msoLogger.error(MessageEnum.RA_WSDL_URL_CONVENTION_EXC, SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - URL convention problem", e); - } + logger.info("{} {} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_CALLBACK_ADAPTER_WSDL, + wsdlUrl.toURI().toString(), "SDNC"); + } catch (Exception e) { + logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_CALLBACK_ADAPTER_WSDL, + "SDNC", MsoLogger.ErrorCode.DataError.getValue(), "Exception - URL convention problem", e); + } } WSDL_LOCATION = wsdlUrl; } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java index a5800fc73d..6262f2d86f 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -24,6 +25,8 @@ package org.onap.so.adapters.sdnc.impl; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -31,7 +34,7 @@ import org.springframework.stereotype.Component; @Component public class MapRequestTunables { - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,MapRequestTunables.class); + private static Logger logger = LoggerFactory.getLogger(MapRequestTunables.class); public static final String GENERATED_KEY = "Generated key: "; @Autowired @@ -44,14 +47,14 @@ public class MapRequestTunables { String key; if ("query".equals(reqTunable.getAction())) { //due to variable format for reqTunable.getOperation() eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9 key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + ".." + reqTunable.getAction(); - msoLogger.debug(GENERATED_KEY + key); + logger.debug(GENERATED_KEY + key); } else if ("put".equals(reqTunable.getAction()) || "restdelete".equals(reqTunable.getAction())) { //due to variable format for reqTunable.getOperation() eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9 key = Constants.REQUEST_TUNABLES + "..." + reqTunable.getAction(); - msoLogger.debug(GENERATED_KEY + key); + logger.debug(GENERATED_KEY + key); } else { key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + "." + reqTunable.getOperation() +"." + reqTunable.getAction(); - msoLogger.debug(GENERATED_KEY + key); + logger.debug(GENERATED_KEY + key); } String value; @@ -61,31 +64,32 @@ public class MapRequestTunables { String[] parts = value.split("\\|"); //escape pipe if (parts.length < 3) { - msoLogger.warn(MessageEnum.RA_SDNC_INVALID_CONFIG, key, value, "SDNC", "", MsoLogger.ErrorCode.DataError, "Invalid config"); + logger.warn("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), key, value, "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Invalid config"); } for (int i = 0; i < parts.length; i++) { if (i == 0) { reqTunable.setReqMethod(parts[i]) ; - msoLogger.debug("Request Method is set to: " + reqTunable.getReqMethod()); + logger.debug("Request Method is set to: {}", reqTunable.getReqMethod()); } else if (i == 1) { reqTunable.setTimeout( parts[i]); - msoLogger.debug("Timeout is set to: " + reqTunable.getTimeout()); + logger.debug("Timeout is set to: {}", reqTunable.getTimeout()); } else if (i == 2) { reqTunable.setSdncUrl(env.getProperty(Constants.REQUEST_TUNABLES + "." + parts[i],"")); if (reqTunable.getOperation() != null && reqTunable.getSdncUrl() != null) { reqTunable.setSdncUrl(reqTunable.getSdncUrl() + reqTunable.getOperation()); } - msoLogger.debug("SDNC Url is set to: " + reqTunable.getSdncUrl()); + logger.debug("SDNC Url is set to: {}", reqTunable.getSdncUrl()); } else if (i == 3) { reqTunable.setHeaderName(parts[i]); - msoLogger.debug("HeaderName is set to: " + reqTunable.getHeaderName()); + logger.debug("HeaderName is set to: {}", reqTunable.getHeaderName()); } else if (i == 4) { reqTunable.setNamespace(parts[i]); - msoLogger.debug("NameSpace is set to: " + reqTunable.getNamespace()); + logger.debug("NameSpace is set to: {}", reqTunable.getNamespace()); } else if (i == 5) { reqTunable.setAsyncInd(parts[i]); - msoLogger.debug("AsyncInd is set to: " + reqTunable.getAsyncInd()); + logger.debug("AsyncInd is set to: {}", reqTunable.getAsyncInd()); } } @@ -96,9 +100,10 @@ public class MapRequestTunables { error = "Missing configuration for:" + key; } if (error != null) { - msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, key, "SDNC", "", MsoLogger.ErrorCode.DataError, "Missing config param"); + logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), key, "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Missing config param"); } - msoLogger.debug ("RequestTunables Key:" + key + " Value:" + value + " Tunables:" + this.toString()); + logger.debug("RequestTunables Key:{} Value:{} Tunables:{}", key, value, this.toString()); return reqTunable; } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java index 4a6ac9f5e2..cf81ae4be0 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -30,6 +32,8 @@ import org.onap.so.adapters.sdnc.SDNCAdapterResponse; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -40,7 +44,7 @@ public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCAdapterPortTypeImpl.class); + private static Logger logger = LoggerFactory.getLogger(SDNCAdapterPortTypeImpl.class); @Autowired @@ -48,7 +52,7 @@ public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { @PostConstruct public void init () { - msoLogger.info(MessageEnum.RA_INIT_SDNC_ADAPTER, "SDNC", "SDNCAdapterPortType", ""); + logger.info("{} {} {}", MessageEnum.RA_INIT_SDNC_ADAPTER.toString(), "SDNC", "SDNCAdapterPortType"); } /** @@ -57,7 +61,7 @@ public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { @Override public void healthCheck () { - msoLogger.debug("Health check call in SDNC Adapter"); + logger.debug("Health check call in SDNC Adapter"); } @@ -70,7 +74,8 @@ public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { } catch (Exception e){ String respMsg = "Error sending request to SDNC. Failed to start SDNC Client thread " + e.getMessage(); - msoLogger.error(MessageEnum.RA_SEND_REQUEST_SDNC_ERR, "SDNC", "", MsoLogger.ErrorCode.DataError, respMsg, e); + logger.error("{} {} {} {}", MessageEnum.RA_SEND_REQUEST_SDNC_ERR.toString(), "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), respMsg, e); SDNCResponse sdncResp = new SDNCResponse(bpelReqId); sdncResp.setRespCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java index 59884f25b8..d7f2c11d0b 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java @@ -55,6 +55,8 @@ import org.onap.so.adapters.sdnc.client.SDNCCallbackAdapterService; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.Async; @@ -74,7 +76,7 @@ public class SDNCRestClient{ @Autowired private MapRequestTunables tunablesMapper; - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCRestClient.class); + private static Logger logger = LoggerFactory.getLogger(SDNCRestClient.class); private static final String EXCEPTION_MSG="Exception while evaluate xpath"; private static final String MSO_INTERNAL_ERROR="MsoInternalError"; @@ -83,7 +85,7 @@ public class SDNCRestClient{ public void executeRequest(SDNCAdapterRequest bpelRequest) { - msoLogger.debug("BPEL Request:" + bpelRequest.toString()); + logger.debug("BPEL Request:" + bpelRequest.toString()); // Added delay to allow completion of create request to SDNC // before executing activate of create request. @@ -124,11 +126,9 @@ public class SDNCRestClient{ } long sdncStartTime = System.currentTimeMillis(); SDNCResponse sdncResp = getSdncResp(sdncReqBody, rt); - msoLogger.recordMetricEvent (sdncStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from SDNC", "SDNC", action + "." + operation, null); - msoLogger.debug ("Got the SDNC Response: " + sdncResp.getSdncRespXml()); + logger.debug ("Got the SDNC Response: {}", sdncResp.getSdncRespXml()); long bpelStartTime = System.currentTimeMillis(); sendRespToBpel(callbackUrl, sdncResp); - msoLogger.recordMetricEvent (bpelStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully send reauest to BPEL", "BPMN", callbackUrl, null); return; } @@ -142,8 +142,8 @@ public class SDNCRestClient{ SDNCResponse sdncResp = new SDNCResponse(rt.getReqId()); StringBuilder response = new StringBuilder(); - msoLogger.info(MessageEnum.RA_SEND_REQUEST_SDNC.name() + ":\n" + rt.toString(), "SDNC", ""); - msoLogger.trace("SDNC Request Body:\n" + sdncReqBody); + logger.info("{} :\n {} {}", MessageEnum.RA_SEND_REQUEST_SDNC.name(), rt.toString(), "SDNC"); + logger.trace("SDNC Request Body:{} \n", sdncReqBody); try { @@ -186,12 +186,13 @@ public class SDNCRestClient{ } sdncResp.setSdncRespXml(response.toString()); - msoLogger.info(MessageEnum.RA_RESPONSE_FROM_SDNC.name() + ":\n" + sdncResp.toString(), "SDNC", ""); + logger.info("{} :\n {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.name(), sdncResp.toString(), "SDNC"); return(sdncResp); } catch (Exception e) { - msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception processing request to SDNC", e); + logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception processing request to SDNC", e); //default sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR); String respMsg = "Error processing request to SDNC. "; @@ -231,7 +232,8 @@ public class SDNCRestClient{ eType = xpath.evaluate("error-type", error); sdncErrMsg = new StringBuilder(". SDNC Returned-[error-type:" + eType); } catch (Exception e3) { - msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, EXCEPTION_MSG, e3); + logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type", + error.toString(), "SDNC", MsoLogger.ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3); } String eTag = null; @@ -239,7 +241,8 @@ public class SDNCRestClient{ eTag = xpath.evaluate( "error-tag", error); sdncErrMsg.append(", error-tag:").append(eTag); } catch (Exception e3) { - msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, EXCEPTION_MSG, e3); + logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag", + error.toString(), "SDNC", MsoLogger.ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3); } String eMsg = null; @@ -247,15 +250,18 @@ public class SDNCRestClient{ eMsg = xpath.evaluate("error-message", error); sdncErrMsg.append(", error-message:").append(eMsg).append("]"); } catch (Exception e3) { - msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, EXCEPTION_MSG, e3); + logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message", error.toString(), + "SDNC", MsoLogger.ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3); } } } catch (Exception e2) { - msoLogger.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while analyse error", e2); + logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Exception while analyse error", e2); } } //is != null } catch (Exception e1) { - msoLogger.error (MessageEnum.RA_ERROR_GET_RESPONSE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception while get SDNC response", e1); + logger.error("{} {} {} {}", MessageEnum.RA_ERROR_GET_RESPONSE_SDNC.toString(), "SDNC", + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception while get SDNC response", e1); } } //con != null @@ -266,7 +272,8 @@ public class SDNCRestClient{ sdncResp.setRespMsg(respMsg); - msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with SDNC", e); + logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + MsoLogger.ErrorCode.AvailabilityError.getValue(), "Exception while communicate with SDNC", e); return sdncResp; } @@ -289,14 +296,15 @@ public class SDNCRestClient{ { cbReq.setRequestData(sdncResp.getSdncRespXml()); } - msoLogger.info(MessageEnum.RA_CALLBACK_BPEL.name() + ":\n" + cbReq.toString(), CAMUNDA, ""); + logger.info("{} :\n {} {}", MessageEnum.RA_CALLBACK_BPEL.name(), cbReq.toString(), CAMUNDA); URL wsdlUrl = null; try { wsdlUrl = new URL (bpelUrl); } catch (MalformedURLException e1) { error = "Caught exception initializing Callback wsdl " + e1.getMessage(); - msoLogger.error(MessageEnum.RA_INIT_CALLBACK_WSDL_ERR, CAMUNDA, "", MsoLogger.ErrorCode.DataError, "Exception initializing Callback wsdl", e1); + logger.error("{} {} {} {}", MessageEnum.RA_INIT_CALLBACK_WSDL_ERR.toString(), CAMUNDA, + MsoLogger.ErrorCode.DataError.getValue(), "Exception initializing Callback wsdl", e1); } @@ -310,7 +318,7 @@ public class SDNCRestClient{ bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, wsdlUrl.toExternalForm()); } else { - msoLogger.debug("wsdlUrl is NULL:"); + logger.debug("wsdlUrl is NULL:"); } //authentication @@ -326,22 +334,23 @@ public class SDNCRestClient{ } catch (Exception e2) { error = "Unable to set authorization in callback request " + e2.getMessage(); - msoLogger.error(MessageEnum.RA_SET_CALLBACK_AUTH_EXC, CAMUNDA, "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - Unable to set authorization in callback request", e2); + logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + "Exception - Unable to set authorization in callback request", e2); } - msoLogger.debug("Invoking Bpel Callback. BpelCallbackUrl:" + bpelUrl); + logger.debug("Invoking Bpel Callback. BpelCallbackUrl:{}", bpelUrl); cbPort.sdncAdapterCallback(cbReq); } catch (Exception e) { error = "Error sending BpelCallback request" + e.getMessage(); - msoLogger.error("Error " + MsoLogger.ErrorCode.BusinessProcesssError + " - " + MessageEnum.RA_CALLBACK_BPEL_EXC + " - " + error, e); - + logger.error("Error {} - {} - {}", MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), error, e); } - msoLogger.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE.name(), CAMUNDA, ""); + logger.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE.name(), CAMUNDA); return; } - } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java index 55af0d7cad..96e7dcf51a 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -33,13 +35,15 @@ import javax.xml.transform.stream.StreamResult; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Utils { - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, Utils.class); + private static Logger logger = LoggerFactory.getLogger(Utils.class); private Utils() { } @@ -94,11 +98,12 @@ public class Utils { } String s = domToStr(newdoc); - msoLogger.debug("Formatted SdncReq:\n" + s); + logger.debug("Formatted SdncReq:\n", s); return s; } catch (Exception e) { - msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in genSdncReq", e); + logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e); } return null; } @@ -127,11 +132,12 @@ public class Utils { } String s = domToStr(newdoc); - msoLogger.debug("Formatted SdncPutReq:\n" + s); + logger.debug("Formatted SdncPutReq:\n {}", s); return s; } catch (Exception e) { - msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception in genSdncPutReq", e); + logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Exception in genSdncPutReq", e); } return null; } @@ -161,11 +167,12 @@ public class Utils { root.appendChild(elem3); String s = domToStr(newdoc); - msoLogger.debug("Formatted SdncReq:" + s); + logger.debug("Formatted SdncReq: {}", s); return s; } catch (Exception e) { - msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception in genMsoFailResp", e); + logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE.toString(), "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Exception in genMsoFailResp", e); } return null; } @@ -191,7 +198,8 @@ public class Utils { s = s.replaceAll("xmlns=\"\"", ""); return s; } catch (Exception e) { - msoLogger.error(MessageEnum.RA_ERROR_CONVERT_XML2STR, "", "", MsoLogger.ErrorCode.DataError, "Exception - domToStr", e); + logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), MsoLogger.ErrorCode.DataError + .getValue(), "Exception - domToStr", e); } } return null; diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java index e427423763..6a66770d29 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java @@ -6,6 +6,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -38,6 +39,8 @@ import org.onap.so.adapters.sdnc.impl.Constants; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.onap.so.utils.CryptoUtils; @@ -49,7 +52,7 @@ import org.springframework.core.env.Environment; */ @Component public class BPRestCallback { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,BPRestCallback.class); + private static final Logger logger = LoggerFactory.getLogger(BPRestCallback.class); private static final String CAMUNDA="Camunda"; private static final String MSO_INTERNAL_ERROR="MsoInternalError"; @@ -66,7 +69,7 @@ public class BPRestCallback { * @return true if the message was consumed successfully by the endpoint */ public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) { - LOGGER.debug(getClass().getSimpleName() + ".send(" + logger.debug(getClass().getSimpleName() + ".send(" + "workflowMessageUrl=" + workflowMessageUrl + " messageType=" + messageType + " correlator=" + correlator @@ -91,12 +94,13 @@ public class BPRestCallback { * @return true if the message was consumed successfully by the endpoint */ public boolean send(String url, String message) { - LOGGER.debug(getClass().getSimpleName() + ".send(" + logger.debug(getClass().getSimpleName() + ".send(" + "url=" + url + " message=" + message + ")"); - LOGGER.info(MessageEnum.RA_CALLBACK_BPEL, message == null ? "[no content]" : message, CAMUNDA, ""); + logger.info("{} {} {}", MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message, + CAMUNDA); HttpPost method = null; HttpResponse httpResponse = null; @@ -129,8 +133,8 @@ public class BPRestCallback { method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID,MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME,"SO-SDNCAdapter"); } catch (Exception e) { - LOGGER.error(MessageEnum.RA_SET_CALLBACK_AUTH_EXC, CAMUNDA, "", MsoLogger.ErrorCode.BusinessProcesssError, - "Unable to set authorization in callback request", e); + logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Unable to set authorization in callback request", e); error = true; } @@ -146,14 +150,15 @@ public class BPRestCallback { if (httpResponse.getStatusLine().getStatusCode() >= 300) { String msg = "Received error response to callback request: " + httpResponse.getStatusLine(); - LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, CAMUNDA, "", MsoLogger.ErrorCode.BusinessProcesssError, msg); + logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, MsoLogger.ErrorCode + .BusinessProcesssError.getValue(), msg); } } return true; } catch (Exception e) { - LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, CAMUNDA, "", MsoLogger.ErrorCode.BusinessProcesssError, - "Error sending callback request", e); + logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Error sending callback request", e); return false; } finally { if (httpResponse != null) { @@ -161,7 +166,7 @@ public class BPRestCallback { EntityUtils.consume(httpResponse.getEntity()); httpResponse = null; } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); } } @@ -169,10 +174,10 @@ public class BPRestCallback { try { method.reset(); } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); } } - LOGGER.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE, CAMUNDA, "",""); + logger.info("{} {}", MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA); } } -}
\ No newline at end of file +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java index 6f40ba07a9..fd9ce4c719 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -27,6 +28,8 @@ import org.onap.so.adapters.sdnc.impl.Constants; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -34,9 +37,7 @@ import org.springframework.stereotype.Component; @Component public class MapTypedRequestTunablesData { - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,MapTypedRequestTunablesData.class); - - + private static Logger logger = LoggerFactory.getLogger(MapTypedRequestTunablesData.class); private static final String MISSING_CONFIGURATION_ERROR_MSG= "Missing configuration for: "; private static final String MISSING_CONFIG_PARAM_ERROR_MSG="Missing config param"; @@ -54,7 +55,8 @@ public class MapTypedRequestTunablesData { if ("".equals(value)) { error= MISSING_CONFIGURATION_ERROR_MSG + reqTunable.getKey(); - msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, reqTunable.getKey(), "SDNC", "", MsoLogger.ErrorCode.DataError, MISSING_CONFIG_PARAM_ERROR_MSG); + logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), reqTunable.getKey(), "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG); throw new SDNCAdapterException(error); } @@ -63,41 +65,42 @@ public class MapTypedRequestTunablesData { if (parts.length != 5) { error="Invalid configuration for: " + reqTunable.getKey(); - msoLogger.error(MessageEnum.RA_SDNC_INVALID_CONFIG, reqTunable.getKey(), value, "SDNC", "", MsoLogger.ErrorCode.DataError, "Invalid config"); - + logger.error("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), reqTunable.getKey(), value, "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Invalid config"); throw new SDNCAdapterException(error); } reqTunable.setReqMethod(parts[0]); - msoLogger.trace("Request Method is set to: " + reqTunable.getReqMethod()); + logger.trace("Request Method is set to: {}", reqTunable.getReqMethod()); reqTunable.setTimeout(parts[1]); - msoLogger.trace("Timeout is set to: " + reqTunable.getTimeout()); + logger.trace("Timeout is set to: {}", reqTunable.getTimeout()); String urlPropKey = Constants.REQUEST_TUNABLES + "." + parts[2]; reqTunable.setSdncUrl(env.getProperty(urlPropKey, "")); if ("".equals(reqTunable.getSdncUrl())) { error=MISSING_CONFIGURATION_ERROR_MSG + urlPropKey; - msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, urlPropKey, "SDNC", "", MsoLogger.ErrorCode.DataError, MISSING_CONFIG_PARAM_ERROR_MSG); + logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), urlPropKey, "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG); throw new SDNCAdapterException(error); } - msoLogger.trace("SDNC Url is set to: " + reqTunable.getSdncUrl()); + logger.trace("SDNC Url is set to: {}", reqTunable.getSdncUrl()); reqTunable.setHeaderName(parts[3]); - msoLogger.trace("Header Name is set to: " + reqTunable.getHeaderName()); + logger.trace("Header Name is set to: {}", reqTunable.getHeaderName()); reqTunable.setNamespace(parts[4]); - msoLogger.trace("Namespace is set to: " + reqTunable.getNamespace()); + logger.trace("Namespace is set to: {}", reqTunable.getNamespace()); reqTunable.setMyUrl(env.getProperty(Constants.MY_URL_PROP, "")); if ("".equals(reqTunable.getMyUrl())) { error=MISSING_CONFIGURATION_ERROR_MSG + Constants.MY_URL_PROP; - msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, Constants.MY_URL_PROP, "SDNC", "", - MsoLogger.ErrorCode.DataError, MISSING_CONFIG_PARAM_ERROR_MSG); + logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.MY_URL_PROP, "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG); throw new SDNCAdapterException(error); } @@ -108,7 +111,7 @@ public class MapTypedRequestTunablesData { reqTunable.setMyUrl(reqTunable.getMyUrl().concat(reqTunable.getMyUrlSuffix())); - msoLogger.debug(reqTunable.toString()); + logger.debug(reqTunable.toString()); return reqTunable; } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java index dcb1fdae8c..8cafbda325 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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 @@ -21,11 +23,11 @@ package org.onap.so.adapters.sdnc.sdncrest; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.web.util.UriUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -35,7 +37,7 @@ import org.w3c.dom.NodeList; * Utility methods used by SDNCAdapterRest. */ public final class SDNCAdapterUtils { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, SDNCAdapterUtils.class); + private static final Logger logger = LoggerFactory.getLogger(SDNCAdapterUtils.class); /** * Instantiation is not allowed. */ @@ -67,4 +69,4 @@ public final class SDNCAdapterUtils { public static String encodeURLPathSegment(String pathSegment) { return UriUtils.encodePathSegment(pathSegment, "UTF-8"); } -}
\ No newline at end of file +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java index 3ecf6337cf..06e7ab23a6 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java @@ -6,6 +6,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -54,6 +55,8 @@ import org.onap.so.adapters.sdncrest.SDNCResponseCommon; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.w3c.dom.Document; @@ -68,7 +71,7 @@ import org.springframework.core.env.Environment; */ @Component public abstract class SDNCConnector { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCConnector.class); + private static final Logger logger = LoggerFactory.getLogger(SDNCConnector.class); private static final String MSO_INTERNAL_ERROR="MsoInternalError"; private static final String XPATH_EXCEPTION="XPath Exception"; @@ -76,8 +79,8 @@ public abstract class SDNCConnector { private Environment env; public SDNCResponseCommon send(String content, TypedRequestTunables rt) { - LOGGER.debug("SDNC URL: " + rt.getSdncUrl()); - LOGGER.debug("SDNC Request Body:\n" + content); + logger.debug("SDNC URL: {}", rt.getSdncUrl()); + logger.debug("SDNC Request Body:\n {}", content); HttpRequestBase method = null; HttpResponse httpResponse = null; @@ -122,7 +125,7 @@ public abstract class SDNCConnector { method.setHeader("Accept", "application/yang.data+xml"); } else { - LOGGER.debug("method is NULL:"); + logger.debug("method is NULL:"); } @@ -137,8 +140,8 @@ public abstract class SDNCConnector { int statusCode = httpResponse.getStatusLine().getStatusCode(); String statusMessage = httpResponse.getStatusLine().getReasonPhrase(); - LOGGER.debug("SDNC Response: " + statusCode + " " + statusMessage - + (responseContent == null ? "" : System.lineSeparator() + responseContent)); + logger.debug("SDNC Response: {} {}", statusCode, + statusMessage + (responseContent == null ? "" : System.lineSeparator() + responseContent)); if (httpResponse.getStatusLine().getStatusCode() >= 300) { String errMsg = "SDNC returned " + statusCode + " " + statusMessage; @@ -159,12 +162,12 @@ public abstract class SDNCConnector { method.reset(); } else { - LOGGER.debug("method is NULL:"); + logger.debug("method is NULL:"); } method = null; - LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", ""); + logger.info("{} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), responseContent, "SDNC"); return createResponseFromContent(statusCode, statusMessage, responseContent, rt); } catch (SocketTimeoutException | ConnectTimeoutException e) { @@ -182,7 +185,7 @@ public abstract class SDNCConnector { try { EntityUtils.consume(httpResponse.getEntity()); } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); } } @@ -190,22 +193,20 @@ public abstract class SDNCConnector { try { method.reset(); } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); } } } } protected void logError(String errMsg) { - LOGGER.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", - MsoLogger.ErrorCode.AvailabilityError, errMsg); - + logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + MsoLogger.ErrorCode.AvailabilityError.getValue(), errMsg); } protected void logError(String errMsg, Throwable t) { - LOGGER.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", - MsoLogger.ErrorCode.AvailabilityError, errMsg, t); - + logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + MsoLogger.ErrorCode.AvailabilityError.getValue(), errMsg, t); } /** @@ -288,8 +289,8 @@ public abstract class SDNCConnector { String errorType = xpath.evaluate("error-type", error); info += "error-type:" + errorType; } catch (XPathExpressionException e) { - LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "", - MsoLogger.ErrorCode.DataError, XPATH_EXCEPTION, e); + logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type", error.toString(), + "SDNC", MsoLogger.ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); } try { @@ -299,8 +300,8 @@ public abstract class SDNCConnector { } info += "error-tag:" + errorTag; } catch (XPathExpressionException e) { - LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "", - MsoLogger.ErrorCode.DataError, XPATH_EXCEPTION, e); + logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag", error.toString(), + "SDNC", MsoLogger.ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); } try { @@ -310,8 +311,8 @@ public abstract class SDNCConnector { } info += "error-message:" + errorMessage; } catch (Exception e) { - LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "", - MsoLogger.ErrorCode.DataError, XPATH_EXCEPTION, e); + logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message", + error.toString(), "SDNC", MsoLogger.ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); } if (!info.isEmpty()) { @@ -323,8 +324,8 @@ public abstract class SDNCConnector { } } } catch (Exception e) { - LOGGER.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "", - MsoLogger.ErrorCode.DataError, "Exception while analyzing errors", e); + logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", + MsoLogger.ErrorCode.DataError.getValue(), "Exception while analyzing errors", e); } return output.toString(); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java index 8ca14501e5..57051e570e 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java @@ -6,6 +6,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -38,7 +39,8 @@ import org.onap.so.adapters.sdncrest.SDNCErrorCommon; import org.onap.so.adapters.sdncrest.SDNCResponseCommon; import org.onap.so.adapters.sdncrest.SDNCServiceError; import org.onap.so.adapters.sdncrest.SDNCServiceResponse; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -52,17 +54,17 @@ import org.xml.sax.SAXException; @Component public class SDNCServiceRequestConnector extends SDNCConnector { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,SDNCServiceRequestConnector.class); + private static final Logger logger = LoggerFactory.getLogger(SDNCServiceRequestConnector.class); @Override protected SDNCResponseCommon createResponseFromContent(int statusCode, String statusMessage, String responseContent, TypedRequestTunables rt) { try { return parseResponseContent(responseContent); } catch (ParseException e) { - LOGGER.error(e); + logger.error("Error occured:", e); return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt); }catch (Exception e) { - LOGGER.error(e); + logger.error("Error occured:", e); return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt); } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java index deb39ac54e..62233273b1 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -34,12 +36,13 @@ import javax.xml.transform.stream.StreamResult; import org.apache.http.HttpStatus; import org.onap.so.adapters.sdnc.exception.SDNCAdapterException; import org.onap.so.adapters.sdncrest.RequestInformation; -import org.onap.so.adapters.sdncrest.SDNCErrorCommon; import org.onap.so.adapters.sdncrest.SDNCResponseCommon; import org.onap.so.adapters.sdncrest.SDNCServiceError; import org.onap.so.adapters.sdncrest.SDNCServiceRequest; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @@ -48,7 +51,7 @@ import org.w3c.dom.Element; @Component public class SDNCServiceRequestTask { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCServiceRequestTask.class); + private static final Logger logger = LoggerFactory.getLogger(SDNCServiceRequestTask.class); @Autowired private SDNCServiceRequestConnector connector; @@ -91,24 +94,8 @@ public class SDNCServiceRequestTask { long sdncStartTime = System.currentTimeMillis(); SDNCResponseCommon response = connector.send(xml, mappedTunables); - if (response instanceof SDNCErrorCommon) { - LOGGER.recordMetricEvent(sdncStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - "Received success response from SDNC", "SDNC", sdncService + "." + sdncOperation, null); - } else { - LOGGER.recordMetricEvent(sdncStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, - "Received error response from SDNC", "SDNC", sdncService + "." + sdncOperation, null); - } - long bpStartTime = System.currentTimeMillis(); boolean callbackSuccess = bpRestCallback.send(request.getBPNotificationUrl(), response.toJson()); - - if (callbackSuccess) { - LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - "Sent notification", "BPMN", request.getBPNotificationUrl(), null); - } else { - LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, - "Failed to send notification", "BPMN", request.getBPNotificationUrl(), null); - } } private Element addChild(Element parent, String tag) { @@ -206,8 +193,8 @@ public class SDNCServiceRequestTask { addTextChild(agnosticServiceInformation, "content-type", contentType); addTextChild(agnosticServiceInformation, "anydata", anydata); } catch (Exception e) { - LOGGER.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", - MsoLogger.ErrorCode.BusinessProcesssError, "Exception in genSdncReq", e); + logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e); return null; } @@ -225,12 +212,12 @@ public class SDNCServiceRequestTask { transformer.transform(new DOMSource(doc), new StreamResult(writer)); xml = writer.toString(); } catch (Exception e) { - LOGGER.error(MessageEnum.RA_ERROR_CONVERT_XML2STR, "", "", - MsoLogger.ErrorCode.DataError, "Exception - domToStr", e); + logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), MsoLogger.ErrorCode.DataError.getValue(), + "Exception - domToStr", e); return null; } - LOGGER.trace("Formatted SDNC service request XML:\n" + xml); + logger.trace("Formatted SDNC service request XML:\n {}", xml); return xml; } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java index 48bc2d84bb..75a0b07643 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -35,6 +36,8 @@ import org.onap.so.adapters.sdnc.impl.Constants; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -47,7 +50,7 @@ import org.springframework.stereotype.Component; @Path("/") @Component public class SNIROResponse { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SNIROResponse.class); + private static final Logger logger = LoggerFactory.getLogger(SNIROResponse.class); @Autowired @@ -61,34 +64,18 @@ public class SNIROResponse { @Consumes("*/*") @Produces({MediaType.TEXT_PLAIN}) public Response serviceNotification(@PathParam("correlator") String correlator, String content) { - LOGGER.info(MessageEnum.RA_RECEIVE_SDNC_NOTIF, content, "SDNC", "SDNCNotify/SNIROResponse"); - - long startTime = System.currentTimeMillis(); + logger.info("{} {} {} {}", MessageEnum.RA_RECEIVE_SDNC_NOTIF.toString(), content, "SDNC", + "SDNCNotify/SNIROResponse"); String bpUrl = env.getProperty(Constants.BPEL_REST_URL_PROP, ""); if (bpUrl == null || ("").equals(bpUrl)) { String error = "Missing configuration for: " + Constants.BPEL_REST_URL_PROP; - LOGGER.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, Constants.BPEL_REST_URL_PROP, "SDNC", "", - MsoLogger.ErrorCode.DataError, "Missing config param"); + logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.BPEL_REST_URL_PROP, + "SDNC", MsoLogger.ErrorCode.DataError.getValue(), "Missing config param"); return Response.status(HttpServletResponse.SC_BAD_REQUEST).entity(error).build(); } - - long bpStartTime = System.currentTimeMillis(); - boolean callbackSuccess = callback.send(bpUrl, "SNIROResponse", correlator, content); - - if (callbackSuccess) { - LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - "Sent notification", "BPMN", bpUrl, null); - LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful"); - } else { - LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, - "Failed to send notification", "BPMN", bpUrl, null); - LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, - "Failed to send notification"); - } - return Response.status(204).build(); } -}
\ No newline at end of file +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java index 6331d6aaae..4ff6dbc9a6 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 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 @@ -22,7 +24,8 @@ package org.onap.so.adapters.sdnc.sdncrest; import org.apache.commons.lang3.builder.ToStringBuilder; import org.onap.so.adapters.sdnc.impl.Constants; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Typed Request Tunables. Each entry is identified by a TYPE in the property name. @@ -39,7 +42,7 @@ import org.onap.so.logger.MsoLogger; */ public class TypedRequestTunables { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, TypedRequestTunables.class); + private static final Logger logger = LoggerFactory.getLogger(TypedRequestTunables.class); private String reqId; private String myUrlSuffix; @@ -82,7 +85,7 @@ public class TypedRequestTunables { */ public void setServiceKey(String service, String operation) { key = Constants.REQUEST_TUNABLES + ".service." + service + "." + operation; - LOGGER.debug("Generated " + getClass().getSimpleName() + " key: " + key); + logger.debug("Generated {} key: {}", getClass().getSimpleName(), key); } /** diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java index f2fba5900f..d72775399f 100644 --- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java +++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 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 @@ -20,7 +22,8 @@ package org.onap.so.adapters.sdnc; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; @@ -30,7 +33,7 @@ import java.io.InputStream; */ public class FileUtil { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, FileUtil.class); + private static final Logger logger = LoggerFactory.getLogger(FileUtil.class); /** * Read the specified resource file and return the contents as a String. @@ -53,7 +56,7 @@ public class FileUtil { return ""; } } catch (IOException e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); return ""; } } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java index ce5637baa3..5d9b7ce558 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * Copyright (C) 2018 CMCC 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. @@ -26,10 +27,10 @@ import java.io.ByteArrayOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; -import org.onap.so.logger.MsoLogger; - import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * NS Create Input Parameter For VFC Adapter<br> @@ -40,7 +41,7 @@ import com.fasterxml.jackson.databind.SerializationFeature; */ public class NSResourceInputParameter { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, NSResourceInputParameter.class); + private static final Logger logger = LoggerFactory.getLogger(NSResourceInputParameter.class); private NsOperationKey nsOperationKey; @@ -114,7 +115,7 @@ public class NSResourceInputParameter { mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); jsonString = mapper.writeValueAsString(this); } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); } return jsonString; } @@ -128,7 +129,7 @@ public class NSResourceInputParameter { marshaller.marshal(this, bs); return bs.toString(); } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); return ""; } } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java index c39a165338..52fd8fb103 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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 @@ -27,8 +29,8 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; -import org.onap.so.logger.MsoLogger; -import org.onap.so.utils.UUIDChecker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** @@ -44,7 +46,7 @@ import org.springframework.stereotype.Component; @Component public class HealthCheckHandler { - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, HealthCheckHandler.class); + private static Logger logger = LoggerFactory.getLogger(HealthCheckHandler.class); private static final String CHECK_HTML = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>"; @@ -57,8 +59,6 @@ public class HealthCheckHandler { @Path("/healthcheck") @Produces("text/html") public Response healthcheck(@QueryParam("requestId") String requestId) { - MsoLogger.setServiceName("Healthcheck"); - UUIDChecker.verifyOldUUID(requestId, msoLogger); return HEALTH_CHECK_RESPONSE; } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java index 0f0a14c8f5..db613ea988 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -36,7 +37,8 @@ import org.onap.so.adapters.vfc.model.NsOperationKey; import org.onap.so.adapters.vfc.model.RestfulResponse; import org.onap.so.adapters.vfc.util.JsonUtil; import org.onap.so.adapters.vfc.util.ValidateUtil; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -52,7 +54,7 @@ import org.springframework.stereotype.Component; @Path("/v1/vfcadapter") public class VfcAdapterRest { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, VfcAdapterRest.class); + private static final Logger logger = LoggerFactory.getLogger(VfcAdapterRest.class); private static final String REQUEST_DEBUG_MSG="body from request is {}"; private static final String APPLICATION_EXCEPTION="ApplicationException: "; @Autowired @@ -76,12 +78,12 @@ public class VfcAdapterRest { public Response createNfvoNs(String data) { try { ValidateUtil.assertObjectNotNull(data); - LOGGER.debug(REQUEST_DEBUG_MSG + data); + logger.debug(REQUEST_DEBUG_MSG + data); NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class); RestfulResponse rsp = driverMgr.createNs(nsInput); return buildResponse(rsp); } catch(ApplicationException e) { - LOGGER.debug(APPLICATION_EXCEPTION, e); + logger.debug(APPLICATION_EXCEPTION, e); return e.buildErrorResponse(); } } @@ -102,12 +104,12 @@ public class VfcAdapterRest { try { ValidateUtil.assertObjectNotNull(data); - LOGGER.debug(REQUEST_DEBUG_MSG + data); + logger.debug(REQUEST_DEBUG_MSG + data); NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class); RestfulResponse rsp = driverMgr.deleteNs(nsOperationKey, nsInstanceId); return buildResponse(rsp); } catch(ApplicationException e) { - LOGGER.debug(APPLICATION_EXCEPTION, e); + logger.debug(APPLICATION_EXCEPTION, e); return e.buildErrorResponse(); } } @@ -127,12 +129,12 @@ public class VfcAdapterRest { public Response queryNfvoJobStatus(String data, @PathParam("jobId") String jobId) { try { ValidateUtil.assertObjectNotNull(data); - LOGGER.debug(REQUEST_DEBUG_MSG + data); + logger.debug(REQUEST_DEBUG_MSG + data); NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class); RestfulResponse rsp = driverMgr.getNsProgress(nsOperationKey, jobId); return buildResponse(rsp); } catch(ApplicationException e) { - LOGGER.debug(APPLICATION_EXCEPTION, e); + logger.debug(APPLICATION_EXCEPTION, e); return e.buildErrorResponse(); } } @@ -152,12 +154,12 @@ public class VfcAdapterRest { public Response instantiateNfvoNs(String data, @PathParam("nsInstanceId") String nsInstanceId) { try { ValidateUtil.assertObjectNotNull(data); - LOGGER.debug(REQUEST_DEBUG_MSG + data); + logger.debug(REQUEST_DEBUG_MSG + data); NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class); RestfulResponse rsp = driverMgr.instantiateNs(nsInstanceId, nsInput); return buildResponse(rsp); } catch(ApplicationException e) { - LOGGER.debug(APPLICATION_EXCEPTION, e); + logger.debug(APPLICATION_EXCEPTION, e); return e.buildErrorResponse(); } } @@ -177,12 +179,12 @@ public class VfcAdapterRest { public Response terminateNfvoNs(String data, @PathParam("nsInstanceId") String nsInstanceId) { try { ValidateUtil.assertObjectNotNull(data); - LOGGER.debug(REQUEST_DEBUG_MSG + data); + logger.debug(REQUEST_DEBUG_MSG + data); NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class); RestfulResponse rsp = driverMgr.terminateNs(nsOperationKey, nsInstanceId); return buildResponse(rsp); } catch(ApplicationException e) { - LOGGER.debug(APPLICATION_EXCEPTION, e); + logger.debug(APPLICATION_EXCEPTION, e); return e.buildErrorResponse(); } } @@ -201,16 +203,16 @@ public class VfcAdapterRest { @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response scaleNfvoNs(String data, @PathParam("nsInstanceId") String nsInstanceId) { - try { - ValidateUtil.assertObjectNotNull(data); - LOGGER.debug("Scale Ns Request Received.Body from request is {}" + data); - NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class); - RestfulResponse rsp = driverMgr.scaleNs(nsInstanceId, nsInput); - return buildResponse(rsp); - } catch(ApplicationException e) { - LOGGER.debug(APPLICATION_EXCEPTION, e); - return e.buildErrorResponse(); - } + try { + ValidateUtil.assertObjectNotNull(data); + logger.debug("Scale Ns Request Received.Body from request is {}" + data); + NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class); + RestfulResponse rsp = driverMgr.scaleNs(nsInstanceId, nsInput); + return buildResponse(rsp); + } catch (ApplicationException e) { + logger.debug(APPLICATION_EXCEPTION, e); + return e.buildErrorResponse(); + } } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java index 64032e25f5..66ed6953a2 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018 IBM. + * 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. @@ -33,6 +34,8 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Interface for json analyzing.<br/> @@ -47,7 +50,7 @@ public class JsonUtil { /** * Log service */ - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, JsonUtil.class); + private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); /** * Mapper. @@ -83,7 +86,7 @@ public class JsonUtil { try { return MAPPER.readValue(jsonstr, type); } catch (IOException e) { - LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, + logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), MsoLogger.ErrorCode.BusinessProcesssError.getValue(), UNMARSHAL_FAIL_MSG, e); throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG); } @@ -101,7 +104,7 @@ public class JsonUtil { try { return MAPPER.readValue(jsonstr, type); } catch (IOException e) { - LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, + logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), MsoLogger.ErrorCode.BusinessProcesssError.getValue(), UNMARSHAL_FAIL_MSG, e); throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG); } @@ -118,7 +121,7 @@ public class JsonUtil { try { return MAPPER.writeValueAsString(srcObj); } catch (IOException e) { - LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, + logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "fail to marshal json", e); throw new ApplicationException(HttpCode.BAD_REQUEST, "srcObj marshal failed!"); } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java index bb7fa70bda..9a23861bf6 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java @@ -6,6 +6,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2018. + * 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. @@ -44,6 +45,8 @@ import org.apache.http.util.EntityUtils; import org.onap.so.adapters.vfc.model.RestfulResponse; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -63,7 +66,7 @@ public class RestfulUtil { /** * Log service */ - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, RestfulUtil.class); + private static final Logger logger = LoggerFactory.getLogger(RestfulUtil.class); private static final int DEFAULT_TIME_OUT = 60000; @@ -88,7 +91,7 @@ public class RestfulUtil { Integer msbPort = env.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT); String msbEndpoint = UriBuilder.fromPath("").host(msbIp).port(msbPort).scheme("http").build().toString(); - LOGGER.debug("msbEndpoint in vfc adapter: " + msbEndpoint); + logger.debug("msbEndpoint in vfc adapter: {}", msbEndpoint); return msbEndpoint; } @@ -99,7 +102,7 @@ public class RestfulUtil { public RestfulResponse send(String url, String methodType, String content) { String msbUrl = getMsbHost() + url; - LOGGER.debug("Begin to sent message " + methodType +": " + msbUrl); + logger.debug("Begin to sent message {}: {}", methodType, msbUrl); HttpRequestBase method = null; HttpResponse httpResponse = null; @@ -132,14 +135,6 @@ public class RestfulUtil { method = httpDelete; } - // now VFC have no auth - // String userCredentials = - // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP, - // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY); - // String authorization = "Basic " + - // DatatypeConverter.printBase64Binary(userCredentials.getBytes()); - // method.setHeader("Authorization", authorization); - httpResponse = client.execute(method); String responseContent = null; @@ -150,7 +145,7 @@ public class RestfulUtil { int statusCode = httpResponse.getStatusLine().getStatusCode(); String statusMessage = httpResponse.getStatusLine().getReasonPhrase(); - LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage + logger.debug("VFC Response: {} {}", statusCode, statusMessage + (responseContent == null ? "" : System.lineSeparator() + responseContent)); if(httpResponse.getStatusLine().getStatusCode() >= 300) { @@ -164,7 +159,7 @@ public class RestfulUtil { if(null != method) { method.reset(); } else { - LOGGER.debug("method is NULL:"); + logger.debug("method is NULL:"); } method = null; @@ -185,7 +180,7 @@ public class RestfulUtil { try { EntityUtils.consume(httpResponse.getEntity()); } catch(Exception e) { - LOGGER.debug("Exception :", e); + logger.debug("Exception :", e); } } @@ -193,18 +188,20 @@ public class RestfulUtil { try { method.reset(); } catch(Exception e) { - LOGGER.debug("Exception :", e); + logger.debug("Exception :", e); } } } } private static void logError(String errMsg, Throwable t) { - LOGGER.error(MessageEnum.RA_NS_EXC, VFC_ADAPTER, "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t); + logger.error("{} {} {} {}", MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER, + MsoLogger.ErrorCode.AvailabilityError.getValue(), errMsg, t); } private static void logError(String errMsg) { - LOGGER.error(MessageEnum.RA_NS_EXC, VFC_ADAPTER, "", MsoLogger.ErrorCode.AvailabilityError, errMsg); + logger.error("{} {} {} {}", MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER, + MsoLogger.ErrorCode.AvailabilityError.toString(), errMsg); } private static RestfulResponse createResponse(int statusCode, String content) { |