From a2423cf3ba54da34bb865befd44d56bbb925a94b Mon Sep 17 00:00:00 2001 From: "Tait,Trevor(rt0435)" Date: Wed, 3 Oct 2018 15:08:34 -0400 Subject: POMBA: SDNC Context Builder Initial code for POMBA: SDNC Context Builder Issue-ID: LOG-520 Change-Id: I6b06561b9050acc83b0c2b18b21c94f0f13f63e4 Signed-off-by: Tait,Trevor(rt0435) --- src/main/java/META-INF/MANIFEST.MF | 3 + .../pomba/contextbuilder/sdnc/Application.java | 53 ++++++++ .../contextbuilder/sdnc/JerseyConfiguration.java | 71 ++++++++++ .../contextbuilder/sdnc/SdncConfiguration.java | 74 ++++++++++ .../contextbuilder/sdnc/SdncCtxbConfiguration.java | 41 ++++++ .../contextbuilder/sdnc/WebConfiguration.java | 45 +++++++ .../sdnc/exception/AuditException.java | 46 +++++++ .../contextbuilder/sdnc/service/SpringService.java | 28 ++++ .../sdnc/service/SpringServiceImpl.java | 74 ++++++++++ .../sdnc/service/rs/RestService.java | 58 ++++++++ .../sdnc/service/rs/RestServiceImpl.java | 81 +++++++++++ .../pomba/contextbuilder/sdnc/util/RestUtil.java | 150 +++++++++++++++++++++ 12 files changed, 724 insertions(+) create mode 100644 src/main/java/META-INF/MANIFEST.MF create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/JerseyConfiguration.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncConfiguration.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncCtxbConfiguration.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/WebConfiguration.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/exception/AuditException.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringService.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestService.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestServiceImpl.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java (limited to 'src/main/java') diff --git a/src/main/java/META-INF/MANIFEST.MF b/src/main/java/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/src/main/java/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java new file mode 100644 index 0000000..e0ebfc8 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java @@ -0,0 +1,53 @@ +/* + * ============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.sdnc; + +import org.apache.velocity.app.VelocityEngine; +import org.springframework.boot.SpringApplication; +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.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@ComponentScan(basePackages = "org.onap.pomba.contextbuilder.sdnc") +@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) { + SpringApplication.run(Application.class, args); + } + + @Bean + public VelocityEngine velocityEngine() { + VelocityEngine velocityEngine = new VelocityEngine(); + velocityEngine.init(); + return velocityEngine; + } +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/JerseyConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/JerseyConfiguration.java new file mode 100644 index 0000000..3f73644 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/JerseyConfiguration.java @@ -0,0 +1,71 @@ +/* + * ============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.sdnc; + +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.sdnc.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; + +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; + +@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/sdnc/SdncConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncConfiguration.java new file mode 100644 index 0000000..ec5c8b3 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncConfiguration.java @@ -0,0 +1,74 @@ +/* + * ============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.sdnc; + +import java.util.Base64; +import javax.ws.rs.ApplicationPath; +import org.eclipse.jetty.util.security.Password; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + + +@Component +@ApplicationPath("/") +public class SdncConfiguration { + + @Value("${sdnc.serviceName}") + private String serviceName; + + @Value("${sdnc.servicePort}") + private String servicePort; + + @Value("${sdnc.httpProtocol}") + private String httpProtocol; + + @Value("${sdnc.user}") + private String user; + + @Value("${sdnc.password}") + private String password; + + @Value("${sdnc.connectionTimeout}") + private Integer connectionTimeout; + + @Value("${sdnc.readTimeout}") + private Integer readTimeout; + + @Value("${sdnc.genericResourcePath}") + private String genericResourcePath; + + @Bean(name="sdncBaseUrl") + public String getURL() { + return httpProtocol + "://" + serviceName + ":" + servicePort; + } + + @Bean(name="sdncGenericResourcePath") + public String getgenericResourcePath() { + return genericResourcePath; + } + + @Bean(name = "sdncBasicAuthorization") + public String getSdncBasicAuth() { + String auth = this.user + ":"+ Password.deobfuscate(this.password); + return ("Basic " + Base64.getEncoder().encodeToString(auth.getBytes())); + } + + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncCtxbConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncCtxbConfiguration.java new file mode 100644 index 0000000..7268d4b --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncCtxbConfiguration.java @@ -0,0 +1,41 @@ +/* + * ============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.sdnc; + +import java.util.Base64; +import org.eclipse.jetty.util.security.Password; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + +@Component +public class SdncCtxbConfiguration { + @Value("${sdncCtxBuilder.userId:admin}") + private String sdncCtxBuilderUserId; + + @Value("${sdncCtxBuilder.password:OBF:1u2a1toa1w8v1tok1u30}") + private String sdncCtxBuilderPassword; + + @Bean(name = "sdncCtxBuilderBasicAuthorization") + public String getSdncBasicAuth() { + String auth = this.sdncCtxBuilderUserId + ":" + + Password.deobfuscate(this.sdncCtxBuilderPassword); + return ("Basic " + Base64.getEncoder().encodeToString(auth.getBytes())); + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/WebConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/WebConfiguration.java new file mode 100644 index 0000000..c49ff24 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/WebConfiguration.java @@ -0,0 +1,45 @@ +/* + * ============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.sdnc; + +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/sdnc/exception/AuditException.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/exception/AuditException.java new file mode 100644 index 0000000..63137a1 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/exception/AuditException.java @@ -0,0 +1,46 @@ +/* + * ============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.sdnc.exception; + +import javax.ws.rs.core.Response.Status; + +public class AuditException extends Exception { + + private static final long serialVersionUID = 8162385108397238865L; + + private Status httpStatus; + + + public AuditException(String message) { + super(message); + } + + public AuditException(String message, Status httpStatus) { + super(message); + this.setHttpStatus(httpStatus); + } + + public Status getHttpStatus() { + return httpStatus; + } + + public void setHttpStatus(Status httpStatus) { + this.httpStatus = httpStatus; + } +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringService.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringService.java new file mode 100644 index 0000000..6ead761 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/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.sdnc.service; + + +import org.onap.pomba.common.datatypes.ModelContext; +import org.onap.pomba.contextbuilder.sdnc.exception.AuditException; + +public interface SpringService { + public ModelContext getContext(String serviceInstanceId, String transactionId) throws AuditException; + public String getSdncAuthoriztion(); +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java new file mode 100644 index 0000000..daf6bf8 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java @@ -0,0 +1,74 @@ +/* + * ============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.sdnc.service; + +import javax.ws.rs.client.Client; +import org.onap.pomba.common.datatypes.ModelContext; +import org.onap.pomba.contextbuilder.sdnc.exception.AuditException; +import org.onap.pomba.contextbuilder.sdnc.service.rs.RestService; +import org.onap.pomba.contextbuilder.sdnc.util.RestUtil; +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(RestService.class); + + @Autowired + private Client jerseyClient; + @Autowired + private String sdncBaseUrl; + @Autowired + private String sdncBasicAuthorization; + @Autowired + private String sdncGenericResourcePath; + @Autowired + private String sdncCtxBuilderBasicAuthorization; + + public SpringServiceImpl() { + // needed for instantiation + } + + + @Override + public ModelContext getContext(String serviceInstanceId, String transactionId) throws AuditException { + ModelContext context = null; + String url = "serviceInstanceId=" + serviceInstanceId + " transactionId=" + transactionId; + log.info("URL Query the SDN-C model data with URL: " , url); + + // Retrieve the service instance information from SDNC and AAI + try { + String sdncResponse = RestUtil.getSdncGenericResource(jerseyClient, sdncBaseUrl, sdncBasicAuthorization, sdncGenericResourcePath, serviceInstanceId); + log.info("sdncResponse: ", sdncResponse); + context = RestUtil.transform(sdncResponse); + } catch (AuditException ae) { + throw ae; + } catch (Exception e) { + throw new AuditException(e.getLocalizedMessage()); + } + return context; + } + + public String getSdncAuthoriztion() { + return sdncCtxBuilderBasicAuthorization; + } + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestService.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestService.java new file mode 100644 index 0000000..ec1581a --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestService.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.sdnc.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.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + + +@Api +@Path("/service") +@Produces({MediaType.APPLICATION_JSON}) +public interface RestService { + + @GET + @Path("/context") + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation( + value = "Respond SDNCContext Model Data", + notes = "Returns a JSON object which represents the SDNCConetxt model data", + response = Response.class + ) + @ApiResponses( + value = { + @ApiResponse(code = 200, message = "OK"), + @ApiResponse(code = 400, message = "Bad Request"), + @ApiResponse(code = 404, message = "Service not available"), + @ApiResponse(code = 500, message = "Unexpected Runtime error") + }) + public Response getContext(@Context HttpHeaders headers, + @QueryParam("serviceInstanceId") String serviceInstanceId + ); +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestServiceImpl.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestServiceImpl.java new file mode 100644 index 0000000..d3b6378 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/rs/RestServiceImpl.java @@ -0,0 +1,81 @@ +/* + * ============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.sdnc.service.rs; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.onap.pomba.common.datatypes.ModelContext; +import org.onap.pomba.contextbuilder.sdnc.exception.AuditException; +import org.onap.pomba.contextbuilder.sdnc.service.SpringService; +import org.onap.pomba.contextbuilder.sdnc.util.RestUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + + +@Component +public class RestServiceImpl implements RestService { + private static final String EMPTY_JSON_STRING = "{}"; + + @Autowired + private SpringService service; + + + public RestServiceImpl() throws UnsupportedOperationException{ + } + + @Override + public Response getContext(HttpHeaders headers, String serviceInstanceId) { + + Response response = null; + ModelContext sdncContext= null; + Gson gson = new GsonBuilder().create(); + try { + // Do some validation on Http headers and URL parameters + RestUtil.validateHeader(headers, service.getSdncAuthoriztion()); + RestUtil.validateURL(serviceInstanceId); + + // Keep the same transaction id for logging purposeString transactionId + String transactionId = RestUtil.extractTranIdHeader(headers); + + sdncContext = service.getContext(serviceInstanceId, transactionId); + + if (sdncContext==null) { + // Return empty JSON + response = Response.ok().entity(EMPTY_JSON_STRING).build(); + }else { + response = Response.ok().entity(gson.toJson(sdncContext)).build(); + } + } catch (AuditException ce) { + if (ce.getHttpStatus() !=null) { + response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build(); + }else { + // No response received, could be the cases of network issue: i.e. unreachable host + response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(ce.getMessage()).build(); + } + } catch (Exception e) { + response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + + return response; + } + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java new file mode 100644 index 0000000..806514c --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java @@ -0,0 +1,150 @@ +/* + * ============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.sdnc.util; + +import com.bazaarvoice.jolt.Chainr; +import com.bazaarvoice.jolt.JsonUtils; +import com.google.gson.Gson; +import java.text.MessageFormat; +import java.util.List; +import java.util.UUID; +import javax.ws.rs.client.Client; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.json.JSONObject; +import org.onap.pomba.common.datatypes.ModelContext; +import org.onap.pomba.contextbuilder.sdnc.exception.AuditException; +import org.onap.pomba.contextbuilder.sdnc.service.rs.RestService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RestUtil { + + private static Logger log = LoggerFactory.getLogger(RestService.class); + + public static final String INTERNAL_SERVER_ERROR = "Internal Server Error"; + + // HTTP headers + public static final String TRANSACTION_ID = "X-TransactionId"; + public static final String FROM_APP_ID = "X-FromAppId"; + public static final String AUTHORIZATION = "Authorization"; + + // Parameters for Query SDNC Model Data REST API URL + private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; + + private RestUtil() { + } + + /** + * Validates the URL parameter. + * @throws AuditException if there is missing parameter + */ + public static void validateURL(String serviceInstanceId) throws AuditException { + + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) + throw new AuditException("Invalid request URL, missing parameter: "+ SERVICE_INSTANCE_ID, Status.BAD_REQUEST); + } + + + public static void validateHeader(HttpHeaders headers, String sdncCtxBuilderBasicAuthorization) throws AuditException { + + String fromAppId = headers.getRequestHeaders().getFirst(FROM_APP_ID); + if((fromAppId == null) || fromAppId.trim().isEmpty()) { + throw new AuditException("Missing header parameter: "+ FROM_APP_ID, Status.BAD_REQUEST); + } + + String headerAuthorization = headers.getRequestHeaders().getFirst(AUTHORIZATION); + if((headerAuthorization == null) || headerAuthorization.trim().isEmpty()) { + throw new AuditException("Missing header parameter: "+ AUTHORIZATION, Status.BAD_REQUEST); + } + if((!headerAuthorization.contentEquals(sdncCtxBuilderBasicAuthorization))) { + throw new AuditException("Failed Basic "+ AUTHORIZATION, Status.UNAUTHORIZED); + } + } + + + /* + * The purpose is to keep same transaction Id from north bound interface to south bound interface + */ + public static String extractTranIdHeader(HttpHeaders headers) { + String transactionId = null; + transactionId = headers.getRequestHeaders().getFirst(TRANSACTION_ID); + if((transactionId == null) || transactionId.trim().isEmpty()) { + transactionId = UUID.randomUUID().toString(); + log.info("Header ", TRANSACTION_ID, " not present in request, generating new value: ", transactionId); + } + return transactionId; + } + + + /** + * For each AAI VnfInstance, use the AAI VfModuleId to make a rest call to SDNC VNF-API to create a list of all SDNC Vnfs. + * The URL for VNF-API is https://:8543/restconf/config/VNF-API:vnfs/vnf-list/ + * @param sdncClient + * @param sdncBaseUrl + * @param authorization + * @param sdncGenericResourcePath + * @param serviceInstaceId + * @return + * @throws AuditException + */ + public static String getSdncGenericResource(Client sdncClient, String sdncBaseUrl, String authorization, String sdncGenericResourcePath, + String serviceInstaceId) throws AuditException { + String vnfSdncURL = sdncBaseUrl+generateSdncInstanceURL(sdncGenericResourcePath, serviceInstaceId); + // send rest request to SDNC VNF-API + return getSdncResource(sdncClient, vnfSdncURL, authorization); + } + + + public static ModelContext transform(String sdncResponse) { + List jsonSpec = JsonUtils.filepathToList("config/sdnccontextbuilder.spec"); + Object jsonInput = JsonUtils.jsonToObject(sdncResponse); + Chainr chainr = Chainr.fromSpec(jsonSpec); + Object transObject = chainr.transform(jsonInput); + Gson gson = new Gson(); + return gson.fromJson(JsonUtils.toPrettyJsonString(transObject), ModelContext.class); + + } + + + private static String getSdncResource(Client sdncClient, String url, String authorization) throws AuditException { + + Response response = sdncClient.target(url).request() + .header("Accept", "application/json") + .header(AUTHORIZATION, authorization).get(); + + if (response.getStatus() == 200) { + return response.readEntity(String.class); + } else if (response.getStatus() == 404) { + //Resource not found, generate empty JSON format + log.info("Return empty Json. Resource not found: ", url); + return new JSONObject().toString(); + + } else { + throw new AuditException(INTERNAL_SERVER_ERROR + " with " + response.getStatus()); + } + } + + + private static String generateSdncInstanceURL(String siPath, String vfModuleLink) { + return MessageFormat.format(siPath, vfModuleLink); + } + +} -- cgit 1.2.3-korg