diff options
Diffstat (limited to 'src')
26 files changed, 302 insertions, 148 deletions
diff --git a/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java index d8bd992e9..bc3d1b986 100644 --- a/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java @@ -28,6 +28,7 @@ import com.att.eelf.configuration.EELFManager; import com.fasterxml.jackson.databind.JsonNode; import java.security.GeneralSecurityException; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -35,7 +36,7 @@ import java.util.List; import org.apache.commons.codec.DecoderException; import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException; import org.onap.clamp.clds.util.CryptoUtils; -import org.openecomp.sdc.api.consumer.IConfiguration; +import org.onap.sdc.api.consumer.IConfiguration; /** * This class maps the SDC config JSON for one controller. @@ -65,6 +66,7 @@ public class SdcSingleControllerConfiguration implements IConfiguration { public static final String ACTIVATE_SERVER_TLS_AUTH = "activateServerTLSAuth"; public static final String KEY_STORE_KEY = "keyStorePassword"; public static final String KEY_STORE_PATH = "keyStorePath"; + public static final String MESSAGE_BUS_ADDRESSES = "messageBusAddresses"; private String errorMessageKeyNotFound; /** * Supported artifact types. @@ -127,8 +129,8 @@ public class SdcSingleControllerConfiguration implements IConfiguration { private String getEncryptedStringConfig(String key) throws GeneralSecurityException, DecoderException { if (jsonRootNode != null && jsonRootNode.get(key) != null) { - String config = CryptoUtils.decrypt(jsonRootNode.get(key).asText()); - return config.isEmpty() ? null : config; + return jsonRootNode.get(key).asText().isEmpty() ? null + : CryptoUtils.decrypt(jsonRootNode.get(key).asText()); } return null; } @@ -241,6 +243,9 @@ public class SdcSingleControllerConfiguration implements IConfiguration { if (this.getAsdcAddress() == null || this.getAsdcAddress().isEmpty()) { throw new SdcParametersException(SDC_ADDRESS_ATTRIBUTE_NAME + errorMessageKeyNotFound); } + if (this.getMsgBusAddress() == null || this.getMsgBusAddress().isEmpty()) { + throw new SdcParametersException(MESSAGE_BUS_ADDRESSES + errorMessageKeyNotFound); + } if (this.getPassword() == null || this.getPassword().isEmpty()) { throw new SdcParametersException(SDC_KEY_ATTRIBUTE_NAME + errorMessageKeyNotFound); } @@ -265,11 +270,17 @@ public class SdcSingleControllerConfiguration implements IConfiguration { */ @Override public boolean isFilterInEmptyResources() { - return true; + return false; } @Override public List<String> getMsgBusAddress() { - return null; + List<String> addressesList = new ArrayList<>(); + if (jsonRootNode != null && jsonRootNode.get(MESSAGE_BUS_ADDRESSES) != null) { + jsonRootNode.get(MESSAGE_BUS_ADDRESSES).forEach(k -> addressesList.add(k.asText())); + return addressesList; + } else { + return addressesList; + } } } diff --git a/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java index 09d4d6332..c191dbc85 100644 --- a/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java @@ -75,7 +75,7 @@ public class CldsSdcControllerConfiguration { try { e.closeSdc(); } catch (SdcControllerException e1) { - logger.error("Exception caught during initialization of sdc controller", e); + logger.error("Exception caught during initialization of sdc controller", e1); } }); } diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java b/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java index db5d271b0..ca4f97b1d 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java @@ -23,8 +23,8 @@ package org.onap.clamp.clds.sdc.controller; -import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; -import org.openecomp.sdc.utils.DistributionStatusEnum; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.utils.DistributionStatusEnum; public class DistributionStatusMessage implements IDistributionStatusMessage { diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java index c02edbbf9..627bc72ad 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java @@ -38,17 +38,17 @@ import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException; import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
import org.onap.clamp.clds.util.LoggingUtils;
-import org.openecomp.sdc.api.IDistributionClient;
-import org.openecomp.sdc.api.consumer.IDistributionStatusMessage;
-import org.openecomp.sdc.api.consumer.INotificationCallback;
-import org.openecomp.sdc.api.notification.IArtifactInfo;
-import org.openecomp.sdc.api.notification.INotificationData;
-import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
-import org.openecomp.sdc.api.results.IDistributionClientResult;
-import org.openecomp.sdc.impl.DistributionClientFactory;
-import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
-import org.openecomp.sdc.utils.DistributionActionResultEnum;
-import org.openecomp.sdc.utils.DistributionStatusEnum;
+import org.onap.sdc.api.IDistributionClient;
+import org.onap.sdc.api.consumer.IDistributionStatusMessage;
+import org.onap.sdc.api.consumer.INotificationCallback;
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.notification.INotificationData;
+import org.onap.sdc.api.results.IDistributionClientDownloadResult;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.impl.DistributionClientFactory;
+import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+import org.onap.sdc.utils.DistributionStatusEnum;
/**
* This class handles one sdc controller defined in the config.
@@ -204,8 +204,15 @@ public class SdcSingleController { this.changeControllerStatus(SdcSingleControllerStatus.BUSY);
csar = new CsarHandler(iNotif, this.sdcConfig.getSdcControllerName(),
refProp.getStringValue(CONFIG_SDC_FOLDER));
+ csar.save(downloadTheArtifact(csar.getArtifactElement()));
if (csarInstaller.isCsarAlreadyDeployed(csar)) {
- csar.save(downloadTheArtifact(csar.getArtifactElement()));
+ this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),
+ sdcConfig.getConsumerID(), iNotif.getDistributionID(),
+ DistributionStatusEnum.ALREADY_DOWNLOADED, null, System.currentTimeMillis());
+ this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),
+ sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.ALREADY_DEPLOYED,
+ null, System.currentTimeMillis());
+ } else {
this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),
sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DOWNLOAD_OK, null,
System.currentTimeMillis());
@@ -213,13 +220,6 @@ public class SdcSingleController { this.sendSdcNotification(NotificationType.DEPLOY, csar.getArtifactElement().getArtifactURL(),
sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.DEPLOY_OK, null,
System.currentTimeMillis());
- } else {
- this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),
- sdcConfig.getConsumerID(), iNotif.getDistributionID(),
- DistributionStatusEnum.ALREADY_DOWNLOADED, null, System.currentTimeMillis());
- this.sendSdcNotification(NotificationType.DOWNLOAD, csar.getArtifactElement().getArtifactURL(),
- sdcConfig.getConsumerID(), iNotif.getDistributionID(), DistributionStatusEnum.ALREADY_DEPLOYED,
- null, System.currentTimeMillis());
}
} catch (SdcArtifactInstallerException e) {
logger.error("SdcArtifactInstallerException exception caught during the notification processing", e);
diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java index 97ab05868..62169379c 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java @@ -27,9 +27,9 @@ import com.att.aft.dme2.internal.apache.commons.io.IOUtils; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -41,13 +41,13 @@ import java.util.zip.ZipFile; import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException; import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException; -import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; /** * CsarDescriptor that will be used to deploy file in CLAMP file system. Some @@ -97,9 +97,9 @@ public class CsarHandler { + artifactElement.getArtifactUUID() + ")"); Path path = Paths.get(csarFilePath); Files.createDirectories(path.getParent()); - Files.createFile(path); - try (FileOutputStream outFile = new FileOutputStream(csarFilePath)) { - outFile.write(resultArtifact.getArtifactPayload(), 0, resultArtifact.getArtifactPayload().length); + // Create or replace the file + try (OutputStream out = Files.newOutputStream(path)) { + out.write(resultArtifact.getArtifactPayload(), 0, resultArtifact.getArtifactPayload().length); } sdcCsarHelper = factory.getSdcCsarHelper(csarFilePath); this.loadDcaeBlueprint(); diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java index 4c6ed7fc7..91c0b6a64 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java @@ -43,6 +43,7 @@ import org.onap.clamp.clds.model.CldsModel; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.service.CldsService; import org.onap.clamp.clds.service.CldsTemplateService; +import org.springframework.transaction.annotation.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; @@ -58,6 +59,7 @@ public class CsarInstallerImpl implements CsarInstaller { private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>(); public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-ClosedLoopTemplate-"; public static final String MODEL_NAME_PREFIX = "ClosedLoop-"; + public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input"; /** * The file name that will be loaded by Spring. */ @@ -83,11 +85,12 @@ public class CsarInstallerImpl implements CsarInstaller { @Override public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException { - return (CldsModel.retrieve(cldsDao, csar.getSdcCsarHelper().getServiceMetadata().getValue("name"), - false) != null) ? true : false; + return (CldsModel.retrieve(cldsDao, csar.getSdcCsarHelper().getServiceMetadata().getValue("name"), true) + .getId() != null) ? true : false; } @Override + @Transactional public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException { try { String serviceTypeId = queryDcaeToGetServiceTypeId(csar); @@ -132,9 +135,9 @@ public class CsarInstallerImpl implements CsarInstaller { policyNameList.add(filteredPolicyName); } else { String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef - .getValue()).get("properties")).get("policy_id")).get("get_input"); + .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM); if (inputPolicyName != null) { - policyNameList.add("get_input"); + policyNameList.add(GET_INPUT_BLUEPRINT_PARAM); } } }); @@ -184,7 +187,8 @@ public class CsarInstallerImpl implements CsarInstaller { cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\"" + csar.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\"" + csar.getBlueprintInvariantResourceUuid() - + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]}]}"); + + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},{\"name\":\"deployParameters\",\"value\":{\n" + + " \"policy_id\": \"" + "test" + "\"" + " }}]}"); cldsModel.setBpmnText(cldsTemplate.getBpmnText()); cldsModel.setTypeId(serviceTypeId); cldsModel.save(cldsDao, null); diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index 2b6862dc5..cfea2535e 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -32,7 +32,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; -import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; @@ -121,6 +120,7 @@ public class CldsService extends SecureServiceBase { private SecureServicePermission permissionUpdateCl; private SecureServicePermission permissionReadTemplate; private SecureServicePermission permissionUpdateTemplate; + private static final long DCAE_DEPLOY_WAITING_TIME = TimeUnit.SECONDS.toNanos(30); @PostConstruct private final void afterConstruction() { @@ -161,8 +161,7 @@ public class CldsService extends SecureServiceBase { public List<CldsMonitoringDetails> getCLDSDetails() { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: GET model details", getPrincipalName()); - List<CldsMonitoringDetails> cldsMonitoringDetailsList = new ArrayList<CldsMonitoringDetails>(); - cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails(); + List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get cldsDetails success", this.getClass().getName()); @@ -831,12 +830,14 @@ public class CldsService extends SecureServiceBase { String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId, model.getTypeId(), modelProp.getGlobal().getDeployParameters()); String operationStatus = "processing"; - long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10); + long waitingTime = System.nanoTime() + DCAE_DEPLOY_WAITING_TIME; while ("processing".equalsIgnoreCase(operationStatus)) { - // Break the loop if waiting for more than 10 mins if (waitingTime < System.nanoTime()) { + logger.info("Waiting is over for DCAE deployment"); break; } + logger.info("Waiting 5s before sending query to DCAE"); + Thread.sleep(5000); operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl); } if ("succeeded".equalsIgnoreCase(operationStatus)) { diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index 7a9ee70e5..f26d74670 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -23,10 +23,6 @@ package org.onap.clamp.clds.service; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; - -import java.io.IOException; import java.util.Date; import java.util.List; @@ -147,9 +143,8 @@ public class CldsTemplateService extends SecureServiceBase { * REST service that saves a CLDS template by name in the database. * * @param templateName - * @throws IOException - * @throws JsonMappingException - * @throws JsonParseException + * @param cldsTemplate + * @return The CldsTemplate modified and saved in DB */ @PUT @Path("/template/{templateName}") diff --git a/src/main/resources/clds/sdc-controllers-config.json b/src/main/resources/clds/sdc-controllers-config.json index df73a504f..d18a161a5 100644 --- a/src/main/resources/clds/sdc-controllers-config.json +++ b/src/main/resources/clds/sdc-controllers-config.json @@ -1,26 +1,18 @@ { "sdc-connections":{ - "sdc-controller1":{ - "user": "User1", + "sdc-controller":{ + "user": "clamp", "consumerGroup": "consumerGroup1", "consumerId": "consumerId1", - "environmentName": "environmentName1", - "sdcAddress": "hostname1", - "password": "bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", - "pollingInterval":10, - "pollingTimeout":30 - - }, - "sdc-controller2":{ - "user": "User2", - "consumerGroup": "consumerGroup2", - "consumerId": "consumerId2", - "environmentName": "environmentName2", - "sdcAddress": "hostname2", - "password": "bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", - "pollingInterval":10, - "pollingTimeout":30 - + "environmentName": "AUTO", + "sdcAddress": "sdc.api.simpledemo.onap.org:8443", + "password": "b7acccda32b98c5bb7acccda32b98c5b05D511BD6D93626E90D18E9D24D9B78CD34C7EE8012F0A189A28763E82271E50A5D4EC10C7D93E06E0A2D27CAE66B981", + "pollingInterval":30, + "pollingTimeout":30, + "activateServerTLSAuth":"false", + "keyStorePassword":"", + "keyStorePath":"", + "messageBusAddresses":["ueb.api.simpledemo.onap.org"] } } } diff --git a/src/main/resources/clds/templates/ui-alarm-default.json b/src/main/resources/clds/templates/ui-alarm-default.json index 0d0835981..c851e6cdd 100644 --- a/src/main/resources/clds/templates/ui-alarm-default.json +++ b/src/main/resources/clds/templates/ui-alarm-default.json @@ -267,7 +267,7 @@ "jnxSpaceSNAProcessUp": "vDBE-EMS-Juniper: jnxSpaceSNAProcessUp", "jnxSpaceNodeDown": "vDBE-EMS-Juniper: jnxSpaceNodeDown", "jnxSpaceNodeUp": "vDBE-EMS-Juniper: jnxSpaceNodeUp", - " jnxSpaceNodeRemoval": "vDBE-EMS-Juniper: jnxSpaceNodeRemoval", + "jnxSpaceNodeRemoval": "vDBE-EMS-Juniper: jnxSpaceNodeRemoval", "jnxCmCfgChange": "vDBE-Juniper: jnxCmCfgChange", "jnxCmRescueChange": "vDBE-Juniper: jnxCmRescueChange", "jnxEventTrap": "vDBE-Juniper: jnxEventTrap", diff --git a/src/test/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfigurationTest.java b/src/test/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfigurationTest.java index ecef30ee4..00d5dffbb 100644 --- a/src/test/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfigurationTest.java +++ b/src/test/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfigurationTest.java @@ -20,7 +20,9 @@ package org.onap.clamp.clds.config.sdc; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -58,13 +60,16 @@ public class SdcSingleControllerConfigurationTest { assertEquals("consumerGroup", sdcConfig.getConsumerGroup()); assertEquals("consumerId", sdcConfig.getConsumerID()); assertEquals("environmentName", sdcConfig.getEnvironmentName()); - assertEquals("hostname", sdcConfig.getAsdcAddress()); + assertEquals("hostname:8080", sdcConfig.getAsdcAddress()); assertEquals(10, sdcConfig.getPollingInterval()); assertEquals(30, sdcConfig.getPollingTimeout()); assertEquals(SdcSingleControllerConfiguration.SUPPORTED_ARTIFACT_TYPES_LIST.size(), sdcConfig.getRelevantArtifactTypes().size()); assertTrue(sdcConfig.activateServerTLSAuth()); assertEquals("ThePassword", sdcConfig.getKeyStorePassword()); + assertArrayEquals(new String[] { + "localhost" + }, sdcConfig.getMsgBusAddress().toArray()); } @Test(expected = SdcParametersException.class) @@ -78,6 +83,15 @@ public class SdcSingleControllerConfigurationTest { } @Test + public final void testAllRequiredParametersEmptyEncrypted() + throws JsonParseException, JsonMappingException, IOException { + SdcSingleControllerConfiguration sdcConfig = loadControllerConfiguration( + "clds/sdc-controller-config-empty-encrypted.json", "sdc-controller1"); + sdcConfig.testAllRequiredParameters(); + assertNull(sdcConfig.getKeyStorePassword()); + } + + @Test public final void testConsumerGroupWithNull() throws JsonParseException, JsonMappingException, IOException { SdcSingleControllerConfiguration sdcConfig = loadControllerConfiguration("clds/sdc-controller-config-NULL.json", "sdc-controller1"); diff --git a/src/test/java/org/onap/clamp/clds/it/CldsDaoItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsDaoItCase.java index ba37b57f8..788a7ff7c 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsDaoItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsDaoItCase.java @@ -44,10 +44,10 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.onap.clamp.clds.client.req.sdc.SdcCatalogServices; import org.onap.clamp.clds.dao.CldsDao; -import org.onap.clamp.clds.model.CldsMonitoringDetails; import org.onap.clamp.clds.model.CldsDbServiceCache; import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.CldsModel; +import org.onap.clamp.clds.model.CldsMonitoringDetails; import org.onap.clamp.clds.model.CldsServiceData; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.util.ResourceFileUtil; diff --git a/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java b/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java index fc5cb040f..c0300eff6 100644 --- a/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java @@ -24,6 +24,7 @@ package org.onap.clamp.clds.it.sdc.controller.installer; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -45,9 +46,9 @@ import org.onap.clamp.clds.sdc.controller.installer.CsarHandler; import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl; import org.onap.clamp.clds.util.ResourceFileUtil; -import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; -import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException; -import org.openecomp.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.sdc.toscaparser.api.elements.Metadata; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @@ -58,7 +59,7 @@ public class CsarInstallerItCase { private static final String CSAR_ARTIFACT_NAME = "testArtifact.csar"; private static final String INVARIANT_SERVICE_UUID = "4cc5b45a-1f63-4194-8100-cd8e14248c92"; - private static final String INVARIANT_RESOURCE1_UUID = "ba4d4b5d-f861-4155-886b-b1cdba5e0957"; + private static final String INVARIANT_RESOURCE1_UUID = "07e266fc-49ab-4cd7-8378-ca4676f1b9ec"; @Autowired private CsarInstaller csarInstaller; @Autowired @@ -94,6 +95,7 @@ public class CsarInstallerItCase { throws SdcArtifactInstallerException, SdcToscaParserException, CsarHandlerException, IOException { String generatedName = RandomStringUtils.randomAlphanumeric(5); CsarHandler csarHandler = buildFakeCsarHandler(generatedName); + assertFalse(csarInstaller.isCsarAlreadyDeployed(csarHandler)); csarInstaller.installTheCsar(csarHandler); assertTrue(csarInstaller.isCsarAlreadyDeployed(csarHandler)); } @@ -104,22 +106,22 @@ public class CsarInstallerItCase { String generatedName = RandomStringUtils.randomAlphanumeric(5); csarInstaller.installTheCsar(buildFakeCsarHandler(generatedName)); // Get the template back from DB - CldsTemplate templateFromDB = CldsTemplate.retrieve(cldsDao, + CldsTemplate templateFromDb = CldsTemplate.retrieve(cldsDao, CsarInstallerImpl.TEMPLATE_NAME_PREFIX + generatedName, false); - assertNotNull(templateFromDB); - assertNotNull(templateFromDB.getBpmnText()); - assertNotNull(templateFromDB.getImageText()); - assertNotNull(templateFromDB.getPropText()); - assertTrue(templateFromDB.getPropText().contains("global") - && templateFromDB.getPropText().contains("node_templates:")); - assertEquals(templateFromDB.getName(), CsarInstallerImpl.TEMPLATE_NAME_PREFIX + generatedName); + assertNotNull(templateFromDb); + assertNotNull(templateFromDb.getBpmnText()); + assertNotNull(templateFromDb.getImageText()); + assertNotNull(templateFromDb.getPropText()); + assertTrue(templateFromDb.getPropText().contains("global") + && templateFromDb.getPropText().contains("node_templates:")); + assertEquals(templateFromDb.getName(), CsarInstallerImpl.TEMPLATE_NAME_PREFIX + generatedName); // Get the Model back from DB - CldsModel modelFromDB = CldsModel.retrieve(cldsDao, generatedName, true); - assertNotNull(modelFromDB); - assertNotNull(modelFromDB.getBpmnText()); - assertNotNull(modelFromDB.getImageText()); - assertNotNull(modelFromDB.getPropText()); - assertEquals(modelFromDB.getName(), generatedName); - assertEquals(CsarInstallerImpl.MODEL_NAME_PREFIX, modelFromDB.getControlNamePrefix()); + CldsModel modelFromDb = CldsModel.retrieve(cldsDao, generatedName, true); + assertNotNull(modelFromDb); + assertNotNull(modelFromDb.getBpmnText()); + assertNotNull(modelFromDb.getImageText()); + assertNotNull(modelFromDb.getPropText()); + assertEquals(modelFromDb.getName(), generatedName); + assertEquals(CsarInstallerImpl.MODEL_NAME_PREFIX, modelFromDb.getControlNamePrefix()); } } diff --git a/src/test/java/org/onap/clamp/clds/model/CldsDbServiceCacheTest.java b/src/test/java/org/onap/clamp/clds/model/CldsDbServiceCacheTest.java index 447e25531..033c67d42 100644 --- a/src/test/java/org/onap/clamp/clds/model/CldsDbServiceCacheTest.java +++ b/src/test/java/org/onap/clamp/clds/model/CldsDbServiceCacheTest.java @@ -41,15 +41,15 @@ public class CldsDbServiceCacheTest { cldsServiceData.setServiceUUID("testUUID"); cldsServiceData.setAgeOfRecord(Long.valueOf(100)); cldsServiceData.setServiceInvariantUUID("testInvariantUUID"); - List<CldsVfData> cldsVfs = new ArrayList<>(); CldsVfData cldsVfData = new CldsVfData(); cldsVfData.setVfName("vf"); - List<CldsVfKPIData> cldsKPIList = new ArrayList<>(); - CldsVfKPIData cldsVfKPIData = new CldsVfKPIData(); - cldsVfKPIData.setFieldPath("fieldPath"); - cldsVfKPIData.setFieldPathValue("fieldValue"); - cldsKPIList.add(cldsVfKPIData); - cldsVfData.setCldsKPIList(cldsKPIList); + CldsVfKPIData cldsVfKpiData = new CldsVfKPIData(); + cldsVfKpiData.setFieldPath("fieldPath"); + cldsVfKpiData.setFieldPathValue("fieldValue"); + List<CldsVfKPIData> cldsKpiList = new ArrayList<>(); + cldsKpiList.add(cldsVfKpiData); + cldsVfData.setCldsKPIList(cldsKpiList); + List<CldsVfData> cldsVfs = new ArrayList<>(); cldsVfs.add(cldsVfData); cldsServiceData.setCldsVfs(cldsVfs); CldsDbServiceCache cldsDbServiceCache = new CldsDbServiceCache(cldsServiceData); diff --git a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java index c842068d9..3a37f9457 100644 --- a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java +++ b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java @@ -43,11 +43,11 @@ import org.mockito.Mockito; import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException; import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException; import org.onap.clamp.clds.util.ResourceFileUtil; -import org.openecomp.sdc.api.notification.IArtifactInfo; -import org.openecomp.sdc.api.notification.INotificationData; -import org.openecomp.sdc.api.notification.IResourceInstance; -import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; -import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.notification.IResourceInstance; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; public class CsarHandlerTest { @@ -90,8 +90,6 @@ public class CsarHandlerTest { // Build what is needed for UUID Mockito.when(notifData.getServiceInvariantUUID()).thenReturn(SERVICE_UUID); // Build fake resource with one artifact BLUEPRINT - List<IResourceInstance> resourcesList = new ArrayList<>(); - List<IArtifactInfo> artifactsListForResource = new ArrayList<>(); IResourceInstance resource1 = Mockito.mock(IResourceInstance.class); Mockito.when(resource1.getResourceType()).thenReturn("VF"); Mockito.when(resource1.getResourceInvariantUUID()).thenReturn(RESOURCE1_UUID); @@ -99,8 +97,10 @@ public class CsarHandlerTest { IArtifactInfo blueprintArtifact = Mockito.mock(IArtifactInfo.class); Mockito.when(blueprintArtifact.getArtifactType()).thenReturn(CsarHandler.BLUEPRINT_TYPE); Mockito.when(blueprintArtifact.getArtifactName()).thenReturn(BLUEPRINT1_NAME); + List<IArtifactInfo> artifactsListForResource = new ArrayList<>(); artifactsListForResource.add(blueprintArtifact); Mockito.when(resource1.getArtifacts()).thenReturn(artifactsListForResource); + List<IResourceInstance> resourcesList = new ArrayList<>(); resourcesList.add(resource1); Mockito.when(notifData.getResources()).thenReturn(resourcesList); return notifData; @@ -135,4 +135,29 @@ public class CsarHandlerTest { Path path = Paths.get(SDC_FOLDER + "/test-controller/" + CSAR_ARTIFACT_NAME); Files.deleteIfExists(path); } + + @Test + public void testDoubleSave() + throws SdcArtifactInstallerException, SdcToscaParserException, CsarHandlerException, IOException { + CsarHandler csar = new CsarHandler(buildFakeSdcNotification(), "test-controller", "/tmp/csar-handler-tests"); + // Test the save + csar.save(buildFakeSdcResut()); + assertTrue((new File(SDC_FOLDER + "/test-controller/" + CSAR_ARTIFACT_NAME)).exists()); + assertEquals(CSAR_ARTIFACT_NAME, csar.getArtifactElement().getArtifactName()); + assertNotNull(csar.getSdcCsarHelper()); + // Test dcaeBlueprint + String blueprint = csar.getDcaeBlueprint(); + assertNotNull(blueprint); + assertTrue(!blueprint.isEmpty()); + assertTrue(blueprint.contains("DCAE-VES-PM-EVENT-v1")); + // Test additional properties from Sdc notif + assertEquals(BLUEPRINT1_NAME, csar.getBlueprintArtifactName()); + assertEquals(RESOURCE1_UUID, csar.getBlueprintInvariantResourceUuid()); + assertEquals(SERVICE_UUID, csar.getBlueprintInvariantServiceUuid()); + Path path = Paths.get(SDC_FOLDER + "/test-controller/" + CSAR_ARTIFACT_NAME); + // A double save should simply overwrite the existing + csar.save(buildFakeSdcResut()); + // Do some cleanup + Files.deleteIfExists(path); + } } diff --git a/src/test/resources/clds/sdc-controller-config-NULL.json b/src/test/resources/clds/sdc-controller-config-NULL.json index 5c8ec0cfe..bf310c706 100644 --- a/src/test/resources/clds/sdc-controller-config-NULL.json +++ b/src/test/resources/clds/sdc-controller-config-NULL.json @@ -3,8 +3,9 @@ "consumerGroup": "NULL", "consumerId": "consumerId", "environmentName": "environmentName", - "sdcAddress": "hostname", + "sdcAddress": "hostname:8080", "password": "bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", "pollingInterval":10, - "pollingTimeout":30 + "pollingTimeout":30, + "messageBusAddresses":["localhost"] } diff --git a/src/test/resources/clds/sdc-controller-config-TLS.json b/src/test/resources/clds/sdc-controller-config-TLS.json index d7642e6b1..99366b765 100644 --- a/src/test/resources/clds/sdc-controller-config-TLS.json +++ b/src/test/resources/clds/sdc-controller-config-TLS.json @@ -3,11 +3,12 @@ "consumerGroup": "consumerGroup", "consumerId": "consumerId", "environmentName": "environmentName", - "sdcAddress": "hostname", + "sdcAddress": "hostname:8080", "password": "bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", "pollingInterval":10, "pollingTimeout":30, "activateServerTLSAuth": true, - "keyStorePassword":"bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", - "keyStorePath": "/test" + "keyStorePassword":"bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", + "keyStorePath": "/test", + "messageBusAddresses":["localhost"] } diff --git a/src/test/resources/clds/sdc-controller-config-bad.json b/src/test/resources/clds/sdc-controller-config-bad.json index d99ed5801..194ff5f4b 100644 --- a/src/test/resources/clds/sdc-controller-config-bad.json +++ b/src/test/resources/clds/sdc-controller-config-bad.json @@ -5,7 +5,7 @@ "consumerGroup": "consumerGroup", "consumerId": "consumerId", "environmentName": "environmentName", - "sdcAddress": "hostname1", + "sdcAddress": "hostname1:8080", "pollingInterval": 10, "pollingTimeout": 30 } diff --git a/src/test/resources/clds/sdc-controller-config-empty-encrypted.json b/src/test/resources/clds/sdc-controller-config-empty-encrypted.json new file mode 100644 index 000000000..2a70b9edc --- /dev/null +++ b/src/test/resources/clds/sdc-controller-config-empty-encrypted.json @@ -0,0 +1,14 @@ +{ + "user": "User", + "consumerGroup": "consumerGroup", + "consumerId": "consumerId", + "environmentName": "environmentName", + "sdcAddress": "hostname:8080", + "password": "bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", + "pollingInterval":10, + "pollingTimeout":30, + "activateServerTLSAuth": true, + "keyStorePassword":"", + "keyStorePath": "/test", + "messageBusAddresses":["localhost"] +} diff --git a/src/test/resources/clds/sdc-controllers-config.json b/src/test/resources/clds/sdc-controllers-config.json index df73a504f..ce56fef27 100644 --- a/src/test/resources/clds/sdc-controllers-config.json +++ b/src/test/resources/clds/sdc-controllers-config.json @@ -5,21 +5,22 @@ "consumerGroup": "consumerGroup1", "consumerId": "consumerId1", "environmentName": "environmentName1", - "sdcAddress": "hostname1", + "sdcAddress": "localhost:${docker.http-cache.port.host}", "password": "bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", "pollingInterval":10, - "pollingTimeout":30 - + "pollingTimeout":30, + "messageBusAddresses":["localhost"] }, "sdc-controller2":{ "user": "User2", "consumerGroup": "consumerGroup2", "consumerId": "consumerId2", "environmentName": "environmentName2", - "sdcAddress": "hostname2", + "sdcAddress": "localhost:${docker.http-cache.port.host}", "password": "bb3871669d893c7fb8aaacda31b77b4f537E67A081C2726889548ED7BC4C2DE6", "pollingInterval":10, - "pollingTimeout":30 + "pollingTimeout":30, + "messageBusAddresses":["localhost"] } } diff --git a/src/test/resources/clds/templates/ui-alarm-default.json b/src/test/resources/clds/templates/ui-alarm-default.json index 0d0835981..c851e6cdd 100644 --- a/src/test/resources/clds/templates/ui-alarm-default.json +++ b/src/test/resources/clds/templates/ui-alarm-default.json @@ -267,7 +267,7 @@ "jnxSpaceSNAProcessUp": "vDBE-EMS-Juniper: jnxSpaceSNAProcessUp", "jnxSpaceNodeDown": "vDBE-EMS-Juniper: jnxSpaceNodeDown", "jnxSpaceNodeUp": "vDBE-EMS-Juniper: jnxSpaceNodeUp", - " jnxSpaceNodeRemoval": "vDBE-EMS-Juniper: jnxSpaceNodeRemoval", + "jnxSpaceNodeRemoval": "vDBE-EMS-Juniper: jnxSpaceNodeRemoval", "jnxCmCfgChange": "vDBE-Juniper: jnxCmCfgChange", "jnxCmRescueChange": "vDBE-Juniper: jnxCmRescueChange", "jnxEventTrap": "vDBE-Juniper: jnxEventTrap", diff --git a/src/test/resources/example/sdc/service-Simsfoimap0112.csar b/src/test/resources/example/sdc/service-Simsfoimap0112.csar Binary files differindex 160c8f2cc..fac487cec 100644 --- a/src/test/resources/example/sdc/service-Simsfoimap0112.csar +++ b/src/test/resources/example/sdc/service-Simsfoimap0112.csar diff --git a/src/test/resources/http-cache/example/pdp/api/deletePolicy/.file b/src/test/resources/http-cache/example/pdp/api/deletePolicy/.file new file mode 100644 index 000000000..0637a088a --- /dev/null +++ b/src/test/resources/http-cache/example/pdp/api/deletePolicy/.file @@ -0,0 +1 @@ +[]
\ No newline at end of file diff --git a/src/test/resources/http-cache/example/pdp/api/deletePolicy/.header b/src/test/resources/http-cache/example/pdp/api/deletePolicy/.header new file mode 100644 index 000000000..6a280d972 --- /dev/null +++ b/src/test/resources/http-cache/example/pdp/api/deletePolicy/.header @@ -0,0 +1 @@ +{"Transfer-Encoding": "chunked", "Set-Cookie": "JSESSIONID=158qxkdtdobkd1umr3ikkgrmlx;Path=/", "Expires": "Thu, 01 Jan 1970 00:00:00 GMT", "Server": "Jetty(9.3.21.v20170918)", "Content-Type": "application/json", "X-ECOMP-RequestID": "e2ddb3c8-994f-47df-b4dc-097d4fb55c08"}
\ No newline at end of file diff --git a/src/test/resources/http-cache/start_http_cache.sh b/src/test/resources/http-cache/start_http_cache.sh index fe9e9911f..fb4975e54 100755 --- a/src/test/resources/http-cache/start_http_cache.sh +++ b/src/test/resources/http-cache/start_http_cache.sh @@ -22,16 +22,31 @@ # ECOMP is a trademark and service mark of AT&T Intellectual Property. ### -if [ $# -eq 1 ] - then - echo 'input parameter is set (proxy http)'; - export http_proxy=$1 - export https_proxy=$1 - else - echo 'input parameter is not set (proxy http)'; -fi +echo "Starting HTTP CACHE python script" +for i in "$@" +do +case $i in + --python_proxyaddress=*) + python_proxyaddress="--proxyaddress ${i#*=}" + echo "- Using python_proxyaddress and set it to: $python_proxyaddress" + shift # past argument=value + ;; + --http_proxyaddress=*) + export http_proxy="${i#*=}" + export https_proxy="${i#*=}" + echo "- Defining http_proxy/https_proxy env variables to: $http_proxy" + shift # past argument=value + ;; + -?|--help|-help) + echo "Usage: $(basename $0) [--http_proxyaddress=<http://proxy_address:port>] [--python_proxyaddress=<python_simulator_address:port>]" + echo "--http_proxyaddress Set the http_proxy/https_proxy in the script before running python" + echo "--python_proxyaddress <python_simulator_address:port>, like localhost:8080 and will be set as --proxyaddress, this is the adress returned by DCAE simulator response" + exit 2 + ;; +esac +done echo 'Installing requests packages for Python' pip install requests echo 'Executing the Http proxy in Cache mode only' -python third_party_proxy.py --port 8080 --root /usr/src/http-cache-app/data-cache +python third_party_proxy.py --port 8080 --root /usr/src/http-cache-app/data-cache $python_proxyaddress diff --git a/src/test/resources/http-cache/third_party_proxy.py b/src/test/resources/http-cache/third_party_proxy.py index 72ea49587..29d34cc89 100755 --- a/src/test/resources/http-cache/third_party_proxy.py +++ b/src/test/resources/http-cache/third_party_proxy.py @@ -41,6 +41,7 @@ parser.add_argument("--root", "-r", default=tempfile.mkdtemp, type=str, help parser.add_argument("--proxy" , type=str, help="Url of the Act as a proxy. If not set, this script only uses the cache and will return a 404 if files aren't found") parser.add_argument("--port", "-P", type=int, default="8081", help="Port on which the proxy should listen to") parser.add_argument("--verbose", "-v", type=bool, help="Print more information in case of error") +parser.add_argument("--proxyaddress","-a", type=str, help="Address of this proxy, generally either third_party_proxy:8085 or localhost:8085 depending if started with docker-compose or not") options = parser.parse_args() @@ -49,6 +50,7 @@ HOST = options.proxy AUTH = (options.username, options.password) HEADERS = {'X-ECOMP-InstanceID':'CLAMP'} CACHE_ROOT = options.root +PROXY_ADDRESS=options.proxyaddress def signal_handler(signal_sent, frame): global httpd @@ -116,7 +118,17 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): os.makedirs(cached_file, True) with open(cached_file_header, 'w') as f: - f.write("{\"Content-Length\": \"144\", \"Content-Type\": \"application/json\"}") + f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") + with open(cached_file_content, 'w') as f: + f.write(jsonGenerated) + elif self.path.startswith("/dcae-operationstatus"): + print "self.path start with /dcae-operationstatus, generating response json..." + jsonGenerated = "{\"operationType\": \"operationType1\", \"status\": \"succeeded\"}" + print "jsonGenerated: " + jsonGenerated + + os.makedirs(cached_file, True) + with open(cached_file_header, 'w') as f: + f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") with open(cached_file_content, 'w') as f: f.write(jsonGenerated) else: @@ -215,27 +227,91 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): cached_file_header = "%s/.header" % (cached_file,) _file_available = os.path.exists(cached_file_content) - if not _file_available and not HOST: - print("No file corresponding in cache and no HOST specified: %s" % HOST) - self.send_response(404) - return "404 Not found" if not _file_available: - print("Request for data currently not present in cache: %s" % (cached_file,)) + if self.path.startswith("/dcae-deployments/"): + print "self.path start with /dcae-deployments/, generating response json..." + #jsondata = json.loads(self.data_string) + jsonGenerated = "{\"links\":{\"status\":\"http:\/\/" + PROXY_ADDRESS + "\/dcae-operationstatus\",\"test2\":\"test2\"}}" + print "jsonGenerated: " + jsonGenerated + + os.makedirs(cached_file, True) + with open(cached_file_header, 'w') as f: + f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") + with open(cached_file_content, 'w') as f: + f.write(jsonGenerated) + else: + if not HOST: + self.send_response(404) + return "404 Not found" + + print("Request for data currently not present in cache: %s" % (cached_file,)) + + url = '%s%s' % (HOST, self.path) + print("url: %s" % (url,)) + response = requests.put(url, data=self.data_string, headers=self.headers, stream=True) + + if response.status_code == 200: + self._write_cache(cached_file, cached_file_header, cached_file_content, response) + else: + print('Error when requesting file :') + print('Requested url : %s' % (url,)) + print('Status code : %s' % (response.status_code,)) + print('Content : %s' % (response.content,)) + self.send_response(response.status_code) + return response.content + else: + print("Request for data present in cache: %s" % (cached_file,)) + + self._send_content(cached_file_header, cached_file_content) - url = '%s%s' % (HOST, self.path) - print("url: %s" % (url,)) - response = requests.put(url, data=self.data_string, headers=self.headers, stream=True) - if response.status_code == 200: - self._write_cache(cached_file, cached_file_header, cached_file_content, response) + def do_DELETE(self): + print("\n\n\nGot a DELETE for %s " % self.path) + self.check_credentials() + print("self.headers:\n %s" % self.headers) + + cached_file = '%s/%s' % (CACHE_ROOT, self.path,) + print("Cached file name before escaping : %s" % cached_file) + cached_file = cached_file.replace('<','<').replace('>','>').replace('?','?').replace('*','*').replace('\\','*').replace(':',':').replace('|','|') + print("Cached file name after escaping (used for cache storage) : %s" % cached_file) + cached_file_content = "%s/.file" % (cached_file,) + cached_file_header = "%s/.header" % (cached_file,) + + _file_available = os.path.exists(cached_file_content) + + if not _file_available: + if self.path.startswith("/dcae-deployments/"): + print "self.path start with /dcae-deployments/, generating response json..." + #jsondata = json.loads(self.data_string) + jsonGenerated = "{\"links\":{\"status\":\"http:\/\/" + PROXY_ADDRESS + "\/dcae-operationstatus\",\"test2\":\"test2\"}}" + print "jsonGenerated: " + jsonGenerated + + os.makedirs(cached_file, True) + with open(cached_file_header, 'w') as f: + f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") + with open(cached_file_content, 'w') as f: + f.write(jsonGenerated) else: - print('Error when requesting file :') - print('Requested url : %s' % (url,)) - print('Status code : %s' % (response.status_code,)) - print('Content : %s' % (response.content,)) - self.send_response(response.status_code) - return response.content + if not HOST: + self.send_response(404) + return "404 Not found" + + print("Request for data currently not present in cache: %s" % (cached_file,)) + + url = '%s%s' % (HOST, self.path) + print("url: %s" % (url,)) + response = requests.put(url, data=self.data_string, headers=self.headers, stream=True) + + if response.status_code == 200: + self._write_cache(cached_file, cached_file_header, cached_file_content, response) + else: + print('Error when requesting file :') + print('Requested url : %s' % (url,)) + print('Status code : %s' % (response.status_code,)) + print('Content : %s' % (response.content,)) + self.send_response(response.status_code) + return response.content else: print("Request for data present in cache: %s" % (cached_file,)) |