summaryrefslogtreecommitdiffstats
path: root/src/test
diff options
context:
space:
mode:
authorsebdet <sebastien.determe@intl.att.com>2018-12-01 15:09:54 +0100
committersebdet <sebastien.determe@intl.att.com>2018-12-05 13:18:19 +0100
commitd72d0d05d74f4125e8f36beea096aa7769d19eab (patch)
tree18e76a08b52de40a77288a14f20448efede92d7d /src/test
parentd1779040e9f6aeaff20a8c0f4da64f4ac7774ae0 (diff)
Additional code for Tosca
Tosca code for policy dynamic configuration Issue-ID: CLAMP-252,CLAMP-251 Change-Id: Icd96f833567050c1dd4730a61765507ad24ebd2e Signed-off-by: sebdet <sebastien.determe@intl.att.com>
Diffstat (limited to 'src/test')
-rw-r--r--src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java10
-rw-r--r--src/test/java/org/onap/clamp/clds/it/CldsDictionaryServiceItCase.java161
-rw-r--r--src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java12
-rw-r--r--src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java141
-rw-r--r--src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java17
-rw-r--r--src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java54
-rw-r--r--src/test/java/org/onap/clamp/clds/util/JacksonUtilsTest.java33
-rw-r--r--src/test/resources/clds/camel/routes/flexible-flow.xml50
-rw-r--r--src/test/resources/example/json-editor-schema/tca-policy-json-editor-schema.json115
-rwxr-xr-xsrc/test/resources/http-cache/start_http_cache.sh2
-rwxr-xr-xsrc/test/resources/http-cache/third_party_proxy.py393
-rw-r--r--src/test/resources/tosca/tca-policy-test.yaml80
-rw-r--r--src/test/resources/tosca/tosca_example.yaml80
13 files changed, 952 insertions, 196 deletions
diff --git a/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java b/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java
index a6a209a1e..293f0e625 100644
--- a/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java
+++ b/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java
@@ -77,7 +77,7 @@ public class OperationalPolicyAttributesConstructorTest {
// then
Assertions.assertThat(requestAttributes).containsKeys(AttributeType.MATCHING, AttributeType.RULE);
Assertions.assertThat(requestAttributes.get(AttributeType.MATCHING))
- .contains(Assertions.entry(OperationalPolicyAttributesConstructor.CONTROLLER, "amsterdam"));
+ .contains(Assertions.entry(OperationalPolicyAttributesConstructor.CONTROLLER, "amsterdam"));
Map<String, String> ruleParameters = requestAttributes.get(AttributeType.RULE);
Assertions.assertThat(ruleParameters).containsExactly(
@@ -97,8 +97,8 @@ public class OperationalPolicyAttributesConstructorTest {
// given
ClampProperties mockClampProperties = createMockClampProperties(
ImmutableMap.<String, String>builder().put("op.templateName", "ClosedLoopControlName")
- .put("op.operationTopic", "APPP-CL").put("op.notificationTopic", "POLICY-CL-MGT")
- .put("op.controller", "amsterdam").put("op.recipeTopic", "APPC").build());
+ .put("op.operationTopic", "APPP-CL").put("op.notificationTopic", "POLICY-CL-MGT")
+ .put("op.controller", "amsterdam").put("op.recipeTopic", "APPC").build());
Policy expectedPolicy = new Policy("6f76ad0b-ea9d-4a92-8d7d-6a6367ce2c77", "healthCheck Policy",
"healthCheck Policy - the trigger (no parent) policy - created by CLDS", "APPC", null,
@@ -112,7 +112,7 @@ public class OperationalPolicyAttributesConstructorTest {
// then
Assertions.assertThat(requestAttributes).containsKeys(AttributeType.MATCHING, AttributeType.RULE);
Assertions.assertThat(requestAttributes.get(AttributeType.MATCHING))
- .contains(Assertions.entry("controller", "amsterdam"));
+ .contains(Assertions.entry("controller", "amsterdam"));
Map<String, String> ruleParameters = requestAttributes.get(AttributeType.RULE);
Assertions.assertThat(ruleParameters).contains(
@@ -127,7 +127,7 @@ public class OperationalPolicyAttributesConstructorTest {
Assertions.assertThat(controlLoopPolicy.getControlLoop().getControlLoopName()).isEqualTo(CONTROL_NAME);
Assertions.assertThat(controlLoopPolicy.getPolicies()).usingElementComparatorIgnoringFields("id")
- .containsExactly(expectedPolicy);
+ .containsExactly(expectedPolicy);
}
private ClampProperties createMockClampProperties(ImmutableMap<String, String> propertiesMap) {
diff --git a/src/test/java/org/onap/clamp/clds/it/CldsDictionaryServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsDictionaryServiceItCase.java
new file mode 100644
index 000000000..d31d5a01e
--- /dev/null
+++ b/src/test/java/org/onap/clamp/clds/it/CldsDictionaryServiceItCase.java
@@ -0,0 +1,161 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2018 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.clds.it;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+import java.io.IOException;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import org.onap.clamp.clds.model.CldsDictionary;
+import org.onap.clamp.clds.model.CldsDictionaryItem;
+import org.onap.clamp.clds.service.CldsDictionaryService;
+import org.onap.clamp.clds.util.LoggingUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ * Test CLDS Dictionary Service APIs.
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class CldsDictionaryServiceItCase {
+
+ protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsDictionaryServiceItCase.class);
+ @Autowired
+ private CldsDictionaryService cldsDictionaryService;
+ private Authentication authentication;
+ private CldsDictionary cldsDictionary;
+ private CldsDictionaryItem cldsDictionaryItem;
+ private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>();
+ private LoggingUtils util;
+
+ /**
+ * Setup the variable before the tests execution.
+ *
+ * @throws IOException
+ * In case of issues when opening the files
+ */
+ @Before
+ public void setupBefore() throws IOException {
+ authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|read"));
+ authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|update"));
+ authList.add(new SimpleGrantedAuthority("permission-type-template|dev|read"));
+ authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update"));
+ authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*"));
+ authList.add(new SimpleGrantedAuthority("permission-type-tosca|dev|read"));
+ authList.add(new SimpleGrantedAuthority("permission-type-tosca|dev|update"));
+ authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList);
+
+ SecurityContext securityContext = Mockito.mock(SecurityContext.class);
+ Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
+
+ util = Mockito.mock(LoggingUtils.class);
+ Mockito.doNothing().when(util).entering(Matchers.any(HttpServletRequest.class), Matchers.any(String.class));
+ cldsDictionaryService.setLoggingUtil(util);
+
+ cldsDictionaryService.setSecurityContext(securityContext);
+
+ cldsDictionary = new CldsDictionary();
+
+ cldsDictionary.setDictionaryName("TestDictionary");
+ ResponseEntity entity = cldsDictionaryService.createOrUpdateDictionary("TestDictionary", cldsDictionary);
+ cldsDictionary = (CldsDictionary) entity.getBody();
+
+ cldsDictionaryItem = new CldsDictionaryItem();
+ cldsDictionaryItem.setDictElementShortName("TestDictionaryItemShortName");
+ cldsDictionaryItem.setDictElementName("TestDictionaryItemName");
+ cldsDictionaryItem.setDictElementType("string");
+ cldsDictionaryItem.setDictionaryId(cldsDictionary.getDictionaryId());
+ cldsDictionaryItem.setDictElementDesc("TestDictionaryItemDesc");
+ cldsDictionaryService.createOrUpdateDictionaryElements("TestDictionary", cldsDictionaryItem);
+
+ logger.info("Initial Clds Dictionary uploaded in DB:" + cldsDictionaryItem);
+ }
+
+ @Test
+ public void testCreateOrUpdateDictionary() throws Exception {
+ ResponseEntity<CldsDictionary> responseEntity = cldsDictionaryService.createOrUpdateDictionary("TestDictionary",
+ cldsDictionary);
+ CldsDictionary dictionary = responseEntity.getBody();
+ assertNotNull(dictionary);
+ logger.info("CLDS Dictionary is:" + dictionary);
+ assertEquals("TestDictionary", dictionary.getDictionaryName());
+ }
+
+ @Test
+ public void testCreateOrUpdateDictionaryElements() throws Exception {
+ cldsDictionaryItem = new CldsDictionaryItem();
+ cldsDictionaryItem.setDictElementShortName("TestDictionaryItemShortName1");
+ cldsDictionaryItem.setDictElementName("TestDictionaryItemName1");
+ cldsDictionaryItem.setDictElementType("string");
+ cldsDictionaryItem.setDictionaryId(cldsDictionary.getDictionaryId());
+ cldsDictionaryItem.setDictElementDesc("TestDictionaryItemDesc1");
+
+ ResponseEntity<CldsDictionaryItem> responseEntity = cldsDictionaryService
+ .createOrUpdateDictionaryElements("TestDictionary", cldsDictionaryItem);
+ CldsDictionaryItem dictionaryItem = responseEntity.getBody();
+ assertNotNull(dictionaryItem);
+ logger.info("CLDS Dictionary Item is:" + dictionaryItem);
+ assertEquals("TestDictionaryItemName1", dictionaryItem.getDictElementName());
+ }
+
+ @Test
+ public void testGetAllDictionaryNames() throws Exception {
+ ResponseEntity<List<CldsDictionary>> responseEntity = cldsDictionaryService.getAllDictionaryNames();
+ List<CldsDictionary> dictionaries = responseEntity.getBody();
+ assertNotNull(dictionaries);
+ logger.info("CLDS Dictionary List is:" + dictionaries);
+ }
+
+ @Test
+ public void testGetDictionaryElementsByName() throws Exception {
+ ResponseEntity<List<CldsDictionaryItem>> responseEntity = cldsDictionaryService
+ .getDictionaryElementsByName("TestDictionary");
+ List<CldsDictionaryItem> dictionaryItems = responseEntity.getBody();
+ assertNotNull(dictionaryItems);
+ logger.info("CLDS Dictionary Item LIst is:" + dictionaryItems);
+ }
+}
diff --git a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java
index e8d52c0ed..ff65f42e2 100644
--- a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java
+++ b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java
@@ -54,6 +54,7 @@ import org.onap.clamp.clds.dao.CldsDao;
import org.onap.clamp.clds.model.CldsEvent;
import org.onap.clamp.clds.model.CldsInfo;
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.model.DcaeEvent;
@@ -120,6 +121,7 @@ public class CldsServiceItCase {
util = Mockito.mock(LoggingUtils.class);
Mockito.doNothing().when(util).entering(Matchers.any(HttpServletRequest.class), Matchers.any(String.class));
cldsService.setLoggingUtil(util);
+
}
@Test
@@ -159,6 +161,12 @@ public class CldsServiceItCase {
}
@Test
+ public void testGetCLDSDetails() throws IOException {
+ List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsService.getCLDSDetails();
+ assertNotNull(cldsMonitoringDetailsList);
+ }
+
+ @Test
public void testCompleteFlow() throws TransformerException, ParseException {
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
@@ -190,6 +198,10 @@ public class CldsServiceItCase {
// Test the PutModel method
cldsService.putModel(randomNameModel, newModel);
+
+ assertEquals(bpmnText, cldsService.getBpmnXml(randomNameModel));
+ assertEquals(imageText, cldsService.getImageXml(randomNameModel));
+
// Verify whether it has been added properly or not
assertNotNull(cldsDao.getModel(randomNameModel));
diff --git a/src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java
new file mode 100644
index 000000000..407e0c50c
--- /dev/null
+++ b/src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java
@@ -0,0 +1,141 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2018 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.clds.it;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.IOException;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.model.CldsToscaModel;
+import org.onap.clamp.clds.service.CldsToscaService;
+import org.onap.clamp.clds.util.LoggingUtils;
+import org.onap.clamp.clds.util.ResourceFileUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+/**
+ * Test CLDS Tosca Service APIs.
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class CldsToscaServiceItCase {
+
+ protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsToscaServiceItCase.class);
+ @Autowired
+ private CldsToscaService cldsToscaService;
+ @Autowired
+ private CldsDao cldsDao;
+ private String toscaModelYaml;
+ private Authentication authentication;
+ private CldsToscaModel cldsToscaModel;
+ private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>();
+ private LoggingUtils util;
+
+ /**
+ * Setup the variable before the tests execution.
+ *
+ * @throws IOException
+ * In case of issues when opening the files
+ */
+ @Before
+ public void setupBefore() throws IOException {
+ authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|read"));
+ authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|update"));
+ authList.add(new SimpleGrantedAuthority("permission-type-template|dev|read"));
+ authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update"));
+ authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*"));
+ authList.add(new SimpleGrantedAuthority("permission-type-tosca|dev|read"));
+ authList.add(new SimpleGrantedAuthority("permission-type-tosca|dev|update"));
+ authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList);
+
+ SecurityContext securityContext = Mockito.mock(SecurityContext.class);
+ Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
+
+ util = Mockito.mock(LoggingUtils.class);
+ Mockito.doNothing().when(util).entering(Matchers.any(HttpServletRequest.class), Matchers.any(String.class));
+ cldsToscaService.setLoggingUtil(util);
+
+ cldsToscaService.setSecurityContext(securityContext);
+
+ toscaModelYaml = ResourceFileUtil.getResourceAsString("tosca/tca-policy-test.yaml");
+
+ cldsToscaModel = new CldsToscaModel();
+ cldsToscaModel.setToscaModelName("tca-policy-test");
+ cldsToscaModel.setToscaModelYaml(toscaModelYaml);
+ cldsToscaModel.setUserId("admin");
+ cldsToscaModel.setPolicyType("tca");
+ cldsToscaService.parseToscaModelAndSave("tca-policy-test", cldsToscaModel);
+ logger.info("Initial Tosca Model uploaded in DB:" + cldsToscaModel);
+ }
+
+ @Test
+ public void testParseToscaModelAndSave() throws Exception {
+ ResponseEntity responseEntity = cldsToscaService.parseToscaModelAndSave("tca-policy-test", cldsToscaModel);
+ CldsToscaModel savedModel = (CldsToscaModel) responseEntity.getBody();
+ assertNotNull(savedModel);
+ logger.info("Parsed Tosca Model is:" + savedModel);
+ assertEquals("tca-policy-test", savedModel.getToscaModelName());
+ }
+
+ @Test
+ public void testGetToscaModel() throws Exception {
+ ResponseEntity<CldsToscaModel> responseEntity = cldsToscaService.getToscaModel("tca-policy-test");
+ CldsToscaModel savedModel = responseEntity.getBody();
+ assertNotNull(savedModel);
+ assertEquals("tca-policy-test", savedModel.getToscaModelName());
+ }
+
+ @Test
+ public void testGetToscaModelsByPolicyType() throws Exception {
+ ResponseEntity<CldsToscaModel> responseEntity = cldsToscaService.getToscaModelsByPolicyType("tca");
+ CldsToscaModel savedModel = responseEntity.getBody();
+ assertNotNull(savedModel);
+ assertEquals("tca-policy-test", savedModel.getToscaModelName());
+ assertEquals("tca", savedModel.getPolicyType());
+ }
+
+}
diff --git a/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java b/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java
index 95e29c034..37eb6aed3 100644
--- a/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java
+++ b/src/test/java/org/onap/clamp/clds/it/config/CldsReferencePropertiesItCase.java
@@ -18,7 +18,7 @@
* limitations under the License.
* ============LICENSE_END============================================
* ===================================================================
- *
+ *
*/
package org.onap.clamp.clds.it.config;
@@ -26,10 +26,12 @@ package org.onap.clamp.clds.it.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -64,7 +66,7 @@ public class CldsReferencePropertiesItCase {
* Test getting prop value as a JSON Node / template.
*
* @throws IOException
- * when JSON parsing fails
+ * when JSON parsing fails
*/
@Test
public void testGetJsonTemplate() throws IOException {
@@ -85,7 +87,7 @@ public class CldsReferencePropertiesItCase {
* Test getting prop value as a JSON Node / template.
*
* @throws IOException
- * when JSON parsing fails
+ * when JSON parsing fails
*/
@Test
public void testGetFileContent() throws IOException {
@@ -95,4 +97,13 @@ public class CldsReferencePropertiesItCase {
content = refProp.getFileContent("sdc.decode", "service_ids");
assertEquals("{}", content);
}
+
+ @Test
+ public void testGetStringList() {
+ List<String> profileList = refProp.getStringList("policy.pdpUrl1", ",");
+ assertTrue(profileList.size() == 3);
+ assertTrue(profileList.get(0).trim().equals("http://localhost:8085/pdp/"));
+ assertTrue(profileList.get(1).trim().equals("testpdp"));
+ assertTrue(profileList.get(2).trim().equals("alpha123"));
+ }
}
diff --git a/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java b/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java
new file mode 100644
index 000000000..d94ffabaf
--- /dev/null
+++ b/src/test/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertorTest.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2018 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.clds.tosca;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.io.IOException;
+
+import org.junit.Test;
+import org.onap.clamp.clds.util.ResourceFileUtil;
+import org.skyscreamer.jsonassert.JSONAssert;
+
+public class ToscaYamlToJsonConvertorTest {
+
+ /**
+ * This Test validates TOSCA yaml to JSON Schema conversion based on JSON Editor
+ * Schema.
+ *
+ * @throws IOException
+ *
+ */
+ @Test
+ public final void testParseToscaYaml() throws IOException {
+ String toscaModelYaml = ResourceFileUtil.getResourceAsString("tosca/tosca_example.yaml");
+ ToscaYamlToJsonConvertor convertor = new ToscaYamlToJsonConvertor(null);
+
+ String parsedJsonSchema = convertor.parseToscaYaml(toscaModelYaml);
+ assertNotNull(parsedJsonSchema);
+ JSONAssert.assertEquals(
+ ResourceFileUtil.getResourceAsString("example/json-editor-schema/tca-policy-json-editor-schema.json"),
+ parsedJsonSchema, true);
+ }
+}
diff --git a/src/test/java/org/onap/clamp/clds/util/JacksonUtilsTest.java b/src/test/java/org/onap/clamp/clds/util/JacksonUtilsTest.java
index e482d6870..1d9e4e79d 100644
--- a/src/test/java/org/onap/clamp/clds/util/JacksonUtilsTest.java
+++ b/src/test/java/org/onap/clamp/clds/util/JacksonUtilsTest.java
@@ -5,20 +5,20 @@
* Copyright (C) 2018 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.
+ * 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
* ===================================================================
- *
+ *
*/
package org.onap.clamp.clds.util;
@@ -73,21 +73,22 @@ public class JacksonUtilsTest {
/**
* This method test that the security hole in Jackson is not enabled in the
* default ObjectMapper.
- *
+ *
* @throws JsonParseException
- * In case of issues
+ * In case of issues
* @throws JsonMappingException
- * In case of issues
+ * In case of issues
* @throws IOException
- * In case of issues
+ * In case of issues
*/
@Test
public void testCreateBeanDeserializer() throws JsonParseException, JsonMappingException, IOException {
TestClass test = new TestClass("value1", "value2");
test.setObject2(new TestObject2("test3"));
- Object testObject = JacksonUtils.getObjectMapperInstance().readValue(
- "[\"org.onap.clamp.clds.util.JacksonUtilsTest$TestClass\",{\"test\":\"value1\",\"test2\":\"value2\",\"object2\":[\"org.onap.clamp.clds.util.TestObject2\",{\"test3\":\"test3\"}]}]",
- Object.class);
+ Object testObject = JacksonUtils.getObjectMapperInstance()
+ .readValue("[\"org.onap.clamp.clds.util.JacksonUtilsTest$TestClass\""
+ + ",{\"test\":\"value1\",\"test2\":\"value2\",\"object2\":[\"org.onap.clamp.clds.util.TestObject2\","
+ + "{\"test3\":\"test3\"}]}]", Object.class);
assertNotNull(testObject);
assertFalse(testObject instanceof TestObject);
assertFalse(testObject instanceof TestClass);
diff --git a/src/test/resources/clds/camel/routes/flexible-flow.xml b/src/test/resources/clds/camel/routes/flexible-flow.xml
new file mode 100644
index 000000000..8305c2e49
--- /dev/null
+++ b/src/test/resources/clds/camel/routes/flexible-flow.xml
@@ -0,0 +1,50 @@
+<routes xmlns="http://camel.apache.org/schema/spring">
+ <route id="submit">
+ <from uri="direct:processSubmit" />
+ <choice>
+ <when>
+ <simple> ${exchangeProperty.actionCd} == 'SUBMIT' || ${exchangeProperty.actionCd} == 'RESUBMIT'</simple>
+ <to uri="bean:org.onap.clamp.clds.client.TcaPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.HolmesPolicyDelegate" />
+ <delay>
+ <constant>30000</constant>
+ </delay>
+ <to uri="bean:org.onap.clamp.clds.client.OperationalPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
+ </when>
+ <when>
+ <simple> ${exchangeProperty.actionCd} == 'DELETE'</simple>
+ <to uri="bean:org.onap.clamp.clds.client.TcaPolicyDeleteDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.HolmesPolicyDeleteDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.ModelDeleteDelegate" />
+ <delay>
+ <constant>30000</constant>
+ </delay>
+ <to
+ uri="bean:org.onap.clamp.clds.client.OperationalPolicyDeleteDelegate" />
+ </when>
+ <when>
+ <simple> ${exchangeProperty.actionCd} == 'UPDATE'</simple>
+ <to uri="bean:org.onap.clamp.clds.client.TcaPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.HolmesPolicyDelegate" />
+ <delay>
+ <constant>30000</constant>
+ </delay>
+ <to uri="bean:org.onap.clamp.clds.client.OperationalPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
+ </when>
+ <when>
+ <simple> ${exchangeProperty.actionCd} == 'STOP'</simple>
+ <to
+ uri="bean:org.onap.clamp.clds.client.OperationalPolicyDeleteDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
+ </when>
+ <when>
+ <simple> ${exchangeProperty.actionCd} == 'RESTART'</simple>
+ <to uri="bean:org.onap.clamp.clds.client.OperationalPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
+ </when>
+ </choice>
+ </route>
+
+</routes> \ No newline at end of file
diff --git a/src/test/resources/example/json-editor-schema/tca-policy-json-editor-schema.json b/src/test/resources/example/json-editor-schema/tca-policy-json-editor-schema.json
new file mode 100644
index 000000000..11b91dfb4
--- /dev/null
+++ b/src/test/resources/example/json-editor-schema/tca-policy-json-editor-schema.json
@@ -0,0 +1,115 @@
+{
+ "schema": {
+ "uniqueItems": "true",
+ "format": "tabs-top",
+ "type": "array",
+ "title": "Thresholds",
+ "items": {
+ "type": "object",
+ "title": "Thresholds",
+ "required": [
+ "dummySignatures"
+ ],
+ "properties": {
+ "severity": {
+ "propertyOrder": 1004,
+ "title": "event severity or priority",
+ "type": "string",
+ "enum": [
+ "CRITICAL",
+ "MAJOR",
+ "MINOR",
+ "WARNING",
+ "NORMAL"
+ ]
+ },
+ "fieldPath": {
+ "propertyOrder": 1003,
+ "title": "Field Path",
+ "type": "string"
+ },
+ "thresholdValue": {
+ "propertyOrder": 1005,
+ "default": 0,
+ "maximum": 65535,
+ "title": "ThresholdValue",
+ "type": "integer",
+ "minimum": 0
+ },
+ "dummySignatures": {
+ "propertyOrder": 1007,
+ "uniqueItems": "true",
+ "format": "tabs-top",
+ "title": "dummy Signatures",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": [
+ "signature",
+ "traversal"
+ ],
+ "properties": {
+ "signature": {
+ "propertyOrder": 1008,
+ "required": [
+ "filter_clause"
+ ],
+ "properties": {
+ "filter_clause": {
+ "propertyOrder": 20002,
+ "title": "Filter Clause",
+ "type": "string",
+ "enum": [
+ "OR",
+ "AND",
+ "NOT"
+ ]
+ }
+ }
+ },
+ "traversal": {
+ "propertyOrder": 1009,
+ "required": [
+ "traversal"
+ ],
+ "properties": {
+ "traversal": {
+ "propertyOrder": 20003,
+ "title": "Dummy Traverse",
+ "type": "string",
+ "enum": [
+ "ONE",
+ "TWO",
+ "THREE"
+ ]
+ }
+ }
+ }
+ }
+ }
+ },
+ "closedLoopControlName": {
+ "propertyOrder": 1001,
+ "title": "A UNIQUE string identifying the Closed Loop ID this event is for.",
+ "type": "string"
+ },
+ "version": {
+ "propertyOrder": 1006,
+ "minLength": 1,
+ "title": "Version for the closed loop message",
+ "type": "string"
+ },
+ "direction": {
+ "propertyOrder": 1002,
+ "type": "string",
+ "enum": [
+ "LESS",
+ "LESS_OR_EQUAL",
+ "GREATER",
+ "GREATER_OR_EQUAL"
+ ]
+ }
+ }
+ }
+ }
+} \ 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 a8ff96ac1..178ac80af 100755
--- a/src/test/resources/http-cache/start_http_cache.sh
+++ b/src/test/resources/http-cache/start_http_cache.sh
@@ -49,4 +49,4 @@ 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_proxyaddress
+python -u 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 fdc4fab34..a10924128 100755
--- a/src/test/resources/http-cache/third_party_proxy.py
+++ b/src/test/resources/http-cache/third_party_proxy.py
@@ -25,6 +25,7 @@
import json
import requests
import os
+import errno
import sys
import SimpleHTTPServer
import SocketServer
@@ -37,7 +38,8 @@ import shutil
parser = argparse.ArgumentParser(description="3rd party Cache & Replay")
parser.add_argument("--username", "-u", type=str, help="Set the username for contacting 3rd party - only used for GET")
parser.add_argument("--password", "-p", type=str, help="Set the password for contacting 3rd party - only used for GET")
-parser.add_argument("--root", "-r", default=tempfile.mkdtemp, type=str, help="Root folder for the proxy cache")
+parser.add_argument("--root", "-r", default=tempfile.mkdtemp(), type=str, help="Root folder for the proxy cache")
+parser.add_argument("--temp", "-t", default=tempfile.mkdtemp(), type=str, help="Temp folder for the generated content")
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")
@@ -49,8 +51,9 @@ PORT = options.port
HOST = options.proxy
AUTH = (options.username, options.password)
HEADERS = {'X-ECOMP-InstanceID':'CLAMP'}
-CACHE_ROOT = options.root
-PROXY_ADDRESS=options.proxyaddress
+CACHE_ROOT = str(options.root)
+TMP_ROOT = str(options.temp)
+PROXY_ADDRESS=str(options.proxyaddress)
def signal_handler(signal_sent, frame):
global httpd
@@ -61,7 +64,6 @@ def signal_handler(signal_sent, frame):
httpd.server_close()
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
-
def print_headers(self):
for header,value in self.headers.items():
print("header: %s : %s" % (header, value))
@@ -82,238 +84,286 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
fc = f.read()
self.wfile.write(fc)
- def _write_cache(self,cached_file, header_file, content_file, response):
- os.makedirs(cached_file, True)
+ def _write_cache(self,cached_file_folder, header_file, content_file, response):
+ os.makedirs(cached_file_folder, 0777)
with open(content_file, 'w') as f:
f.write(response.raw.read())
with open(header_file, 'w') as f:
json.dump(dict(response.raw.headers), f)
# Entry point of the code
+ def _get_cached_file_folder_name(self,folder):
+ cached_file_folder = '%s/%s' % (folder, self.path,)
+ print("Cached file name before escaping : %s" % cached_file_folder)
+ cached_file_folder = cached_file_folder.replace('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
+ print("Cached file name after escaping (used for cache storage) : %s" % cached_file_folder)
+ return cached_file_folder
+
+ def _get_cached_content_file_name(self,cached_file_folder):
+ return "%s/.file" % (cached_file_folder,)
+
+ def _get_cached_header_file_name(self,cached_file_folder):
+ return "%s/.header" % (cached_file_folder,)
+
+ def _execute_content_generated_cases(self,http_type):
+ print("Testing special cases, cache files will be sent to :" +TMP_ROOT)
+ cached_file_folder = self._get_cached_file_folder_name(TMP_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
+ _file_available = os.path.exists(cached_file_content)
+
+ if self.path.startswith("/dcae-service-types?asdcResourceId=") and http_type == "GET":
+ if not _file_available:
+ print "self.path start with /dcae-service-types?asdcResourceId=, generating response json..."
+ uuidGenerated = str(uuid.uuid4())
+ typeId = "typeId-" + uuidGenerated
+ typeName = "typeName-" + uuidGenerated
+ print "typeId generated: " + typeName + " and typeName: "+ typeId
+ jsonGenerated = "{\"totalCount\":1, \"items\":[{\"typeId\":\"" + typeId + "\", \"typeName\":\"" + typeName +"\"}]}"
+ print "jsonGenerated: " + jsonGenerated
+
+ os.makedirs(cached_file_folder, 0777)
+ 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)
+ return True
+ elif self.path.startswith("/dcae-operationstatus") and http_type == "GET":
+ if not _file_available:
+ print "self.path start with /dcae-operationstatus, generating response json..."
+ jsonGenerated = "{\"operationType\": \"operationType1\", \"status\": \"succeeded\"}"
+ print "jsonGenerated: " + jsonGenerated
+
+ try:
+ os.makedirs(cached_file_folder, 0777)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise
+ print(cached_file_folder+" already exists")
+
+ 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)
+ return True
+ elif self.path.startswith("/sdc/v1/catalog/services/") and http_type == "POST":
+ if not _file_available:
+ print "self.path start with /sdc/v1/catalog/services/, generating response json..."
+ jsondata = json.loads(self.data_string)
+ jsonGenerated = "{\"artifactName\":\"" + jsondata['artifactName'] + "\",\"artifactType\":\"" + jsondata['artifactType'] + "\",\"artifactURL\":\"" + self.path + "\",\"artifactDescription\":\"" + jsondata['description'] + "\",\"artifactChecksum\":\"ZjJlMjVmMWE2M2M1OTM2MDZlODlmNTVmZmYzNjViYzM=\",\"artifactUUID\":\"" + str(uuid.uuid4()) + "\",\"artifactVersion\":\"1\"}"
+ print "jsonGenerated: " + jsonGenerated
+
+ os.makedirs(cached_file_folder, 0777)
+ 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)
+ return True;
+ elif self.path.startswith("/dcae-deployments/") and (http_type == "PUT" or http_type == "DELETE"):
+ if not _file_available:
+ 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_folder, 0777)
+ 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)
+ return True
+ else:
+ return False
+
+
def do_GET(self):
+ cached_file_folder = ""
+ cached_file_content =""
+ cached_file_header=""
print("\n\n\nGot a GET request for %s " % self.path)
self.print_headers()
self.check_credentials()
-
- cached_file = '%s/%s' % (CACHE_ROOT, self.path,)
- print("Cached file name before escaping : %s" % cached_file)
- cached_file = cached_file.replace('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
- 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,)
+ # Verify if it's a special case
+ is_special = self._execute_content_generated_cases("GET")
+ if is_special:
+ cached_file_folder = self._get_cached_file_folder_name(TMP_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
+ else:
+ cached_file_folder = self._get_cached_file_folder_name(CACHE_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
_file_available = os.path.exists(cached_file_content)
if not _file_available:
- print("Request for data currently not present in cache: %s" % (cached_file,))
-
- if self.path.startswith("/dcae-service-types?asdcResourceId="):
- print "self.path start with /dcae-service-types?asdcResourceId=, generating response json..."
- uuidGenerated = str(uuid.uuid4())
- typeId = "typeId-" + uuidGenerated
- typeName = "typeName-" + uuidGenerated
- print "typeId generated: " + typeName + " and typeName: "+ typeId
- jsonGenerated = "{\"totalCount\":1, \"items\":[{\"typeId\":\"" + typeId + "\", \"typeName\":\"" + typeName +"\"}]}"
- 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)
- 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)
+ print("Request for data currently not present in cache: %s" % (cached_file_folder,))
+
+ if not HOST:
+ self.send_response(404)
+ return "404 Not found"
+
+ url = '%s%s' % (HOST, self.path)
+ response = requests.get(url, auth=AUTH, headers=HEADERS, stream=True)
+
+ if response.status_code == 200:
+ self._write_cache(cached_file_folder, cached_file_header, cached_file_content, response)
else:
- if not HOST:
- self.send_response(404)
- return "404 Not found"
-
- url = '%s%s' % (HOST, self.path)
- response = requests.get(url, auth=AUTH, headers=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
+ 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 currently present in cache: %s" % (cached_file,))
+ print("Request for data currently present in cache: %s" % (cached_file_folder,))
self._send_content(cached_file_header, cached_file_content)
if self.path.startswith("/dcae-service-types?asdcResourceId="):
- print "DCAE case deleting folder created " + cached_file
- shutil.rmtree(cached_file, ignore_errors=False, onerror=None)
+ print "DCAE case deleting folder created " + cached_file_folder
+ shutil.rmtree(cached_file_folder, ignore_errors=False, onerror=None)
else:
- print "NOT in DCAE case deleting folder created " + cached_file
+ print "NOT in DCAE case deleting folder created " + cached_file_folder
def do_POST(self):
+ cached_file_folder = ""
+ cached_file_content =""
+ cached_file_header=""
print("\n\n\nGot a POST for %s" % self.path)
self.check_credentials()
self.data_string = self.rfile.read(int(self.headers['Content-Length']))
print("data-string:\n %s" % self.data_string)
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('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
- 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,)
+ is_special = self._execute_content_generated_cases("POST")
+ if is_special:
+ cached_file_folder = self._get_cached_file_folder_name(TMP_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
+ else:
+ cached_file_folder = self._get_cached_file_folder_name(CACHE_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
_file_available = os.path.exists(cached_file_content)
if not _file_available:
- if self.path.startswith("/sdc/v1/catalog/services/"):
- print "self.path start with /sdc/v1/catalog/services/, generating response json..."
- jsondata = json.loads(self.data_string)
- jsonGenerated = "{\"artifactName\":\"" + jsondata['artifactName'] + "\",\"artifactType\":\"" + jsondata['artifactType'] + "\",\"artifactURL\":\"" + self.path + "\",\"artifactDescription\":\"" + jsondata['description'] + "\",\"artifactChecksum\":\"ZjJlMjVmMWE2M2M1OTM2MDZlODlmNTVmZmYzNjViYzM=\",\"artifactUUID\":\"" + str(uuid.uuid4()) + "\",\"artifactVersion\":\"1\"}"
- 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)
+
+ if not HOST:
+ self.send_response(404)
+ return "404 Not found"
+
+ print("Request for data currently not present in cache: %s" % (cached_file_folder,))
+
+ url = '%s%s' % (HOST, self.path)
+ print("url: %s" % (url,))
+ response = requests.post(url, data=self.data_string, headers=self.headers, stream=True)
+
+ if response.status_code == 200:
+ self._write_cache(cached_file_folder, cached_file_header, cached_file_content, response)
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.post(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
+ 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,))
+ print("Request for data present in cache: %s" % (cached_file_folder,))
self._send_content(cached_file_header, cached_file_content)
def do_PUT(self):
+ cached_file_folder = ""
+ cached_file_content =""
+ cached_file_header=""
print("\n\n\nGot a PUT for %s " % self.path)
self.check_credentials()
self.data_string = self.rfile.read(int(self.headers['Content-Length']))
print("data-string:\n %s" % self.data_string)
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('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
- 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,)
+ is_special = self._execute_content_generated_cases("PUT")
+ if is_special:
+ cached_file_folder = self._get_cached_file_folder_name(TMP_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
+ else:
+ cached_file_folder = self._get_cached_file_folder_name(CACHE_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
_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)
+ if not HOST:
+ self.send_response(404)
+ return "404 Not found"
+
+ print("Request for data currently not present in cache: %s" % (cached_file_folder,))
+
+ 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_folder, cached_file_header, cached_file_content, response)
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
+ 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,))
+ print("Request for data present in cache: %s" % (cached_file_folder,))
self._send_content(cached_file_header, cached_file_content)
def do_DELETE(self):
+ cached_file_folder = ""
+ cached_file_content =""
+ cached_file_header=""
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('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
- 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,)
+ is_special = self._execute_content_generated_cases("DELETE")
+ if is_special:
+ cached_file_folder = self._get_cached_file_folder_name(TMP_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
+ else:
+ cached_file_folder = self._get_cached_file_folder_name(CACHE_ROOT)
+ cached_file_content = self._get_cached_content_file_name(cached_file_folder)
+ cached_file_header = self._get_cached_header_file_name(cached_file_folder)
_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)
+ if not HOST:
+ self.send_response(404)
+ return "404 Not found"
+
+ print("Request for data currently not present in cache: %s" % (cached_file_folder,))
+
+ 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_folder, cached_file_header, cached_file_content, response)
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
+ 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,))
+ print("Request for data present in cache: %s" % (cached_file_folder,))
self._send_content(cached_file_header, cached_file_content)
@@ -322,6 +372,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
# Main code that start the HTTP server
httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
httpd.allow_reuse_address = True
-print "Listening on port "+ str(PORT) + " and caching in " + CACHE_ROOT + "(Press Ctrl+C to stop HTTPD Caching script)"
+print "Listening on port "+ str(PORT) + "(Press Ctrl+C/Ctrl+Z to stop HTTPD Caching script)"
+print "Caching folder " + CACHE_ROOT + ", Tmp folder for generated files " + TMP_ROOT
signal.signal(signal.SIGINT, signal_handler)
httpd.serve_forever() \ No newline at end of file
diff --git a/src/test/resources/tosca/tca-policy-test.yaml b/src/test/resources/tosca/tca-policy-test.yaml
new file mode 100644
index 000000000..3c5afb01d
--- /dev/null
+++ b/src/test/resources/tosca/tca-policy-test.yaml
@@ -0,0 +1,80 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ policy.nodes.cdap.tca.hi.lo.app:
+ derived_from: policy.nodes.Root
+ properties:
+ domain:
+ type: string
+ description: Domain
+ constraints:
+ - equal: measurementsForVfScaling
+ functionalRole:
+ type: string
+ description: Function of the event source e.g., vnf1, vnf2, vnf3
+ thresholds:
+ type: list
+ description: Thresholds
+ entry_schema:
+ type: policy.data.thresholds
+data_types:
+ policy.data.thresholds:
+ properties:
+ closedLoopControlName:
+ type: string
+ description: A UNIQUE string identifying the Closed Loop ID this event is for.
+ direction:
+ type: string
+ constraints:
+ - valid_values: [ LESS, LESS_OR_EQUAL, GREATER, GREATER_OR_EQUAL]
+ fieldPath:
+ description: Field Path
+ type: string
+ severity:
+ type: string
+ description: event severity or priority
+ constraints:
+ - valid_values: [CRITICAL, MAJOR, MINOR, WARNING, NORMAL]
+ thresholdValue:
+ type: integer
+ description: ThresholdValue
+ default: 0
+ constraints:
+ - in_range: [ 0, 65535 ]
+ version:
+ type: string
+ description: Version for the closed loop message
+ constraints:
+ - min_length: 1
+ dummySignatures:
+ type: list
+ description: dummy Signatures
+ required: true
+ entry_schema:
+ type: policy.data.dummySignatureTraversal
+ policy.data.dummySignatureTraversal:
+ derived_from: tosca.nodes.Root
+ properties:
+ signature:
+ type: policy.data.DUMMY_Signature_FM
+ required: true
+ traversal:
+ type: policy.data.traverse
+ required: true
+ policy.data.traverse:
+ derived_from: tosca.nodes.Root
+ properties:
+ traversal:
+ type: string
+ description: Dummy Traverse
+ required: true
+ constraints:
+ - valid_values: [ ONE, TWO, THREE ]
+ policy.data.DUMMY_Signature_FM:
+ derived_from: tosca.nodes.Root
+ properties:
+ filter_clause:
+ type: string
+ description: Filter Clause
+ required: true
+ constraints:
+ - valid_values: [ OR, AND, NOT ]
diff --git a/src/test/resources/tosca/tosca_example.yaml b/src/test/resources/tosca/tosca_example.yaml
new file mode 100644
index 000000000..3c5afb01d
--- /dev/null
+++ b/src/test/resources/tosca/tosca_example.yaml
@@ -0,0 +1,80 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ policy.nodes.cdap.tca.hi.lo.app:
+ derived_from: policy.nodes.Root
+ properties:
+ domain:
+ type: string
+ description: Domain
+ constraints:
+ - equal: measurementsForVfScaling
+ functionalRole:
+ type: string
+ description: Function of the event source e.g., vnf1, vnf2, vnf3
+ thresholds:
+ type: list
+ description: Thresholds
+ entry_schema:
+ type: policy.data.thresholds
+data_types:
+ policy.data.thresholds:
+ properties:
+ closedLoopControlName:
+ type: string
+ description: A UNIQUE string identifying the Closed Loop ID this event is for.
+ direction:
+ type: string
+ constraints:
+ - valid_values: [ LESS, LESS_OR_EQUAL, GREATER, GREATER_OR_EQUAL]
+ fieldPath:
+ description: Field Path
+ type: string
+ severity:
+ type: string
+ description: event severity or priority
+ constraints:
+ - valid_values: [CRITICAL, MAJOR, MINOR, WARNING, NORMAL]
+ thresholdValue:
+ type: integer
+ description: ThresholdValue
+ default: 0
+ constraints:
+ - in_range: [ 0, 65535 ]
+ version:
+ type: string
+ description: Version for the closed loop message
+ constraints:
+ - min_length: 1
+ dummySignatures:
+ type: list
+ description: dummy Signatures
+ required: true
+ entry_schema:
+ type: policy.data.dummySignatureTraversal
+ policy.data.dummySignatureTraversal:
+ derived_from: tosca.nodes.Root
+ properties:
+ signature:
+ type: policy.data.DUMMY_Signature_FM
+ required: true
+ traversal:
+ type: policy.data.traverse
+ required: true
+ policy.data.traverse:
+ derived_from: tosca.nodes.Root
+ properties:
+ traversal:
+ type: string
+ description: Dummy Traverse
+ required: true
+ constraints:
+ - valid_values: [ ONE, TWO, THREE ]
+ policy.data.DUMMY_Signature_FM:
+ derived_from: tosca.nodes.Root
+ properties:
+ filter_clause:
+ type: string
+ description: Filter Clause
+ required: true
+ constraints:
+ - valid_values: [ OR, AND, NOT ]