From 3772c8513f618f9b76fc7bfa55fa140eb60f2a4b Mon Sep 17 00:00:00 2001 From: sebdet Date: Fri, 29 Mar 2019 11:52:02 +0100 Subject: Refactoring Small refactoring of the Http library Issue-ID: CLAMP-333 Change-Id: I90a5488241ab84636bc0cec5849e97c4f98f3a38 Signed-off-by: sebdet --- .../clamp/clds/client/DcaeDispatcherServices.java | 4 +- .../clamp/clds/client/DcaeInventoryServices.java | 2 +- src/main/java/org/onap/clamp/loop/Loop.java | 40 ++- .../java/org/onap/clamp/loop/LoopOperation.java | 371 ++++++++++++++++++++ .../org/onap/clamp/operation/LoopOperation.java | 374 --------------------- .../org/onap/clamp/policy/PolicyOperation.java | 4 +- .../org/onap/clamp/util/HttpConnectionManager.java | 37 +- 7 files changed, 410 insertions(+), 422 deletions(-) create mode 100644 src/main/java/org/onap/clamp/loop/LoopOperation.java delete mode 100644 src/main/java/org/onap/clamp/operation/LoopOperation.java (limited to 'src/main/java') diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java index 0f465959..f74af49f 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java @@ -99,7 +99,7 @@ public class DcaeDispatcherServices { Date startTime = new Date(); LoggingUtils.setTargetContext("DCAE", "getOperationStatus"); try { - String responseStr = dcaeHttpConnectionManager.doGeneralHttpQuery(statusUrl, "GET", null, null, "DCAE", null, null); + String responseStr = dcaeHttpConnectionManager.doHttpRequest(statusUrl, "GET", null, null, "DCAE", null, null); JSONObject jsonObj = parseResponse(responseStr); String operationType = (String) jsonObj.get("operationType"); String status = (String) jsonObj.get(DCAE_STATUS_FIELD); @@ -190,7 +190,7 @@ public class DcaeDispatcherServices { String nodeAttr) throws IOException, ParseException { Date startTime = new Date(); try { - String responseStr = dcaeHttpConnectionManager.doGeneralHttpQuery(url, requestMethod, payload, contentType, "DCAE", null, null); + String responseStr = dcaeHttpConnectionManager.doHttpRequest(url, requestMethod, payload, contentType, "DCAE", null, null); JSONObject jsonObj = parseResponse(responseStr); JSONObject linksObj = (JSONObject) jsonObj.get(node); String statusUrl = (String) linksObj.get(nodeAttr); diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java index d8bfeeae..dcf05423 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java @@ -207,7 +207,7 @@ public class DcaeInventoryServices { } for (int i = 0; i < retryLimit; i++) { metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory"); - String response = httpConnectionManager.doGeneralHttpQuery(fullUrl, "GET", null, null, "DCAE", null, null); + String response = httpConnectionManager.doHttpRequest(fullUrl, "GET", null, null, "DCAE", null, null); int totalCount = getTotalCountFromDcaeInventoryResponse(response); metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount); if (totalCount > 0) { diff --git a/src/main/java/org/onap/clamp/loop/Loop.java b/src/main/java/org/onap/clamp/loop/Loop.java index cc04ce5d..e62874a8 100644 --- a/src/main/java/org/onap/clamp/loop/Loop.java +++ b/src/main/java/org/onap/clamp/loop/Loop.java @@ -105,8 +105,7 @@ public class Loop implements Serializable { @Expose @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name = "loops_microservicepolicies", joinColumns = @JoinColumn(name = "loop_id"), - inverseJoinColumns = @JoinColumn(name = "microservicepolicy_id")) + @JoinTable(name = "loops_microservicepolicies", joinColumns = @JoinColumn(name = "loop_id"), inverseJoinColumns = @JoinColumn(name = "microservicepolicy_id")) private Set microServicePolicies = new HashSet<>(); @Expose @@ -135,23 +134,23 @@ public class Loop implements Serializable { this.name = name; } - public String getDcaeDeploymentId() { + String getDcaeDeploymentId() { return dcaeDeploymentId; } - public void setDcaeDeploymentId(String dcaeDeploymentId) { + void setDcaeDeploymentId(String dcaeDeploymentId) { this.dcaeDeploymentId = dcaeDeploymentId; } - public String getDcaeDeploymentStatusUrl() { + String getDcaeDeploymentStatusUrl() { return dcaeDeploymentStatusUrl; } - public void setDcaeDeploymentStatusUrl(String dcaeDeploymentStatusUrl) { + void setDcaeDeploymentStatusUrl(String dcaeDeploymentStatusUrl) { this.dcaeDeploymentStatusUrl = dcaeDeploymentStatusUrl; } - public String getSvgRepresentation() { + String getSvgRepresentation() { return svgRepresentation; } @@ -159,7 +158,7 @@ public class Loop implements Serializable { this.svgRepresentation = svgRepresentation; } - public String getBlueprint() { + String getBlueprint() { return blueprint; } @@ -167,11 +166,11 @@ public class Loop implements Serializable { this.blueprint = blueprint; } - public LoopState getLastComputedState() { + LoopState getLastComputedState() { return lastComputedState; } - public void setLastComputedState(LoopState lastComputedState) { + void setLastComputedState(LoopState lastComputedState) { this.lastComputedState = lastComputedState; } @@ -183,7 +182,7 @@ public class Loop implements Serializable { this.operationalPolicies = operationalPolicies; } - public Set getMicroServicePolicies() { + Set getMicroServicePolicies() { return microServicePolicies; } @@ -222,7 +221,7 @@ public class Loop implements Serializable { log.setLoop(this); } - public String getDcaeBlueprintId() { + String getDcaeBlueprintId() { return dcaeBlueprintId; } @@ -230,7 +229,7 @@ public class Loop implements Serializable { this.dcaeBlueprintId = dcaeBlueprintId; } - public JsonObject getModelPropertiesJson() { + JsonObject getModelPropertiesJson() { return modelPropertiesJson; } @@ -240,13 +239,18 @@ public class Loop implements Serializable { /** * Generate the loop name. - * @param serviceName The service name - * @param serviceVersion The service version - * @param resourceName The resource name - * @param blueprintFileName The blueprint file name + * + * @param serviceName + * The service name + * @param serviceVersion + * The service version + * @param resourceName + * The resource name + * @param blueprintFileName + * The blueprint file name * @return The generated loop name */ - public static String generateLoopName(String serviceName, String serviceVersion, String resourceName, + static String generateLoopName(String serviceName, String serviceVersion, String resourceName, String blueprintFilename) { StringBuilder buffer = new StringBuilder("LOOP_").append(serviceName).append("_v").append(serviceVersion) .append("_").append(resourceName).append("_").append(blueprintFilename.replaceAll(".yaml", "")); diff --git a/src/main/java/org/onap/clamp/loop/LoopOperation.java b/src/main/java/org/onap/clamp/loop/LoopOperation.java new file mode 100644 index 00000000..7def783b --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/LoopOperation.java @@ -0,0 +1,371 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 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.clamp.loop; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +import java.io.IOException; +import java.lang.reflect.Array; +import java.util.Collection; +import java.util.Date; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.camel.Exchange; +import org.onap.clamp.clds.client.DcaeDispatcherServices; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.clamp.clds.util.ONAPLogConstants; +import org.onap.clamp.exception.OperationException; +import org.onap.clamp.policy.PolicyOperation; +import org.onap.clamp.util.HttpConnectionManager; +import org.slf4j.event.Level; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.yaml.snakeyaml.Yaml; + +/** + * Closed loop operations + */ +@Component +public class LoopOperation { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class); + protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); + private final DcaeDispatcherServices dcaeDispatcherServices; + private final LoopService loopService; + private LoggingUtils util = new LoggingUtils(logger); + private PolicyOperation policyOp; + + @Autowired + private HttpServletRequest request; + + @Autowired + public LoopOperation(LoopService loopService, DcaeDispatcherServices dcaeDispatcherServices, + ClampProperties refProp, HttpConnectionManager httpConnectionManager, PolicyOperation policyOp) { + this.loopService = loopService; + this.dcaeDispatcherServices = dcaeDispatcherServices; + this.policyOp = policyOp; + } + + /** + * Deploy the closed loop. + * + * @param loopName the loop name + * @return the updated loop + * @throws Exceptions during the operation + */ + public Loop deployLoop(Exchange camelExchange, String loopName) throws OperationException { + util.entering(request, "CldsService: Deploy model"); + Date startTime = new Date(); + Loop loop = loopService.getLoop(loopName); + + if (loop == null) { + String msg = "Deploy loop exception: Not able to find closed loop:" + loopName; + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // verify the current closed loop state + if (loop.getLastComputedState() != LoopState.SUBMITTED) { + String msg = "Deploy loop exception: This closed loop is in state:" + loop.getLastComputedState() + + ". It could be deployed only when it is in SUBMITTED state."; + util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // Set the deploymentId if not present yet + String deploymentId = ""; + // If model is already deployed then pass same deployment id + if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) { + deploymentId = loop.getDcaeDeploymentId(); + } else { + loop.setDcaeDeploymentId(deploymentId = "closedLoop_" + loopName + "_deploymentId"); + } + + Yaml yaml = new Yaml(); + Map yamlMap = yaml.load(loop.getBlueprint()); + JsonObject bluePrint = wrapSnakeObject(yamlMap).getAsJsonObject(); + + loop.setDcaeDeploymentStatusUrl(dcaeDispatcherServices.createNewDeployment(deploymentId, loop.getDcaeBlueprintId(), bluePrint)); + loop.setLastComputedState(LoopState.DEPLOYED); + // save the updated loop + loopService.saveOrUpdateLoop (loop); + + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + auditLogger.info("Deploy model completed"); + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + return loop; + } + + /** + * Un deploy closed loop. + * + * @param loopName the loop name + * @return the updated loop + */ + public Loop unDeployLoop(String loopName) throws OperationException { + util.entering(request, "LoopOperation: Undeploy the closed loop"); + Date startTime = new Date(); + Loop loop = loopService.getLoop(loopName); + + if (loop == null) { + String msg = "Undeploy loop exception: Not able to find closed loop:" + loopName; + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // verify the current closed loop state + if (loop.getLastComputedState() != LoopState.DEPLOYED) { + String msg = "Unploy loop exception: This closed loop is in state:" + loop.getLastComputedState() + + ". It could be undeployed only when it is in DEPLOYED state."; + util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + loop.setDcaeDeploymentStatusUrl( + dcaeDispatcherServices.deleteExistingDeployment(loop.getDcaeDeploymentId(), loop.getDcaeBlueprintId())); + + // clean the deployment ID + loop.setDcaeDeploymentId(null); + loop.setLastComputedState(LoopState.SUBMITTED); + + // save the updated loop + loopService.saveOrUpdateLoop (loop); + + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + auditLogger.info("Undeploy model completed"); + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + return loop; + } + + private JsonElement wrapSnakeObject(Object o) { + //NULL => JsonNull + if (o == null) + return JsonNull.INSTANCE; + + // Collection => JsonArray + if (o instanceof Collection) { + JsonArray array = new JsonArray(); + for (Object childObj : (Collection)o) + array.add(wrapSnakeObject(childObj)); + return array; + } + + // Array => JsonArray + if (o.getClass().isArray()) { + JsonArray array = new JsonArray(); + + int length = Array.getLength(array); + for (int i=0; i JsonObject + if (o instanceof Map) { + Map map = (Map)o; + + JsonObject jsonObject = new JsonObject(); + for (final Map.Entry entry : map.entrySet()) { + final String name = String.valueOf(entry.getKey()); + final Object value = entry.getValue(); + jsonObject.add(name, wrapSnakeObject(value)); + } + return jsonObject; + } + + // otherwise take it as a string + return new JsonPrimitive(String.valueOf(o)); + } + + /** + * Submit the Ms policies. + * + * @param loopName the loop name + * @return the updated loop + * @throws IOException IO exception + * @throws Exceptions during the operation + */ + public Loop submitMsPolicies (String loopName) throws OperationException, IOException { + util.entering(request, "LoopOperation: delete microservice policies"); + Date startTime = new Date(); + Loop loop = loopService.getLoop(loopName); + + if (loop == null) { + String msg = "Submit MS policies exception: Not able to find closed loop:" + loopName; + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // verify the current closed loop state + if (loop.getLastComputedState() != LoopState.SUBMITTED && loop.getLastComputedState() != LoopState.DESIGN) { + String msg = "Submit MS policies exception: This closed loop is in state:" + loop.getLastComputedState() + + ". It could be deleted only when it is in SUBMITTED state."; + util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // Establish the api call to Policy to create the ms services + policyOp.createMsPolicy(loop.getMicroServicePolicies()); + + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + auditLogger.info("Deletion of MS policies completed"); + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + return loop; + } + + + /** + * Delete the Ms policies. + * + * @param loopName the loop name + * @return the updated loop + * @throws IOException IO exception + * @throws Exceptions during the operation + */ + public Loop deleteMsPolicies (Exchange camelExchange, String loopName) throws OperationException, IOException { + util.entering(request, "LoopOperation: delete microservice policies"); + Date startTime = new Date(); + Loop loop = loopService.getLoop(loopName); + + if (loop == null) { + String msg = "Delete MS policies exception: Not able to find closed loop:" + loopName; + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // verify the current closed loop state + if (loop.getLastComputedState() != LoopState.SUBMITTED) { + String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState() + + ". It could be deleted only when it is in SUBMITTED state."; + util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // Establish the api call to Policy to create the ms services + policyOp.deleteMsPolicy(loop.getMicroServicePolicies()); + + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + auditLogger.info("Deletion of MS policies completed"); + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + return loop; + } + + /** + * Delete the operational policy. + * + * @param loopName the loop name + * @return the updated loop + * @throws Exceptions during the operation + */ + public Loop deleteOpPolicy (Exchange camelExchange, String loopName) throws OperationException { + util.entering(request, "LoopOperation: delete guard policy"); + Date startTime = new Date(); + Loop loop = loopService.getLoop(loopName); + + if (loop == null) { + String msg = "Delete guard policy exception: Not able to find closed loop:" + loopName; + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // verify the current closed loop state + if (loop.getLastComputedState() != LoopState.SUBMITTED) { + String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState() + + ". It could be deleted only when it is in SUBMITTED state."; + util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // Establish the api call to Policy to delete operational policy + //client.deleteOpPolicy(); + + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + auditLogger.info("Deletion of Guard policy completed"); + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + return loop; + } + + /** + * Delete the Guard policy. + * + * @param loopName the loop name + * @return the updated loop + * @throws Exceptions during the operation + */ + public Loop deleteGuardPolicy (Exchange camelExchange, String loopName) throws OperationException { + util.entering(request, "LoopOperation: delete operational policy"); + Date startTime = new Date(); + Loop loop = loopService.getLoop(loopName); + + if (loop == null) { + String msg = "Delete operational policy exception: Not able to find closed loop:" + loopName; + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // verify the current closed loop state + if (loop.getLastComputedState() != LoopState.SUBMITTED) { + String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState() + + ". It could be deleted only when it is in SUBMITTED state."; + util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + throw new OperationException(msg); + } + + // Establish the api call to Policy to delete Guard policy + //client.deleteOpPolicy(); + + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + auditLogger.info("Deletion of operational policy completed"); + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + return loop; + } +} diff --git a/src/main/java/org/onap/clamp/operation/LoopOperation.java b/src/main/java/org/onap/clamp/operation/LoopOperation.java deleted file mode 100644 index bdb4b3f0..00000000 --- a/src/main/java/org/onap/clamp/operation/LoopOperation.java +++ /dev/null @@ -1,374 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2019 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.clamp.operation; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; - -import java.io.IOException; -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.Date; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.camel.Exchange; -import org.onap.clamp.clds.client.DcaeDispatcherServices; -import org.onap.clamp.clds.config.ClampProperties; -import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.clds.util.ONAPLogConstants; -import org.onap.clamp.exception.OperationException; -import org.onap.clamp.loop.Loop; -import org.onap.clamp.loop.LoopService; -import org.onap.clamp.loop.LoopState; -import org.onap.clamp.policy.PolicyOperation; -import org.onap.clamp.util.HttpConnectionManager; -import org.slf4j.event.Level; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; -import org.yaml.snakeyaml.Yaml; - -/** - * Closed loop operations - */ -@Component -public class LoopOperation { - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class); - protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); - private final DcaeDispatcherServices dcaeDispatcherServices; - private final LoopService loopService; - private LoggingUtils util = new LoggingUtils(logger); - private PolicyOperation policyOp; - - @Autowired - private HttpServletRequest request; - - @Autowired - public LoopOperation(LoopService loopService, DcaeDispatcherServices dcaeDispatcherServices, - ClampProperties refProp, HttpConnectionManager httpConnectionManager, PolicyOperation policyOp) { - this.loopService = loopService; - this.dcaeDispatcherServices = dcaeDispatcherServices; - this.policyOp = policyOp; - } - - /** - * Deploy the closed loop. - * - * @param loopName the loop name - * @return the updated loop - * @throws Exceptions during the operation - */ - public Loop deployLoop(Exchange camelExchange, String loopName) throws OperationException { - util.entering(request, "CldsService: Deploy model"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Deploy loop exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.SUBMITTED) { - String msg = "Deploy loop exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be deployed only when it is in SUBMITTED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // Set the deploymentId if not present yet - String deploymentId = ""; - // If model is already deployed then pass same deployment id - if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) { - deploymentId = loop.getDcaeDeploymentId(); - } else { - loop.setDcaeDeploymentId(deploymentId = "closedLoop_" + loopName + "_deploymentId"); - } - - Yaml yaml = new Yaml(); - Map yamlMap = yaml.load(loop.getBlueprint()); - JsonObject bluePrint = wrapSnakeObject(yamlMap).getAsJsonObject(); - - loop.setDcaeDeploymentStatusUrl(dcaeDispatcherServices.createNewDeployment(deploymentId, loop.getDcaeBlueprintId(), bluePrint)); - loop.setLastComputedState(LoopState.DEPLOYED); - // save the updated loop - loopService.saveOrUpdateLoop (loop); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Deploy model completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; - } - - /** - * Un deploy closed loop. - * - * @param loopName the loop name - * @return the updated loop - */ - public Loop unDeployLoop(String loopName) throws OperationException { - util.entering(request, "LoopOperation: Undeploy the closed loop"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Undeploy loop exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.DEPLOYED) { - String msg = "Unploy loop exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be undeployed only when it is in DEPLOYED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - loop.setDcaeDeploymentStatusUrl( - dcaeDispatcherServices.deleteExistingDeployment(loop.getDcaeDeploymentId(), loop.getDcaeBlueprintId())); - - // clean the deployment ID - loop.setDcaeDeploymentId(null); - loop.setLastComputedState(LoopState.SUBMITTED); - - // save the updated loop - loopService.saveOrUpdateLoop (loop); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Undeploy model completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; - } - - private JsonElement wrapSnakeObject(Object o) { - //NULL => JsonNull - if (o == null) - return JsonNull.INSTANCE; - - // Collection => JsonArray - if (o instanceof Collection) { - JsonArray array = new JsonArray(); - for (Object childObj : (Collection)o) - array.add(wrapSnakeObject(childObj)); - return array; - } - - // Array => JsonArray - if (o.getClass().isArray()) { - JsonArray array = new JsonArray(); - - int length = Array.getLength(array); - for (int i=0; i JsonObject - if (o instanceof Map) { - Map map = (Map)o; - - JsonObject jsonObject = new JsonObject(); - for (final Map.Entry entry : map.entrySet()) { - final String name = String.valueOf(entry.getKey()); - final Object value = entry.getValue(); - jsonObject.add(name, wrapSnakeObject(value)); - } - return jsonObject; - } - - // otherwise take it as a string - return new JsonPrimitive(String.valueOf(o)); - } - - /** - * Submit the Ms policies. - * - * @param loopName the loop name - * @return the updated loop - * @throws IOException IO exception - * @throws Exceptions during the operation - */ - public Loop submitMsPolicies (String loopName) throws OperationException, IOException { - util.entering(request, "LoopOperation: delete microservice policies"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Submit MS policies exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.SUBMITTED && loop.getLastComputedState() != LoopState.DESIGN) { - String msg = "Submit MS policies exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be deleted only when it is in SUBMITTED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // Establish the api call to Policy to create the ms services - policyOp.createMsPolicy(loop.getMicroServicePolicies()); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Deletion of MS policies completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; - } - - - /** - * Delete the Ms policies. - * - * @param loopName the loop name - * @return the updated loop - * @throws IOException IO exception - * @throws Exceptions during the operation - */ - public Loop deleteMsPolicies (Exchange camelExchange, String loopName) throws OperationException, IOException { - util.entering(request, "LoopOperation: delete microservice policies"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Delete MS policies exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.SUBMITTED) { - String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be deleted only when it is in SUBMITTED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // Establish the api call to Policy to create the ms services - policyOp.deleteMsPolicy(loop.getMicroServicePolicies()); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Deletion of MS policies completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; - } - - /** - * Delete the operational policy. - * - * @param loopName the loop name - * @return the updated loop - * @throws Exceptions during the operation - */ - public Loop deleteOpPolicy (Exchange camelExchange, String loopName) throws OperationException { - util.entering(request, "LoopOperation: delete guard policy"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Delete guard policy exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.SUBMITTED) { - String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be deleted only when it is in SUBMITTED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // Establish the api call to Policy to delete operational policy - //client.deleteOpPolicy(); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Deletion of Guard policy completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; - } - - /** - * Delete the Guard policy. - * - * @param loopName the loop name - * @return the updated loop - * @throws Exceptions during the operation - */ - public Loop deleteGuardPolicy (Exchange camelExchange, String loopName) throws OperationException { - util.entering(request, "LoopOperation: delete operational policy"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Delete operational policy exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.SUBMITTED) { - String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be deleted only when it is in SUBMITTED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // Establish the api call to Policy to delete Guard policy - //client.deleteOpPolicy(); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Deletion of operational policy completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; - } -} diff --git a/src/main/java/org/onap/clamp/policy/PolicyOperation.java b/src/main/java/org/onap/clamp/policy/PolicyOperation.java index 592338c4..edce8ff5 100644 --- a/src/main/java/org/onap/clamp/policy/PolicyOperation.java +++ b/src/main/java/org/onap/clamp/policy/PolicyOperation.java @@ -83,7 +83,7 @@ public class PolicyOperation { String url = refProp.getStringValue(POLICY_URL_PROPERTY_NAME) + policyType + POLICY_URL_SUFFIX; String userName = refProp.getStringValue(POLICY_USER_NAME); String encodedPass = refProp.getStringValue(POLICY_PASSWORD); - httpConnectionManager.doGeneralHttpQuery(url, "POST", payload.toString(), "application/json", "POLICY", userName, encodedPass); + httpConnectionManager.doHttpRequest(url, "POST", payload.toString(), "application/json", "POLICY", userName, encodedPass); } } @@ -93,7 +93,7 @@ public class PolicyOperation { String url = refProp.getStringValue(POLICY_URL_PROPERTY_NAME) + policyType + POLICY_URL_SUFFIX + "/" + msPolicy.getName(); String userName = refProp.getStringValue(POLICY_USER_NAME); String encodedPass = refProp.getStringValue(POLICY_PASSWORD); - httpConnectionManager.doGeneralHttpQuery(url, "POST", null, null, "POLICY", userName, encodedPass); + httpConnectionManager.doHttpRequest(url, "POST", null, null, "POLICY", userName, encodedPass); } } diff --git a/src/main/java/org/onap/clamp/util/HttpConnectionManager.java b/src/main/java/org/onap/clamp/util/HttpConnectionManager.java index 4e97f29b..6459fa97 100644 --- a/src/main/java/org/onap/clamp/util/HttpConnectionManager.java +++ b/src/main/java/org/onap/clamp/util/HttpConnectionManager.java @@ -27,22 +27,19 @@ package org.onap.clamp.util; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import sun.misc.BASE64Encoder; - import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; -import java.security.GeneralSecurityException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; import javax.net.ssl.HttpsURLConnection; import javax.ws.rs.BadRequestException; -import org.apache.commons.codec.DecoderException; import org.apache.commons.io.IOUtils; -import org.onap.clamp.clds.util.CryptoUtils; import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.stereotype.Component; @@ -55,14 +52,16 @@ public class HttpConnectionManager { protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); private static final String REQUEST_FAILED_LOG = "Request Failed - response payload="; - private String doHttpsQuery(URL url, String requestMethod, String payload, String contentType, String target, String userName, String password) throws IOException { + private String doHttpsQuery(URL url, String requestMethod, String payload, String contentType, String target, + String userName, String password) throws IOException { LoggingUtils utils = new LoggingUtils(logger); logger.info("Using HTTPS URL:" + url.toString()); HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection(); secureConnection = utils.invokeHttps(secureConnection, target, requestMethod); secureConnection.setRequestMethod(requestMethod); if (userName != null && password != null) { - secureConnection.setRequestProperty("Authorization", "Basic " + generateBasicAuth(userName, password)); + secureConnection.setRequestProperty("Authorization", "Basic " + + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8))); } if (payload != null && contentType != null) { secureConnection.setRequestProperty("Content-Type", contentType); @@ -91,14 +90,16 @@ public class HttpConnectionManager { } } - private String doHttpQuery(URL url, String requestMethod, String payload, String contentType, String target, String userName, String password) throws IOException { + private String doHttpQuery(URL url, String requestMethod, String payload, String contentType, String target, + String userName, String password) throws IOException { LoggingUtils utils = new LoggingUtils(logger); logger.info("Using HTTP URL:" + url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection = utils.invoke(connection, target, requestMethod); connection.setRequestMethod(requestMethod); if (userName != null && password != null) { - connection.setRequestProperty("Authorization", "Basic " + generateBasicAuth(userName, password)); + connection.setRequestProperty("Authorization", "Basic " + + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8))); } if (payload != null && contentType != null) { connection.setRequestProperty("Content-Type", contentType); @@ -144,8 +145,8 @@ public class HttpConnectionManager { * @throws IOException * In case of issue with the streams */ - public String doGeneralHttpQuery(String url, String requestMethod, String payload, String contentType, String target, String userName, String password) - throws IOException { + public String doHttpRequest(String url, String requestMethod, String payload, String contentType, String target, + String userName, String password) throws IOException { URL urlObj = new URL(url); if (url.contains("https://")) { // Support for HTTPS return doHttpsQuery(urlObj, requestMethod, payload, contentType, target, userName, password); @@ -153,18 +154,4 @@ public class HttpConnectionManager { return doHttpQuery(urlObj, requestMethod, payload, contentType, target, userName, password); } } - - private String generateBasicAuth(String userName, String encodedPassword) { - String password = ""; - try { - password = CryptoUtils.decrypt(encodedPassword); - } catch (GeneralSecurityException e) { - logger.error("Unable to decrypt the password", e); - } catch (DecoderException e) { - logger.error("Exception caught when decoding the HEX String Key for encryption", e); - } - BASE64Encoder enc = new sun.misc.BASE64Encoder(); - String userpassword = userName + ":" + password; - return enc.encode( userpassword.getBytes() ); - } } -- cgit 1.2.3-korg