From 9338362c1605a84a2b8e0a00ad1d65e14789bd6a Mon Sep 17 00:00:00 2001 From: Jennie Jia Date: Fri, 20 Jul 2018 21:23:51 +0000 Subject: Upstreaming the POMBA SDC Context Builder Issue-ID: LOG-522 Change-Id: Ic4606c987a8950ff3d19a8f42f330b08e3f4e4ca Signed-off-by: Jennie Jia --- .../onap/pomba/contextbuilder/sdc/Application.java | 44 +++++ .../contextbuilder/sdc/JerseyConfiguration.java | 68 ++++++++ .../contextbuilder/sdc/SDCClientConfiguration.java | 83 +++++++++ .../pomba/contextbuilder/sdc/SDCContextConfig.java | 175 +++++++++++++++++++ .../contextbuilder/sdc/ToscaBuilderConfig.java | 86 ++++++++++ .../pomba/contextbuilder/sdc/WebConfiguration.java | 44 +++++ .../sdc/exception/ToscaCsarException.java | 86 ++++++++++ .../contextbuilder/sdc/logging/LoggingUtil.java | 48 ++++++ .../contextbuilder/sdc/model/ArtifactInfo.java | 122 +++++++++++++ .../sdc/model/SDCContextRequest.java | 109 ++++++++++++ .../sdc/model/SDCContextResponse.java | 69 ++++++++ .../model/handlers/ToscaCsarArtifactHandler.java | 188 +++++++++++++++++++++ .../sdc/model/handlers/ToscaModelConverter.java | 147 ++++++++++++++++ .../contextbuilder/sdc/service/SpringService.java | 28 +++ .../sdc/service/SpringServiceImpl.java | 61 +++++++ .../contextbuilder/sdc/service/rs/RestService.java | 60 +++++++ .../sdc/service/rs/RestServiceImpl.java | 58 +++++++ 17 files changed, 1476 insertions(+) create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/Application.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/JerseyConfiguration.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/SDCClientConfiguration.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/SDCContextConfig.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/ToscaBuilderConfig.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/WebConfiguration.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/exception/ToscaCsarException.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/logging/LoggingUtil.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/model/ArtifactInfo.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextRequest.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextResponse.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaCsarArtifactHandler.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaModelConverter.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringService.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringServiceImpl.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestService.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestServiceImpl.java (limited to 'src/main/java') diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/Application.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/Application.java new file mode 100644 index 0000000..bd115b9 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/Application.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@ComponentScan(basePackages = {"org.onap.pomba.contextbuilder.sdc"}) +@EnableAsync +@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) +public class Application extends SpringBootServletInitializer { + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/JerseyConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/JerseyConfiguration.java new file mode 100644 index 0000000..08dabc2 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/JerseyConfiguration.java @@ -0,0 +1,68 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.util.logging.Logger; +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.logging.LoggingFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.servlet.ServletProperties; +import org.onap.pomba.contextbuilder.sdc.service.rs.RestServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +@Component +@ApplicationPath("/") +public class JerseyConfiguration extends ResourceConfig { + private static final Logger log = Logger.getLogger(JerseyConfiguration.class.getName()); + + @Bean + @Primary + public ObjectMapper objectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + return objectMapper; + } + + @Autowired + public JerseyConfiguration() { + register(RestServiceImpl.class); + property(ServletProperties.FILTER_FORWARD_ON_404, true); + register(new LoggingFeature(log)); + } + + @Bean + public Client jerseyClient() { + return ClientBuilder.newClient( + new ClientConfig()); + + } +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/SDCClientConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/SDCClientConfiguration.java new file mode 100644 index 0000000..51b5031 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/SDCClientConfiguration.java @@ -0,0 +1,83 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc; + +import java.util.Base64; +import lombok.Data; +import org.openecomp.sdc.http.SdcConnectorClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@Data +public class SDCClientConfiguration { + + @Autowired + @Value("${sdcConnect.username}") + private String username; + @Autowired + @Value("${sdcConnect.sdcAddress}") + private String sdcAddress; + @Autowired + @Value("${sdcConnect.password}") + private String password; + @Autowired + @Value("${sdcConnect.consumerID}") + private String consumerID; + @Autowired + @Value("${sdcConnect.timeout.seconds}") + private String pollingTimeout; + + @Autowired + @Value("${http.userId}") + private String httpUserId; + + @Autowired + @Value("${http.password}") + private String httpPassword; + + + @Bean(name="httpBasicAuthorization") + public String getHttpBasicAuth() { + String auth = new String(this.httpUserId + ":" + this.httpPassword); + + String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes()); + return ("Basic " + encodedAuth); + } + + + @Bean(name="client") + public SdcConnectorClient asdcConnectorClient(){ + SdcConnectorClient client = new SdcConnectorClient(); + SDCContextConfig sdcContextConfig = new SDCContextConfig(); + sdcContextConfig.setUser(username); + sdcContextConfig.setAsdcAddress(sdcAddress); + sdcContextConfig.setPassword(password); + sdcContextConfig.setUseHttpsWithDmaap(false); + sdcContextConfig.setConsumerId(consumerID); + sdcContextConfig.setActivateServerTLSAuth(false); + sdcContextConfig.setPollingTimeout(Integer.parseInt(pollingTimeout)); + + org.openecomp.sdc.impl.Configuration config = new org.openecomp.sdc.impl.Configuration(sdcContextConfig); + client.init(config); + + return client; + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/SDCContextConfig.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/SDCContextConfig.java new file mode 100644 index 0000000..e44ab0a --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/SDCContextConfig.java @@ -0,0 +1,175 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc; + +import java.util.List; +import org.openecomp.sdc.api.consumer.IConfiguration; + +public class SDCContextConfig implements IConfiguration { + + private String sdcAddress; + private String consumerID; + private String user; + private int pollingTimeout; + private String password; + private String environmentName; + private String keyStorePassword; + private List relevantArtifactTypes = null; + private int pollingInterval; + private String consumerGroup; + private String keyStorePath; + private boolean activateServerTLSAuth; + private boolean isFilterInEmptyResources; + private Boolean useHttpsWithDmaap; + private List msgBusAddress; + + + @Override + public List getMsgBusAddress() { + return msgBusAddress; + } + + public void setMsgBusAddress(List msgBusAddress) { + this.msgBusAddress = msgBusAddress; + } + + @Override + + public String getAsdcAddress() { + return sdcAddress; + } + + public void setAsdcAddress(String sdcAddress) { + this.sdcAddress = sdcAddress; + } + + public String getConsumerID() { + return consumerID; + } + + public void setConsumerId(String consumerId) { + this.consumerID = consumerId; + } + + @Override + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + @Override + public int getPollingTimeout() { + return pollingTimeout; + } + + public void setPollingTimeout(int pollingTimeout) { + this.pollingTimeout = pollingTimeout; + } + + @Override + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String getEnvironmentName() { + return environmentName; + } + + public void setEnvironmentName(String environmentName) { + this.environmentName = environmentName; + } + + @Override + public String getKeyStorePassword() { + return keyStorePassword; + } + + public void setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + } + + @Override + public List getRelevantArtifactTypes() { + return relevantArtifactTypes; + } + + public void setRelevantArtifactTypes(List relevantArtifactTypes) { + this.relevantArtifactTypes = relevantArtifactTypes; + } + + @Override + public int getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(int pollingInterval) { + this.pollingInterval = pollingInterval; + } + + @Override + public String getConsumerGroup() { + return consumerGroup; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + @Override + public String getKeyStorePath() { + return keyStorePath; + } + + public void setKeyStorePath(String keyStorePath) { + this.keyStorePath = keyStorePath; + } + + public boolean activateServerTLSAuth() { + return activateServerTLSAuth; + } + + public void setActivateServerTLSAuth(boolean activateServerTLSAuth) { + this.activateServerTLSAuth = activateServerTLSAuth; + } + + @Override + public boolean isFilterInEmptyResources() { + return isFilterInEmptyResources; + } + + public void setFilterInEmptyResources(boolean filterInEmptyResources) { + isFilterInEmptyResources = filterInEmptyResources; + } + + @Override + public Boolean isUseHttpsWithDmaap() { + return useHttpsWithDmaap; + } + + public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { + this.useHttpsWithDmaap = useHttpsWithDmaap; + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/ToscaBuilderConfig.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/ToscaBuilderConfig.java new file mode 100644 index 0000000..4c0a7e5 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/ToscaBuilderConfig.java @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc; + +import lombok.Data; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@Data +public class ToscaBuilderConfig { + + @Autowired + @Value("${sdc.artifact.type}") + private String artifactType; + + @Autowired + @Value("${sdc.url.template}") + private String urlTemplate; + + @Autowired + @Value("${sdc.csar.file.prefix}") + private String csarFilePrefix; + + @Autowired + @Value("${sdc.csar.file.suffix}") + private String csarFileSuffix; + + @Autowired(required=false) + @Value("${test.tosca.csar.file:}") + private String testToscaCsarFile; + + + @Bean(name="config") + public ToscaBuilderConfig config() { + return this; + } + + + public String getArtifactType() { + return artifactType; + } + + + public String getUrlTemplate() { + return urlTemplate; + } + + + public String getCsarFilePrefix() { + return csarFilePrefix; + } + + + public String getCsarFileSuffix() { + return csarFileSuffix; + } + + + public String getTestToscaCsarFile() { + return testToscaCsarFile; + } + + + public void setTestToscaCsarFile(String testToscaCsarFile) { + this.testToscaCsarFile = testToscaCsarFile; + } + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/WebConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/WebConfiguration.java new file mode 100644 index 0000000..db8511b --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/WebConfiguration.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class WebConfiguration { + + @Bean + public WebMvcConfigurerAdapter forwardToIndex() { + return new WebMvcConfigurerAdapter() { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/swagger").setViewName( + "redirect:/swagger/index.html"); + registry.addViewController("/swagger/").setViewName( + "redirect:/swagger/index.html"); + registry.addViewController("/docs").setViewName( + "redirect:/docs/html/index.html"); + registry.addViewController("/docs/").setViewName( + "redirect:/docs/html/index.html"); + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/exception/ToscaCsarException.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/exception/ToscaCsarException.java new file mode 100644 index 0000000..624ee58 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/exception/ToscaCsarException.java @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.exception; + +import javax.ws.rs.core.Response.Status; + +public class ToscaCsarException extends Exception { + + private static final long serialVersionUID = 1L; + private final String errorMessage; + private final Status httpStatus; + + /** + * Constructor for an instance of this exception with just a message. + * HTTP Status set to INTERNAL-SERVER-ERROR + * @param message information about the exception + */ + public ToscaCsarException(String message) { + super(message); + errorMessage = message; + httpStatus = Status.INTERNAL_SERVER_ERROR; + } + + /** + * Constructor for an instance of this exception with a message and status. + * @param httpStatus + * @param message + */ + public ToscaCsarException(Status httpStatus, String message) { + super(message); + this.errorMessage = message; + this.httpStatus = httpStatus; + } + + /** + * Constructor for an instance of this exception with a message and actual exception encountered. + * HTTP Status set to INTERNAL-SERVER-ERROR + * @param message information about the exception + * @param cause the actual exception that was encountered + */ + public ToscaCsarException(String message, Throwable cause) { + super(message, cause); + errorMessage = message; + httpStatus = Status.INTERNAL_SERVER_ERROR; + } + + /** + * Constructor for an instance of this exception with a message, status and actual exception encountered. + * @param httpStatus + * @param message + * @param cause + */ + public ToscaCsarException(Status httpStatus, String message, Throwable cause) { + super(message, cause); + this.errorMessage = message; + this.httpStatus = httpStatus; + } + + public Status getStatus() { + return httpStatus; + } + + @Override + public String getMessage() { + String fullMessage = errorMessage; + if(getCause() != null) { + fullMessage += ": " + getCause().getMessage(); + } + return fullMessage; + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/logging/LoggingUtil.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/logging/LoggingUtil.java new file mode 100644 index 0000000..067bc2c --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/logging/LoggingUtil.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.logging; + +import org.onap.aai.cl.mdc.MdcContext; +import org.slf4j.MDC; + +public class LoggingUtil { + + private static final String APP_NAME = "Pomba SDC ContextBuilder"; + + private LoggingUtil() { + + } + + /** + * Initializes MDC context. + * Called when request processing begins. + * @param httpReq + * @param headers + */ + public static void initMdc(String transactionId, String fromAppId, String remoteAddr) { + MdcContext.initialize(transactionId, APP_NAME, "", fromAppId, remoteAddr); + } + + /** + * Clears the MDC context. + * Called when request processing ends. + */ + public static void closeMdc() { + MDC.clear(); + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/model/ArtifactInfo.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/ArtifactInfo.java new file mode 100644 index 0000000..8e3d179 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/ArtifactInfo.java @@ -0,0 +1,122 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.model; + +import java.util.List; +import lombok.Data; +import lombok.ToString; +import org.openecomp.sdc.api.notification.IArtifactInfo; + +@Data +@ToString(includeFieldNames = true) +public class ArtifactInfo implements IArtifactInfo { + + private String artifactName; + private String artifactType; + private String artifactDescription; + private String artifactVersion; + private String artifactURL; + private String artifactChecksum; + private Integer artifactTimeout; + private String artifactUUID; + private IArtifactInfo generatedArtifact; + private List relatedArtifactsInfo; + + public IArtifactInfo getGeneratedArtifact() { + return generatedArtifact; + } + + public void setGeneratedArtifact(IArtifactInfo generatedArtifact) { + this.generatedArtifact = generatedArtifact; + } + + public List getRelatedArtifacts() { + return relatedArtifactsInfo; + } + + public void setRelatedArtifacts(List relatedArtifactsInfo) { + this.relatedArtifactsInfo = relatedArtifactsInfo; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public Integer getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(Integer artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + + +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextRequest.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextRequest.java new file mode 100644 index 0000000..9ba6197 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextRequest.java @@ -0,0 +1,109 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.model; + +import javax.ws.rs.core.Response.Status; +import org.onap.pomba.contextbuilder.sdc.exception.ToscaCsarException; + +public class SDCContextRequest { + + private String remoteAddr; + private String fromAppId; + private String transactionId; + private String serviceInstanceId; + private String modelVersionId; + private String modelInvariantId; + private String authorization; + + + public SDCContextRequest(String remoteAddr, String authorization, String fromAppId, String transactionId, + String serviceInstanceId, String modelVersionId, String modelInvariantId) { + this.remoteAddr = remoteAddr; + this.authorization = authorization; + this.fromAppId = fromAppId; + this.transactionId = transactionId; + this.serviceInstanceId = serviceInstanceId; + this.modelVersionId = modelVersionId; + this.modelInvariantId = modelInvariantId; + + } + + + public String getAuthorization() { + return authorization; + } + + + public void setAuthorization(String authorization) { + this.authorization = authorization; + } + + + public String getRemoteAddr() { + return remoteAddr; + } + + public String getFromAppId() { + return fromAppId; + } + + public String getTransactionId() { + return transactionId; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void validate(String httpBasicAuthorization) throws ToscaCsarException { + + // validation on HTTP Authorization Header + if (authorization != null && !authorization.trim().isEmpty() && authorization.startsWith("Basic")) { + if (!authorization.equals(httpBasicAuthorization)) { + throw new ToscaCsarException(Status.UNAUTHORIZED, "Authorization Failed due to mismatch basic auth username or password"); + }; + } else { + throw new ToscaCsarException(Status.UNAUTHORIZED, "Missing Authorization header"); + } + + if((fromAppId == null) || fromAppId.isEmpty()) { + throw new ToscaCsarException(Status.BAD_REQUEST, "Missing mandatory header parameter: X-FromAppId"); + } + if((transactionId == null) || transactionId.isEmpty()) { + throw new ToscaCsarException(Status.BAD_REQUEST, "Missing mandatory header parameter: X-TransactionId"); + } + if((modelVersionId == null) || modelVersionId.isEmpty()) { + throw new ToscaCsarException(Status.BAD_REQUEST, "Missing mandatory parameter: modelVersionId"); + } + } + + @Override + public String toString() { + return "SDCContextRequest [remoteAddr=" + remoteAddr + ", authorization=" + authorization + ", fromAppId=" + fromAppId + ", transactionId=" + + transactionId + ", serviceInstanceId=" + serviceInstanceId + ", modelVersionId=" + modelVersionId + + ", modelInvariantId=" + modelInvariantId + "]"; + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextResponse.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextResponse.java new file mode 100644 index 0000000..156874f --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/SDCContextResponse.java @@ -0,0 +1,69 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.model; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +public class SDCContextResponse { + + private String payload; + private Status httpStatus = Status.OK; + private String mediaType = MediaType.APPLICATION_JSON; + + /** + * Instantiates with HTTP Status set to OK and MediaType set to APPLICATION-JSON + */ + public SDCContextResponse() { + // Intentionally empty + } + + /** + * This constructor is meant to be used when an error is encountered. + * MediaType is set to TEXT-PLAIN for the error message. + * @param httpStatus + * @param errorMessage + */ + public SDCContextResponse(Status httpStatus, String errorMessage) { + this.httpStatus = httpStatus; + this.payload = errorMessage; + this.mediaType = MediaType.TEXT_PLAIN; + } + + public String getModelData() { + return payload; + } + + public void setModelData(String modelData) { + this.payload = modelData; + } + + public Status getHttpStatus() { + return httpStatus; + } + + public void setHttpStatus(Status httpStatus) { + this.httpStatus = httpStatus; + } + + public Response buildResponse() { + return Response.status(httpStatus).entity(payload).type(mediaType).build(); + } + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaCsarArtifactHandler.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaCsarArtifactHandler.java new file mode 100644 index 0000000..14079a8 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaCsarArtifactHandler.java @@ -0,0 +1,188 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.model.handlers; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import groovy.util.logging.Slf4j; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; +import org.onap.pomba.contextbuilder.sdc.ToscaBuilderConfig; +import org.onap.pomba.contextbuilder.sdc.exception.ToscaCsarException; +import org.onap.pomba.contextbuilder.sdc.model.ArtifactInfo; +import org.onap.pomba.contextbuilder.sdc.model.SDCContextResponse; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; +import org.openecomp.sdc.http.SdcConnectorClient; +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.openecomp.sdc.utils.DistributionActionResultEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Slf4j +@Component("ToscaCsarArtifactHandler") +public class ToscaCsarArtifactHandler { + + private static final String DEFAULT_CSAR_FILE_EXTENSION = ".zip"; + + private static Logger log = LoggerFactory.getLogger(ToscaCsarArtifactHandler.class); + + private Map sdcCsarHelpers = new HashMap<>(); + + @Autowired + private SdcConnectorClient client; + @Autowired + private ToscaBuilderConfig config; + + + /** + * Retrieves a subset of the TOSCA model for the given version ID. + * If the model is not cached, a request to download the CSAR file is sent to SDC. + * @param modelVersionId + * @return Response containing a subset of the model data + * @throws ToscaCsarException + */ + public SDCContextResponse getToscaModel(String modelVersionId) throws ToscaCsarException { + + ISdcCsarHelper helper = sdcCsarHelpers.get(modelVersionId); + if(helper == null) { + log.debug("No CSAR file cached for " + modelVersionId); + helper = retrieveToscaCsarArtifact(modelVersionId); + if(helper != null) { + sdcCsarHelpers.put(modelVersionId, helper); + } + } + + SDCContextResponse response = new SDCContextResponse(); + + if(helper == null) { + log.debug("CSAR artifact not found for model-version-id: " + modelVersionId); + response.setModelData(""); + return response; + } + + Gson gson = new GsonBuilder().create(); + String modelData = gson.toJson(ToscaModelConverter.convert(helper)); + response.setModelData(modelData); + return response; + } + + + /** + * Retrieves the CSAR file from SDC for the given model version ID + * @param modelVersionId + * @return Returns NULL if CSAR file couldn't be retrieved + * @throws ToscaCsarException + */ + private ISdcCsarHelper retrieveToscaCsarArtifact(String modelVersionId) throws ToscaCsarException { + + if (config.getTestToscaCsarFile() != null && !config.getTestToscaCsarFile().isEmpty()) { + return getSdcToscaContext(config.getTestToscaCsarFile()); + } + + String url = generateURL(modelVersionId); + log.debug("Downloading CSAR using URL suffix: " + url); + + ArtifactInfo artifact = new ArtifactInfo(); + artifact.setArtifactType(config.getArtifactType()); + artifact.setArtifactURL(url); + artifact.setArtifactChecksum("value_not_used_by_sdc_distribution_client_lib"); + + String csarFile = generateTemporaryFile(modelVersionId); + try (OutputStream outputStream = Files.newOutputStream(Paths.get(csarFile), StandardOpenOption.CREATE);) { + IDistributionClientDownloadResult downloadResult = client.dowloadArtifact(artifact); + if (downloadResult.getDistributionActionResult() == DistributionActionResultEnum.ARTIFACT_NOT_FOUND) { + log.debug("Failed to retrieve CSAR artifact from SDC: " + downloadResult.getDistributionMessageResult()); + return null; + } else if (downloadResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { + throw new ToscaCsarException("Failed to retrieve CSAR artifact from SDC: " + downloadResult.getDistributionMessageResult()); + } + + byte[] payload = downloadResult.getArtifactPayload(); + if ((payload == null) || (payload.length == 0)) { + log.debug("Retrieved CSAR payload is empty"); + return null; + } + outputStream.write(payload); + } catch (IOException e){ + throw new ToscaCsarException("Failed to write temporary CSAR file '" + csarFile + "'", e); + } + + ISdcCsarHelper helper = getSdcToscaContext(csarFile); + try { + Files.delete(Paths.get(csarFile)); + } catch (IOException e) { + log.error("Failed to delete temporary CSAR file '" + csarFile + "': " + e.getMessage()); + } + return helper; + } + + + private String generateURL(String uuid) { + return MessageFormat.format(config.getUrlTemplate(), uuid); + } + + + /** + * Creates a temporary file for downloaded CSAR file + * @param uuid + * @return + * @throws ToscaCsarException + */ + private String generateTemporaryFile(String uuid) throws ToscaCsarException { + try { + String fullPrefix = config.getCsarFilePrefix() + uuid + "-"; + String suffix = (config.getCsarFileSuffix() == null ? DEFAULT_CSAR_FILE_EXTENSION : config.getCsarFileSuffix()); + Path downloadFile = Files.createTempFile(fullPrefix, suffix); + log.debug("Temporary CSAR file name: " + downloadFile.toString()); + return downloadFile.toString(); + } catch (IOException e) { + throw new ToscaCsarException("Failed to create temporary CSAR file: " + e.getMessage()); + } + } + + + /** + * Parses a CSAR file + * @param csarFile + * @return + * @throws ToscaCsarException + */ + private ISdcCsarHelper getSdcToscaContext(String csarFile) throws ToscaCsarException { + + log.info("Loading and parsing SDC csar file ..."); + try { + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + return factory.getSdcCsarHelper(csarFile); + } catch (SdcToscaParserException e) { + throw new ToscaCsarException("Failed to parse CSAR file", e); + } + } + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaModelConverter.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaModelConverter.java new file mode 100644 index 0000000..ba6a37b --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/model/handlers/ToscaModelConverter.java @@ -0,0 +1,147 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.model.handlers; + +import java.util.ArrayList; +import java.util.List; +import org.onap.pomba.common.datatypes.ModelContext; +import org.onap.pomba.common.datatypes.Service; +import org.onap.pomba.common.datatypes.VF; +import org.onap.pomba.common.datatypes.VFModule; +import org.onap.pomba.common.datatypes.VNFC; +import org.onap.pomba.contextbuilder.sdc.exception.ToscaCsarException; +import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper; +import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames; +import org.openecomp.sdc.toscaparser.api.Group; +import org.openecomp.sdc.toscaparser.api.NodeTemplate; +import org.openecomp.sdc.toscaparser.api.elements.Metadata; + +public class ToscaModelConverter { + + private static final String PROPERTY_NAME_NFC_NAMING_CODE = "nfc_naming_code"; + + private ToscaModelConverter() { + + } + + /** + * Conversion from SDC model to the common model + * @param helper + * @return + * @throws ToscaCsarException + */ + public static ModelContext convert(ISdcCsarHelper helper) throws ToscaCsarException { + ModelContext context = new ModelContext(); + context.setService(generateService(helper.getServiceMetadata())); + context.setVf(generateVfList(helper)); + return context; + } + + /** + * Instantiates a service based on the SDC Service metadata + * @param serviceMetadata + * @return + * @throws ToscaCsarException + */ + private static Service generateService(Metadata serviceMetadata) throws ToscaCsarException { + Service service = new Service(); + if (serviceMetadata != null) { + service.setName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + service.setInvariantUuid(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + service.setUuid(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + } + return service; + } + + /** + * Generates a list of VFs from the SDC VF-Resources + * @param helper + * @return + * @throws ToscaCsarException + */ + private static List generateVfList(ISdcCsarHelper helper) throws ToscaCsarException { + + List vfList = new ArrayList<>(); + List vfNodeTemplateList = helper.getServiceVfList(); + for (NodeTemplate vfNodeTemplate : vfNodeTemplateList) { + VF vf = new VF(); + vf.setName(vfNodeTemplate.getName()); + vf.setType(vfNodeTemplate.getType()); + vf.setInvariantUuid(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + vf.setUuid(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + String customizationUUID = vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + vf.setVnfc(generateVnfcList(helper.getVfcListByVf(customizationUUID))); + vf.setVfModules(generateVfModuleList(helper.getVfModulesByVf(customizationUUID))); + + vfList.add(vf); + } + return vfList; + } + + /** + * Generates a list of VFNCs from the SDC VF-Resources's VNFCs + * @param vfcNodeTemplateList + * @return + * @throws ToscaCsarException + */ + private static List generateVnfcList(List vfcNodeTemplateList) throws ToscaCsarException { + List vnfcList = new ArrayList<>(); + for (NodeTemplate vfcNodeTemplate : vfcNodeTemplateList) { + VNFC vnfc = new VNFC(); + vnfc.setName(vfcNodeTemplate.getName()); + vnfc.setInvariantUuid(vfcNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + vnfc.setUuid(vfcNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + Object nfcNamingCode = vfcNodeTemplate.getPropertyValue(PROPERTY_NAME_NFC_NAMING_CODE); + if (nfcNamingCode != null) { + vnfc.setNfcNamingCode((String)nfcNamingCode); + } + + vnfcList.add(vnfc); + } + return vnfcList; + } + + /** + * Generates a list of VFModules from the SDC VF-Resource's VF-Modules + * @param vfModuleGroupList + * @return + * @throws ToscaCsarException + */ + private static List generateVfModuleList(List vfModuleGroupList) throws ToscaCsarException { + List vfModuleList = new ArrayList<>(); + for (Group moduleGroup : vfModuleGroupList) { + VFModule vfModule = new VFModule(); + vfModule.setInvariantUuid(moduleGroup.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)); + vfModule.setUuid(moduleGroup.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); + + Object minInstances = moduleGroup.getPropertyValue(SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES); + if (minInstances != null) { + vfModule.setMinInstances((Integer)minInstances); + } + Object maxInstances = moduleGroup.getPropertyValue(SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES); + if (maxInstances != null) { + vfModule.setMaxInstances((Integer)maxInstances); + } + + vfModuleList.add(vfModule); + } + return vfModuleList; + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringService.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringService.java new file mode 100644 index 0000000..f6dec5c --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringService.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.service; + +import org.onap.pomba.contextbuilder.sdc.exception.ToscaCsarException; +import org.onap.pomba.contextbuilder.sdc.model.SDCContextRequest; +import org.onap.pomba.contextbuilder.sdc.model.SDCContextResponse; + +public interface SpringService { + + public SDCContextResponse getModelData (SDCContextRequest sdcContext) throws ToscaCsarException; + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringServiceImpl.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringServiceImpl.java new file mode 100644 index 0000000..1ef7fd0 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/SpringServiceImpl.java @@ -0,0 +1,61 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.service; + +import org.onap.pomba.contextbuilder.sdc.exception.ToscaCsarException; +import org.onap.pomba.contextbuilder.sdc.logging.LoggingUtil; +import org.onap.pomba.contextbuilder.sdc.model.SDCContextRequest; +import org.onap.pomba.contextbuilder.sdc.model.SDCContextResponse; +import org.onap.pomba.contextbuilder.sdc.model.handlers.ToscaCsarArtifactHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class SpringServiceImpl implements SpringService { + + private static Logger log = LoggerFactory.getLogger(SpringService.class); + + + @Autowired + protected ToscaCsarArtifactHandler toscaCsarArtifactHandler; + + @Autowired + private String httpBasicAuthorization; + + @Override + public SDCContextResponse getModelData(SDCContextRequest ctxRequest) throws ToscaCsarException { + + LoggingUtil.initMdc(ctxRequest.getTransactionId(), ctxRequest.getFromAppId(), ctxRequest.getRemoteAddr()); + SDCContextResponse sdcContextResponse = null; + try { + ctxRequest.validate(httpBasicAuthorization); + sdcContextResponse = toscaCsarArtifactHandler.getToscaModel(ctxRequest.getModelVersionId()); + } catch (ToscaCsarException e) { + log.error(e.getStatus().getStatusCode() + " " + e.getStatus()+ ", Reason: " + e.getMessage()); + sdcContextResponse = new SDCContextResponse(e.getStatus(), e.getMessage()); + } finally { + LoggingUtil.closeMdc(); + } + return sdcContextResponse; + + } + + +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestService.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestService.java new file mode 100644 index 0000000..ea0ae0d --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestService.java @@ -0,0 +1,60 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.service.rs; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.pomba.contextbuilder.sdc.exception.ToscaCsarException; + + +@Api +@Path("/service") +@Produces({MediaType.APPLICATION_JSON}) +public interface RestService { + + + @GET + @Path("/context") + @Produces({ MediaType.APPLICATION_JSON }) + @ApiOperation( + value = "Retrieve SDC CSAR file for a give UUID", + notes = "This method returns SDC CSAR encoded value. ", + response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Service not available"), + @ApiResponse(code = 400, message = "Bad request"), + @ApiResponse(code = 401, message = "Unauthorized"), + @ApiResponse(code = 500, message = "Unexpected Runtime error") }) + public Response getContext( + @HeaderParam("Authorization") String authorization, + @HeaderParam("X-FromAppId") String xFromAppId, + @HeaderParam("X-TransactionId") String xTransactionId, + @QueryParam("serviceInstanceId") String serviceInstanceId, + @QueryParam("modelVersionId") String modelVersionId, + @QueryParam("modelInvariantId") String modelInvariantId + ) throws ToscaCsarException; +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestServiceImpl.java b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestServiceImpl.java new file mode 100644 index 0000000..2c3293e --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdc/service/rs/RestServiceImpl.java @@ -0,0 +1,58 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * 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.pomba.contextbuilder.sdc.service.rs; + + +import java.util.UUID; +import javax.ws.rs.core.Response; + +import org.onap.pomba.contextbuilder.sdc.exception.ToscaCsarException; +import org.onap.pomba.contextbuilder.sdc.model.SDCContextRequest; +import org.onap.pomba.contextbuilder.sdc.model.SDCContextResponse; +import org.onap.pomba.contextbuilder.sdc.service.SpringService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class RestServiceImpl implements RestService { + private static Logger log = LoggerFactory.getLogger(RestService.class); + + @Autowired + private SpringService service; + + public RestServiceImpl() { + + } + + @Override + public Response getContext(String authorization, String xFromAppId, String xTransactionId, String serviceInstanceId, + String modelVersionId, String modelInvariantId) throws ToscaCsarException { + + if (xTransactionId == null || xTransactionId.isEmpty()) { + xTransactionId = UUID.randomUUID().toString(); + log.debug("X-TransactionId is missing; using newly generated value: " + xTransactionId); + } + SDCContextRequest sdcContext = new SDCContextRequest(null, authorization, xFromAppId, xTransactionId, + serviceInstanceId, modelVersionId, modelInvariantId); + SDCContextResponse sdcContextResponse = service.getModelData(sdcContext); + return sdcContextResponse.buildResponse(); + } + +} -- cgit 1.2.3-korg