diff options
Diffstat (limited to 'runtime')
10 files changed, 167 insertions, 144 deletions
diff --git a/runtime/extra/docker/clamp/docker-compose.yml b/runtime/extra/docker/clamp/docker-compose.yml index c56be0aae..f27e1de02 100644 --- a/runtime/extra/docker/clamp/docker-compose.yml +++ b/runtime/extra/docker/clamp/docker-compose.yml @@ -27,7 +27,7 @@ services: - clamp.env ports: - "10443:8443" - + third-party-proxy: image: python:2-slim volumes: diff --git a/runtime/src/main/java/org/onap/policy/clamp/clds/Application.java b/runtime/src/main/java/org/onap/policy/clamp/clds/Application.java index bdab9c9a2..aad678bf7 100644 --- a/runtime/src/main/java/org/onap/policy/clamp/clds/Application.java +++ b/runtime/src/main/java/org/onap/policy/clamp/clds/Application.java @@ -121,8 +121,8 @@ public class Application extends SpringBootServletInitializer { @Bean public ServletRegistrationBean<ClampServlet> camelServletRegistrationBean() throws IOException { eelfLogger.info(ResourceFileUtils.getResourceAsString("boot-message.txt") + "(v" - + ClampVersioning.getCldsVersionFromProps() + ")" + System.getProperty("line.separator") - + getSslExpirationDate()); + + ClampVersioning.getCldsVersionFromProps() + ")" + System.getProperty("line.separator") + + getSslExpirationDate()); var registration = new ServletRegistrationBean<ClampServlet>(new ClampServlet(), "/restservices/clds/*"); registration.setName("CamelServlet"); return registration; @@ -150,7 +150,7 @@ public class Application extends SpringBootServletInitializer { private Connector createRedirectConnector(int redirectSecuredPort) { if (redirectSecuredPort <= 0) { eelfLogger.warn("HTTP port redirection to HTTPS is disabled because the HTTPS port is 0 (random port) or -1" - + " (Connector disabled)"); + + " (Connector disabled)"); return null; } var connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); @@ -167,15 +167,15 @@ public class Application extends SpringBootServletInitializer { if (keystoreFile != null) { var keystore = KeyStore.getInstance(keyStoreType); keystore.load(ResourceFileUtils.getResourceAsStream(keystoreFile.replace("classpath:", "")), - PassDecoder.decode(keyStorePass, keyFile).toCharArray()); + PassDecoder.decode(keyStorePass, keyFile).toCharArray()); Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if ("X.509".equals(keystore.getCertificate(alias).getType())) { result.append("* " + alias + " expires " - + ((X509Certificate) keystore.getCertificate(alias)).getNotAfter() - + System.getProperty("line.separator")); + + ((X509Certificate) keystore.getCertificate(alias)).getNotAfter() + + System.getProperty("line.separator")); } } } else { diff --git a/runtime/src/main/java/org/onap/policy/clamp/loop/template/LoopElementModel.java b/runtime/src/main/java/org/onap/policy/clamp/loop/template/LoopElementModel.java index 52f1c5d23..f1ab35722 100644 --- a/runtime/src/main/java/org/onap/policy/clamp/loop/template/LoopElementModel.java +++ b/runtime/src/main/java/org/onap/policy/clamp/loop/template/LoopElementModel.java @@ -40,6 +40,8 @@ import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; +import lombok.Getter; +import lombok.Setter; import org.hibernate.annotations.SortNatural; import org.onap.policy.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport; import org.onap.policy.clamp.loop.Loop; @@ -52,7 +54,8 @@ import org.onap.policy.clamp.policy.operational.OperationalPolicy; * This class represents a micro service/operational/... model for a loop template. * So it's an element in the flow (a box shown in the loop). */ - +@Getter +@Setter @Entity @Table(name = "loop_element_models") public class LoopElementModel extends AuditEntity implements Serializable { @@ -113,15 +116,6 @@ public class LoopElementModel extends AuditEntity implements Serializable { private Set<LoopTemplateLoopElementModel> usedByLoopTemplates = new HashSet<>(); /** - * policyModels getter. - * - * @return the policyModel - */ - public SortedSet<PolicyModel> getPolicyModels() { - return policyModels; - } - - /** * Method to add a new policyModel to the list. * * @param policyModel The policy model @@ -132,103 +126,6 @@ public class LoopElementModel extends AuditEntity implements Serializable { } /** - * name getter. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * name setter. - * - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * blueprint getter. - * - * @return the blueprint - */ - public String getBlueprint() { - return blueprint; - } - - /** - * blueprint setter. - * - * @param blueprint the blueprint to set - */ - public void setBlueprint(String blueprint) { - this.blueprint = blueprint; - } - - /** - * dcaeBlueprintId getter. - * - * @return the dcaeBlueprintId - */ - public String getDcaeBlueprintId() { - return dcaeBlueprintId; - } - - /** - * dcaeBlueprintId setter. - * - * @param dcaeBlueprintId the dcaeBlueprintId to set - */ - public void setDcaeBlueprintId(String dcaeBlueprintId) { - this.dcaeBlueprintId = dcaeBlueprintId; - } - - /** - * loopElementType getter. - * - * @return the loopElementType - */ - public String getLoopElementType() { - return loopElementType; - } - - /** - * loopElementType setter. - * - * @param loopElementType the loopElementType to set - */ - public void setLoopElementType(String loopElementType) { - this.loopElementType = loopElementType; - } - - /** - * shortName getter. - * - * @return the shortName - */ - public String getShortName() { - return shortName; - } - - /** - * * @param shortName the shortName to set. - */ - public void setShortName(String shortName) { - this.shortName = shortName; - } - - /** - * usedByLoopTemplates getter. - * - * @return the usedByLoopTemplates - */ - public Set<LoopTemplateLoopElementModel> getUsedByLoopTemplates() { - return usedByLoopTemplates; - } - - /** * Default constructor for serialization. */ public LoopElementModel() { diff --git a/runtime/src/main/java/org/onap/policy/clamp/tosca/Dictionary.java b/runtime/src/main/java/org/onap/policy/clamp/tosca/Dictionary.java index 40ea25ff8..da6454a44 100644 --- a/runtime/src/main/java/org/onap/policy/clamp/tosca/Dictionary.java +++ b/runtime/src/main/java/org/onap/policy/clamp/tosca/Dictionary.java @@ -177,9 +177,9 @@ public class Dictionary extends AuditEntity implements Serializable { /** * Constructor. * - * @param name The Dictionary name + * @param name The Dictionary name * @param secondLevelDictionary defines if dictionary is a secondary level - * @param subDictionaryType defines the type of secondary level dictionary + * @param subDictionaryType defines the type of secondary level dictionary */ public Dictionary(String name, int secondLevelDictionary, String subDictionaryType) { this.name = name; diff --git a/runtime/src/main/resources/application-noaaf.properties b/runtime/src/main/resources/application-noaaf.properties index a8f4399c4..e698cc0ce 100644 --- a/runtime/src/main/resources/application-noaaf.properties +++ b/runtime/src/main/resources/application-noaaf.properties @@ -4,6 +4,7 @@ # ================================================================================ # Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights # reserved. +# Modifications Copyright (C) 2021 Nordix Foundation. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,6 +17,8 @@ # 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. +# +# SPDX-License-Identifier: Apache-2.0 # ============LICENSE_END============================================ # =================================================================== # diff --git a/runtime/src/main/resources/clds/camel/routes/controlloop-flows.xml b/runtime/src/main/resources/clds/camel/routes/controlloop-flows.xml index 009e00fca..d2bf39b16 100644 --- a/runtime/src/main/resources/clds/camel/routes/controlloop-flows.xml +++ b/runtime/src/main/resources/clds/camel/routes/controlloop-flows.xml @@ -20,8 +20,7 @@ </setProperty> <log loggingLevel="INFO" message="Endpoint to get Tosca Service Template: {{clamp.config.controlloop.runtime.url}}/onap/controlloop/v2/commission/toscaservicetemplate"></log> - <toD - uri="{{clamp.config.controlloop.runtime.url}}/onap/controlloop/v2/commission/toscaservicetemplate?name=${exchangeProperty[name]}&version=${exchangeProperty[version]}&bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&authMethod=Basic&authUsername={{clamp.config.controlloop.runtime.userName}}&authPassword={{clamp.config.controlloop.runtime.password}}&authenticationPreemptive=true&connectionClose=true"/> + <toD uri="{{clamp.config.controlloop.runtime.url}}/onap/controlloop/v2/commission/toscaservicetemplate?name=${exchangeProperty[name]}&version=${exchangeProperty[version]}&bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&authMethod=Basic&authUsername={{clamp.config.controlloop.runtime.userName}}&authPassword={{clamp.config.controlloop.runtime.password}}&authenticationPreemptive=true&connectionClose=true"/> <convertBodyTo type="java.lang.String"/> <doFinally> <to uri="direct:reset-raise-http-exception-flag"/> @@ -40,10 +39,13 @@ <setHeader name="CamelHttpMethod"> <constant>POST</constant> </setHeader> + <setHeader name="Content-Type"> + <constant>application/json</constant> + </setHeader> <log loggingLevel="INFO" message="Endpoint to send Tosca Service Template: {{clamp.config.controlloop.runtime.url}}/onap/controlloop/v2/commission"></log> <toD - uri="{{clamp.config.controlloop.runtime.url}}/onap/controlloop/v2/commission?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&authMethod=Basic&authUsername={{clamp.config.controlloop.runtime.userName}}&authPassword={{clamp.config.controlloop.runtime.password}}&authenticationPreemptive=true&connectionClose=true"/> + uri="{{clamp.config.controlloop.runtime.url}}/onap/controlloop/v2/commission? bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&authMethod=Basic&authUsername={{clamp.config.controlloop.runtime.userName}}&authPassword={{clamp.config.controlloop.runtime.password}}&authenticationPreemptive=true&connectionClose=true"/> <convertBodyTo type="java.lang.String"/> <doFinally> <to uri="direct:reset-raise-http-exception-flag"/> diff --git a/runtime/src/test/java/org/onap/policy/clamp/policy/downloader/PolicyEngineControllerTestItCase.java b/runtime/src/test/java/org/onap/policy/clamp/policy/downloader/PolicyEngineControllerTestItCase.java index 4dd620c4b..8fbd2712b 100644 --- a/runtime/src/test/java/org/onap/policy/clamp/policy/downloader/PolicyEngineControllerTestItCase.java +++ b/runtime/src/test/java/org/onap/policy/clamp/policy/downloader/PolicyEngineControllerTestItCase.java @@ -72,15 +72,15 @@ public class PolicyEngineControllerTestItCase { List<PolicyModel> policyModelsList = policyModelsRepository.findAll(); assertThat(policyModelsList.size()).isGreaterThanOrEqualTo(5); assertThat(policyModelsList).contains(new PolicyModel("onap.policies.controlloop.operational.common.Drools", - null, "1.0.0")); + null, "1.0.0")); assertThat(policyModelsList).contains(new PolicyModel("onap.policies.controlloop.operational.common.Apex", - null, "1.0.0")); + null, "1.0.0")); assertThat(policyModelsList) - .contains(new PolicyModel("onap.policies.controlloop.guard.common.FrequencyLimiter", null, "1.0.0")); + .contains(new PolicyModel("onap.policies.controlloop.guard.common.FrequencyLimiter", null, "1.0.0")); assertThat(policyModelsList) - .contains(new PolicyModel("onap.policies.controlloop.guard.common.Blacklist", null, "1.0.0")); + .contains(new PolicyModel("onap.policies.controlloop.guard.common.Blacklist", null, "1.0.0")); assertThat(policyModelsList) - .contains(new PolicyModel("onap.policies.controlloop.guard.common.MinMax", null, "2.0.0")); + .contains(new PolicyModel("onap.policies.controlloop.guard.common.MinMax", null, "2.0.0")); // Re-do it to check that there is no issue with duplicate key policyController.synchronizeAllPolicies(); @@ -104,9 +104,9 @@ public class PolicyEngineControllerTestItCase { assertThat(policyModelsList.size()).isGreaterThanOrEqualTo(2); PolicyModel policy1 = policyModelsRepository - .getOne(new PolicyModelId("onap.policies.monitoring.test", "1.0.0")); + .getOne(new PolicyModelId("onap.policies.monitoring.test", "1.0.0")); PolicyModel policy2 = policyModelsRepository - .getOne(new PolicyModelId("onap.policies.controlloop.Operational", "1.0.0")); + .getOne(new PolicyModelId("onap.policies.controlloop.Operational", "1.0.0")); String expectedRes1 = "{\"supportedPdpGroups\":[{\"monitoring\":[\"xacml\"]}]}"; JsonObject expectedJson1 = JsonUtils.GSON.fromJson(expectedRes1, JsonObject.class); diff --git a/runtime/src/test/java/org/onap/policy/clamp/runtime/RuntimeCommissioningResponseTestItCase.java b/runtime/src/test/java/org/onap/policy/clamp/runtime/RuntimeCommissioningResponseTestItCase.java new file mode 100644 index 000000000..0ba1486bb --- /dev/null +++ b/runtime/src/test/java/org/onap/policy/clamp/runtime/RuntimeCommissioningResponseTestItCase.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.clamp.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.ExchangeBuilder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.policy.clamp.clds.Application; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class RuntimeCommissioningResponseTestItCase { + @Autowired + CamelContext camelContext; + + private static final String SAMPLE_TOSCA_TEMPLATE = + "{\"tosca_definitions_version\": \"tosca_simple_yaml_1_1_0\"," + + "\"data_types\": {},\"node_types\": {}, \"policy_types\": {}," + + " \"topology_template\": {}," + + " \"name\": \"ToscaServiceTemplateSimple\", \"version\": \"1.0.0\", \"metadata\": {}}"; + + @Test + public void testToscaServiceTemplateStatus() { + ProducerTemplate prodTemplate = camelContext.createProducerTemplate(); + + Exchange exchangeResponse = + prodTemplate.send("direct:get-service-template", ExchangeBuilder.anExchange(camelContext) + .withProperty("name", "ToscaServiceTemplate") + .withProperty("version", "1.0.0") + .withProperty("raiseHttpExceptionFlag", "true") + .build()); + + assertThat(HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE)) + .is2xxSuccessful()).isTrue(); + } + + @Test + public void testToscaServiceTemplateGetResponseBody() { + ProducerTemplate prodTemplate = camelContext.createProducerTemplate(); + + Exchange exchangeResponse = + prodTemplate.send("direct:get-service-template", ExchangeBuilder.anExchange(camelContext) + .withProperty("name", "ToscaServiceTemplate") + .withProperty("version", "1.0.0") + .withProperty("raiseHttpExceptionFlag", "true") + .build()); + + assertThat(exchangeResponse.getIn().getBody().toString()).isEqualTo(SAMPLE_TOSCA_TEMPLATE); + } + + @Test + public void testCommissioningOfToscaServiceTemplateStatus() { + ProducerTemplate prodTemplate = camelContext.createProducerTemplate(); + + Exchange exchangeResponse = + prodTemplate.send("direct:commission-service-template", ExchangeBuilder.anExchange(camelContext) + .withBody(SAMPLE_TOSCA_TEMPLATE) + .withProperty("raiseHttpExceptionFlag", "true") + .build()); + + assertThat(HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE)) + .is2xxSuccessful()).isTrue(); + } +} diff --git a/runtime/src/test/resources/application.properties b/runtime/src/test/resources/application.properties index 60704acf5..54a89078d 100644 --- a/runtime/src/test/resources/application.properties +++ b/runtime/src/test/resources/application.properties @@ -4,6 +4,7 @@ # ================================================================================ # Copyright (C) 2017-2018, 2021 AT&T Intellectual Property. All rights # reserved. +# Modifications Copyright (C) 2021 Nordix Foundation. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,6 +17,8 @@ # 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. +# +# SPDX-License-Identifier: Apache-2.0 # ============LICENSE_END============================================ # =================================================================== # @@ -180,6 +183,6 @@ clamp.config.tosca.converter.default.datatypes=classpath:/clds/tosca-converter/d clamp.config.tosca.converter.dictionary.support.enabled=true # Configuration settings for ControlLoop Runtime Rest API -clamp.config.controlloop.runtime.url=http://localhost:6969 +clamp.config.controlloop.runtime.url=http://localhost:${docker.http-cache.port.host} clamp.config.controlloop.runtime.userName=healthcheck clamp.config.controlloop.runtime.password=zb!XztG34 diff --git a/runtime/src/test/resources/http-cache/third_party_proxy.py b/runtime/src/test/resources/http-cache/third_party_proxy.py index 7fe316852..50bd43a35 100644 --- a/runtime/src/test/resources/http-cache/third_party_proxy.py +++ b/runtime/src/test/resources/http-cache/third_party_proxy.py @@ -5,6 +5,7 @@ # ================================================================================ # Copyright (C) 2018 AT&T Intellectual Property. All rights # reserved. +# Modifications Copyright (C) 2021 Nordix Foundation. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,6 +18,8 @@ # 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. +# +# SPDX-License-Identifier: Apache-2.0 # ============LICENSE_END============================================ # =================================================================== # @@ -94,23 +97,23 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): 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('<','<').replace('>','>').replace('?','?').replace('*','*').replace('\\','*').replace(':',':').replace('|','|') + cached_file_folder = cached_file_folder.replace('+','').replace('<','<').replace('>','>').replace('?','?').replace('*','*').replace('\\','*').replace(':',':').replace('|','|') 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..." @@ -120,7 +123,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): 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\"}") @@ -132,14 +135,14 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): print "self.path start with /dcae-operationstatus/install, generating response json..." jsonGenerated = "{\"operationType\": \"install\", \"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: @@ -150,14 +153,14 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): print "self.path start with /dcae-operationstatus/uninstall, generating response json..." jsonGenerated = "{\"operationType\": \"uninstall\", \"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: @@ -169,7 +172,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): 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\"}") @@ -187,7 +190,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") with open(cached_file_content, 'w+') as f: f.write(jsonGenerated) - return True + return True elif self.path.startswith("/dcae-deployments/") and http_type == "DELETE": print "self.path start with /dcae-deployments/ UNDEPLOY, generating response json..." #jsondata = json.loads(self.data_string) @@ -222,7 +225,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): print "self.path start with DELETE new policy API /policy/api/v1/policytypes/ ..." if not os.path.exists(cached_file_folder): os.makedirs(cached_file_folder, 0777) - + with open(cached_file_header, 'w+') as f: f.write("{\"Content-Length\": \"" + str(len("")) + "\", \"Content-Type\": \""+str("")+"\"}") with open(cached_file_content, 'w+') as f: @@ -265,10 +268,34 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): with open(cached_file_content, 'w') as f: f.write(response) return True + elif (self.path.startswith("/onap/controlloop/v2/commission/toscaservicetemplate")) and http_type == "GET": + if not _file_available: + cached_file_folder = cached_file_folder.split('bridgeEndpoint')[0] + print ("cached file folder for onap is %s: ", cached_file_folder) + print "self.path start with /onap/controlloop/v2/commission/, generating response json..." + jsonGenerated = "{\"tosca_definitions_version\": \"tosca_simple_yaml_1_1_0\",\"data_types\": {},\"node_types\": {}, \"policy_types\": {}, \"topology_template\": {}, \"name\": \"ToscaServiceTemplateSimple\", \"version\": \"1.0.0\", \"metadata\": {}}" + print "jsonGenerated: " + jsonGenerated + if not os.path.exists(cached_file_folder): + 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("/onap/controlloop/v2/commission")) and http_type == "POST": + print "self.path start with POST /onap/controlloop/v2/commission, copying body to response ..." + if not os.path.exists(cached_file_folder): + os.makedirs(cached_file_folder, 0777) + with open(cached_file_header, 'w+') as f: + f.write("{\"Content-Length\": \"" + str(len(self.data_string)) + "\", \"Content-Type\": \""+str(self.headers['Content-Type'])+"\"}") + with open(cached_file_content, 'w+') as f: + f.write(self.data_string) + return True else: return False - + def do_GET(self): cached_file_folder = "" cached_file_content ="" @@ -352,7 +379,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): _file_available = os.path.exists(cached_file_content) if not _file_available: - + if not HOST: self.send_response(404) self.end_headers() @@ -492,6 +519,6 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy) httpd.allow_reuse_address = True 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 +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 +httpd.serve_forever() |