diff options
author | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2018-07-30 15:56:09 -0400 |
---|---|---|
committer | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2018-07-31 11:09:25 -0400 |
commit | 5a6a6de6f1a26a1897e4917a0df613e25a24eb70 (patch) | |
tree | 59a968f27b4b603aacc9d5e7b51fb598aeec5321 /adapters/mso-sdnc-adapter/src/main/java/org/onap | |
parent | b6dc38501f3b746426b42d9de4cc883d894149e8 (diff) |
Containerization feature of SO
Change-Id: I95381232eeefcd247a66a5cec370a8ce1c288e18
Issue-ID: SO-670
Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'adapters/mso-sdnc-adapter/src/main/java/org/onap')
35 files changed, 3996 insertions, 0 deletions
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/AsyncConfiguration.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/AsyncConfiguration.java new file mode 100644 index 0000000000..db5f682f6b --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/AsyncConfiguration.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; + + +@Configuration +@EnableAsync +public class AsyncConfiguration { + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java new file mode 100644 index 0000000000..4a50fb32e3 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + +import java.util.Arrays; + +import javax.xml.ws.Endpoint; + +import org.apache.cxf.Bus; +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.feature.LoggingFeature; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.apache.cxf.jaxrs.swagger.Swagger2Feature; +import org.apache.cxf.jaxws.EndpointImpl; +import org.apache.cxf.transport.servlet.CXFServlet; +import org.onap.so.adapters.sdnc.sdncrest.SNIROResponse; +import org.onap.so.logger.MsoLogger; +import org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + + +@Configuration("CXFConfiguration") +public class CXFConfiguration { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL,CXFConfiguration.class); + + JAXRSServerFactoryBean endpoint; + + @Autowired + private Bus bus; + + @Autowired + private JaxRsFilterLogging jaxRsFilterLogging; + + @Autowired + private SDNCAdapterPortType sdncAdapterPortImpl; + + @Autowired + private SNIROResponse sniroResponse; + + + @Autowired + private ObjectMapper mapper; + @Bean + public Server rsServer() { + endpoint = new JAXRSServerFactoryBean(); + mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + endpoint.setBus(bus); + endpoint.setServiceBeans(Arrays.<Object>asList(sniroResponse)); + endpoint.setAddress("/rest"); + endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature())); + endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper),jaxRsFilterLogging)); + return endpoint.create(); + } + + @Bean + public ServletRegistrationBean cxfServlet() { + return new ServletRegistrationBean(new CXFServlet(), "/adapters/*"); + } + + @Bean + public Endpoint sndcAdapter() { + EndpointImpl endpoint = new EndpointImpl(bus, sdncAdapterPortImpl); + endpoint.publish("/SDNCAdapter"); + return endpoint; + } + + + @Bean + public Swagger2Feature createSwaggerFeature() { + Swagger2Feature swagger2Feature= new Swagger2Feature(); + swagger2Feature.setBasePath("/services/rest"); + swagger2Feature.setPrettyPrint(true); + swagger2Feature.setTitle("SO Orchestration Application"); + swagger2Feature.setContact("The ONAP SO team"); + swagger2Feature.setDescription("This project is the SO Orchestration Engine"); + swagger2Feature.setVersion("1.0.0"); + swagger2Feature.setResourcePackage("org.onap.so.adapters.sdnc"); + swagger2Feature.setScan(true); + return swagger2Feature; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java new file mode 100644 index 0000000000..eab7d5bf6f --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.onap.so.adapters.sdnc package. + * <p>An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.sdnc + * + */ + public ObjectFactory() { + /* Empty constructor */ + } + + /** + * Create an instance of {@link RequestHeader } + * + */ + public RequestHeader createRequestHeader() { + return new RequestHeader(); + } + + /** + * Create an instance of {@link SDNCAdapterResponse } + * + */ + public SDNCAdapterResponse createSDNCAdapterResponse() { + return new SDNCAdapterResponse(); + } + + /** + * Create an instance of {@link SDNCAdapterRequest } + * + */ + public SDNCAdapterRequest createSDNCAdapterRequest() { + return new SDNCAdapterRequest(); + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java new file mode 100644 index 0000000000..1f1b85f34b --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="SvcInstanceId" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="SvcAction" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="SvcOperation" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="CallbackUrl" type="{http://www.w3.org/2001/XMLSchema}string"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//BPEL to SDNCAdapter request header +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestId", + "svcInstanceId", + "svcAction", + "svcOperation", + "callbackUrl", + "msoAction" +}) +@XmlRootElement(name = "RequestHeader") +public class RequestHeader { + + @XmlElement(name = "RequestId", required = true) + protected String requestId; + @XmlElement(name = "SvcInstanceId") + protected String svcInstanceId; + @XmlElement(name = "SvcAction", required = true) + protected String svcAction; + @XmlElement(name = "SvcOperation", required = true) + protected String svcOperation; + @XmlElement(name = "CallbackUrl", required = true) + protected String callbackUrl; + @XmlElement(name = "MsoAction") + protected String msoAction; + + /** + * Gets the value of the requestId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRequestId() { + return requestId; + } + + /** + * Sets the value of the requestId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRequestId(String value) { + this.requestId = value; + } + + public String getSvcInstanceId() { + return svcInstanceId; + } + + public void setSvcInstanceId(String svcInstanceId) { + this.svcInstanceId = svcInstanceId; + } + + /** + * Gets the value of the svcAction property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSvcAction() { + return svcAction; + } + + /** + * Sets the value of the svcAction property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSvcAction(String value) { + this.svcAction = value; + } + + /** + * Gets the value of the svcOperation property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSvcOperation() { + return svcOperation; + } + + /** + * Sets the value of the svcOperation property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSvcOperation(String value) { + this.svcOperation = value; + } + + /** + * Gets the value of the callbackUrl property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCallbackUrl() { + return callbackUrl; + } + + /** + * Sets the value of the callbackUrl property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCallbackUrl(String value) { + this.callbackUrl = value; + } + + /** + * Gets the value of the callbackUrl property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMsoAction() { + return msoAction; + } + + /** + * Sets the value of the callbackUrl property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMsoAction(String value) { + this.msoAction = value; + } + + + @Override + public String toString() { + return "RequestHeader [requestId=" + requestId + + ", svcInstanceId=" + svcInstanceId + + ", svcAction=" + svcAction + + ", svcOperation=" + svcOperation + + ", callbackUrl=" + callbackUrl + + ", msoAction=" + msoAction + "]"; + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java new file mode 100644 index 0000000000..3d88a1467a --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + +import java.util.concurrent.Executor; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +@SpringBootApplication(scanBasePackages = { "org.onap" }) +@EnableJpaRepositories({"org.onap.so.db.request.data.repository"}) +@EntityScan({ "org.onap.so.db.request.beans"}) +public class SDNCAdapterApplication { + + @Value("${mso.async.core-pool-size}") + private int corePoolSize; + + @Value("${mso.async.max-pool-size}") + private int maxPoolSize; + + @Value("${mso.async.queue-capacity}") + private int queueCapacity; + + private static final String LOGS_DIR = "logs_dir"; + + private static void setLogsDir() { + if (System.getProperty(LOGS_DIR) == null) { + System.getProperties().setProperty(LOGS_DIR, "./logs/sdnc/"); + } + } + + public static void main(String[] args) { + SpringApplication.run(SDNCAdapterApplication.class, args); + System.getProperties().setProperty("server.name", "Springboot"); + setLogsDir(); + } + + @Bean + public Executor asyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + + executor.setCorePoolSize(corePoolSize); + executor.setMaxPoolSize(maxPoolSize); + executor.setQueueCapacity(queueCapacity); + executor.setThreadNamePrefix("SDNCAdapter-"); + executor.initialize(); + return executor; + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java new file mode 100644 index 0000000000..66f93ab87f --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.xml.bind.annotation.XmlSeeAlso; + + +/** + * This class was generated by Apache CXF 2.7.11.redhat-3 + * 2015-01-27T18:25:50.914-05:00 + * Generated source version: 2.7.11.redhat-3 + * + */ +//BPEL SDNCAdapter SOAP WebService - impl class in impl pkg +@WebService(targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1", name = "SDNCAdapterPortType") +@XmlSeeAlso({ObjectFactory.class}) +@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) +public interface SDNCAdapterPortType { + + @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterResponse") + @WebMethod(operationName = "SDNCAdapter") + public SDNCAdapterResponse sdncAdapter( + @WebParam(partName = "SDNCAdapterRequest", name = "SDNCAdapterRequest", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1") + SDNCAdapterRequest sdncAdapterRequest + ); + + @WebMethod + public void healthCheck(); +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java new file mode 100644 index 0000000000..d204f0c2dd --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.so.adapters.sdnc.impl.Utils; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element ref="{http://org.onap/workflow/sdnc/adapter/schema/v1}RequestHeader"/> + * <element name="RequestData" type="{http://www.w3.org/2001/XMLSchema}anyType"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//BPEL to SDNCAdapter request +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestHeader", + "requestData" +}) +@XmlRootElement(name = "SDNCAdapterRequest") +public class SDNCAdapterRequest { + + @XmlElement(name = "RequestHeader", required = true) + protected RequestHeader requestHeader; + @XmlElement(name = "RequestData", required = true) + protected Object requestData; + + /** + * Gets the value of the requestHeader property. + * + * @return + * possible object is + * {@link RequestHeader } + * + */ + public RequestHeader getRequestHeader() { + return requestHeader; + } + + /** + * Sets the value of the requestHeader property. + * + * @param value + * allowed object is + * {@link RequestHeader } + * + */ + public void setRequestHeader(RequestHeader value) { + this.requestHeader = value; + } + + /** + * Gets the value of the requestData property. + * + * @return + * possible object is + * {@link Object } + * + */ + public Object getRequestData() { + return requestData; + } + + /** + * Sets the value of the requestData property. + * + * @param value + * allowed object is + * {@link Object } + * + */ + public void setRequestData(Object value) { + this.requestData = value; + } + + @Override + public String toString() { + + String rd = ""; + if (requestData != null) + { + Node node = (Node) requestData; + Document doc = node.getOwnerDocument(); + rd = Utils.domToStr(doc); + } + return "SDNCAdapterRequest [requestHeader=" + requestHeader.toString() + + ", requestData=" + rd + "]"; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java new file mode 100644 index 0000000000..c67fbc0ae0 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//SDNCAdapter to BPEL Sync Response(ACK) - async response(s) follow +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "") +@XmlRootElement(name = "SDNCAdapterResponse") +public class SDNCAdapterResponse { + + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java new file mode 100644 index 0000000000..a648aa5fd8 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + + +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.ws.Service; +import javax.xml.ws.WebEndpoint; +import javax.xml.ws.WebServiceClient; +import javax.xml.ws.WebServiceFeature; + +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; + +/** + * This class was generated by Apache CXF 2.7.11.redhat-3 + * 2015-01-27T18:25:50.994-05:00 + * Generated source version: 2.7.11.redhat-3 + * + */ +//BPEL SDNCAdapter SOAP WebService +@WebServiceClient(name = "SDNCAdapterService", + wsdlLocation = "main/resources/SDNCAdapter.wsdl", + targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1") +public class SDNCAdapterService extends Service { + + private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, SDNCAdapterService.class); + + public static final URL WSDL_LOCATION; + + public static final QName SERVICE = new QName("http://org.onap/workflow/sdnc/adapter/wsdl/v1", "SDNCAdapterService"); + public static final QName SDNCAdapterSoapHttpPort = new QName("http://org.onap/workflow/sdnc/adapter/wsdl/v1", "SDNCAdapterSoapHttpPort"); + static { + URL wsdlUrl = null; + try { + wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCAdapter.wsdl"); + } catch (Exception e) { + logger.error(MessageEnum.RA_WSDL_NOT_FOUND, "SDNCAdapter.wsdl", "", "", MsoLogger.ErrorCode.DataError, "Exception - WSDL not found", e); + } + if(wsdlUrl == null) { + logger.error(MessageEnum.RA_WSDL_NOT_FOUND, "SDNCAdapter.wsdl", "", "", MsoLogger.ErrorCode.DataError, "WSDL not found"); + } else { + try { + logger.info(MessageEnum.RA_PRINT_URL, "SDNCAdpater.wsdl", wsdlUrl.toURI().toString(), ""); + } catch (Exception e) { + logger.error(MessageEnum.RA_WSDL_URL_CONVENTION_EXC, "SDNCAdapter.wsdl", "", "", MsoLogger.ErrorCode.DataError, "Exception - print URL", e); + } + } + WSDL_LOCATION = wsdlUrl; + } + + public SDNCAdapterService(URL wsdlLocation) { + super(wsdlLocation, SERVICE); + } + + public SDNCAdapterService(URL wsdlLocation, QName serviceName) { + super(wsdlLocation, serviceName); + } + + public SDNCAdapterService() { + super(WSDL_LOCATION, SERVICE); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCAdapterService(WebServiceFeature ... features) { + super(WSDL_LOCATION, SERVICE, features); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCAdapterService(URL wsdlLocation, WebServiceFeature ... features) { + super(wsdlLocation, SERVICE, features); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCAdapterService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) { + super(wsdlLocation, serviceName, features); + } + + /** + * + * @return + * returns SDNCAdapterPortType + */ + @WebEndpoint(name = "SDNCAdapterSoapHttpPort") + public SDNCAdapterPortType getSDNCAdapterSoapHttpPort() { + return super.getPort(SDNCAdapterSoapHttpPort, SDNCAdapterPortType.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. + * @return + * returns SDNCAdapterPortType + */ + @WebEndpoint(name = "SDNCAdapterSoapHttpPort") + public SDNCAdapterPortType getSDNCAdapterSoapHttpPort(WebServiceFeature... features) { + return super.getPort(SDNCAdapterSoapHttpPort, SDNCAdapterPortType.class, features); + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SyncConfiguration.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SyncConfiguration.java new file mode 100644 index 0000000000..0755b9ea3f --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SyncConfiguration.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + +import org.springframework.context.annotation.Profile; + +@Profile("non-async") +public class SyncConfiguration { + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java new file mode 100644 index 0000000000..60e37294b1 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + +import org.onap.so.security.MSOSpringFirewall; +import org.onap.so.security.WebSecurityConfig; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.firewall.StrictHttpFirewall; +import org.springframework.util.StringUtils; + +@EnableWebSecurity +public class WebSecurityConfigImpl extends WebSecurityConfig { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + .antMatchers("/manage/health","/manage/info","/services").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString()) + .and() + .httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java new file mode 100644 index 0000000000..67f5516daa --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.client; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="ResponseCode" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="ResponseMessage" type="{http://www.w3.org/2001/XMLSchema}string"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//SDNCAdapter to BPEL Async response header +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestId", + "responseCode", + "responseMessage" +}) +@XmlRootElement(name = "CallbackHeader") +public class CallbackHeader { + + @XmlElement(name = "RequestId", required = true) + protected String requestId; + @XmlElement(name = "ResponseCode", required = true) + protected String responseCode; + @XmlElement(name = "ResponseMessage", required = true) + protected String responseMessage; + + public CallbackHeader() { + /* Empty constructor */ + } + + public CallbackHeader(String reqId, String respCode, String respMsg) { + this.requestId = reqId; + this.responseCode = respCode; + this.responseMessage = respMsg; + } + + /** + * Gets the value of the requestId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRequestId() { + return requestId; + } + + /** + * Sets the value of the requestId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRequestId(String value) { + this.requestId = value; + } + + /** + * Gets the value of the responseCode property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponseCode() { + return responseCode; + } + + /** + * Sets the value of the responseCode property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponseCode(String value) { + this.responseCode = value; + } + + /** + * Gets the value of the responseMessage property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponseMessage() { + return responseMessage; + } + + /** + * Sets the value of the responseMessage property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponseMessage(String value) { + this.responseMessage = value; + } + + @Override + public String toString() { + return "CallbackHeader [requestId=" + requestId + ", responseCode=" + + responseCode + ", responseMessage=" + responseMessage + "]"; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java new file mode 100644 index 0000000000..238b6a7b1c --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.client; + + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.onap.so.adapters.sdnc.client package. + * <p>An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.sdnc.client + * + */ + public ObjectFactory() { + } + + + /** + * Create an instance of {@link SDNCAdapterCallbackRequest } + * + */ + public SDNCAdapterCallbackRequest createSDNCAdapterCallbackRequest() { + return new SDNCAdapterCallbackRequest(); + } + + /** + * Create an instance of {@link CallbackHeader } + * + */ + public CallbackHeader createCallbackHeader() { + return new CallbackHeader(); + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java new file mode 100644 index 0000000000..7ec20afffd --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.client; + + +import java.io.StringWriter; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element ref="{http://org.onap/workflow/sdnc/adapter/schema/v1}CallbackHeader"/> + * <element name="RequestData" type="{http://www.w3.org/2001/XMLSchema}anyType"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//SDNCAdapter to BPEL Async response +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "callbackHeader", + "requestData" +}) +@XmlRootElement(name = "SDNCAdapterCallbackRequest") +public class SDNCAdapterCallbackRequest { + + @XmlElement(name = "CallbackHeader", required = true) + protected CallbackHeader callbackHeader; + @XmlElement(name = "RequestData") + protected Object requestData; + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, SDNCAdapterCallbackRequest.class); + + /** + * Gets the value of the callbackHeader property. + * + * @return + * possible object is + * {@link CallbackHeader } + * + */ + public CallbackHeader getCallbackHeader() { + return callbackHeader; + } + + /** + * Sets the value of the callbackHeader property. + * + * @param value + * allowed object is + * {@link CallbackHeader } + * + */ + public void setCallbackHeader(CallbackHeader value) { + this.callbackHeader = value; + } + + /** + * Gets the value of the requestData property. + * + * @return + * possible object is + * {@link Object } + * + */ + public Object getRequestData() { + return requestData; + } + + /** + * Sets the value of the requestData property. + * + * @param value + * allowed object is + * {@link Object } + * + */ + public void setRequestData(Object value) { + this.requestData = value; + } + + @Override + public String toString() { + try { + JAXBContext ctx = JAXBContext.newInstance("org.onap.so.adapters.sdnc.client"); + Marshaller m = ctx.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); + StringWriter w = new StringWriter(); + m.marshal(this, w); + return w.toString(); + } + catch (Exception e) + { + msoLogger.error(MessageEnum.RA_MARSHING_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception - MARSHING_ERROR", e); + } + return ""; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java new file mode 100644 index 0000000000..369610ce0f --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.client; + + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.xml.bind.annotation.XmlSeeAlso; + +import org.onap.so.adapters.sdnc.SDNCAdapterResponse; + + +/** + * This class was generated by Apache CXF 2.7.11.redhat-3 + * 2015-01-28T11:07:01.997-05:00 + * Generated source version: 2.7.11.redhat-3 + * + */ +//SDNCAdapter to BPEL Async response WEB Service +@WebService(targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", name = "SDNCCallbackAdapterPortType") +@XmlSeeAlso({ObjectFactory.class}) +@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) +@FunctionalInterface +public interface SDNCCallbackAdapterPortType { + + @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse") + @WebMethod(operationName = "SDNCAdapterCallback") + public SDNCAdapterResponse sdncAdapterCallback( + @WebParam(partName = "SDNCAdapterCallbackRequest", name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1") + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest + ); +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java new file mode 100644 index 0000000000..e68bac4178 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.client; + + +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.ws.Service; +import javax.xml.ws.WebEndpoint; +import javax.xml.ws.WebServiceClient; +import javax.xml.ws.WebServiceFeature; + +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; + +/** + * This class was generated by Apache CXF 2.7.11.redhat-3 + * 2015-01-28T11:07:02.074-05:00 + * Generated source version: 2.7.11.redhat-3 + * + */ +//SDNCAdapter to BPEL Async response WEB Service +@WebServiceClient(name = "SDNCCallbackAdapterService", + wsdlLocation = "main/resources/SDNCCallbackAdapter.wsdl", + targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1") +public class SDNCCallbackAdapterService extends Service { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, SDNCCallbackAdapterService.class); + + public static final URL WSDL_LOCATION; + public static final QName SERVICE = new QName("http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterService"); + public static final QName SDNCCallbackAdapterSoapHttpPort = new QName("http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterSoapHttpPort"); + static { + URL wsdlUrl = null; + try { + wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCCallbackAdapter.wsdl"); + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_WSDL_NOT_FOUND, "SDNCCallbackAdapter.wsdl", "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - WSDL not found", e); + } + if(wsdlUrl == null) { + msoLogger.error(MessageEnum.RA_WSDL_NOT_FOUND, "SDNCCallbackAdapter.wsdl", "SDNC", "", MsoLogger.ErrorCode.DataError, "WSDL not found"); + } else { + try { + msoLogger.info(MessageEnum.RA_PRINT_URL, "SDNCCallbackAdapter.wsdl", wsdlUrl.toURI().toString(), "SDNC"); + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_WSDL_URL_CONVENTION_EXC, "SDNCCallbackAdapter.wsdl", "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - URL convention problem", e); + } + } + WSDL_LOCATION = wsdlUrl; + } + + public SDNCCallbackAdapterService(URL wsdlLocation) { + super(wsdlLocation, SERVICE); + } + + public SDNCCallbackAdapterService(URL wsdlLocation, QName serviceName) { + super(wsdlLocation, serviceName); + } + + public SDNCCallbackAdapterService() { + super(WSDL_LOCATION, SERVICE); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCCallbackAdapterService(WebServiceFeature ... features) { + super(WSDL_LOCATION, SERVICE, features); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCCallbackAdapterService(URL wsdlLocation, WebServiceFeature ... features) { + super(wsdlLocation, SERVICE, features); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCCallbackAdapterService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) { + super(wsdlLocation, serviceName, features); + } + + /** + * + * @return + * returns SDNCCallbackAdapterPortType + */ + @WebEndpoint(name = "SDNCCallbackAdapterSoapHttpPort") + public SDNCCallbackAdapterPortType getSDNCCallbackAdapterSoapHttpPort() { + return super.getPort(SDNCCallbackAdapterSoapHttpPort, SDNCCallbackAdapterPortType.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. + * @return + * returns SDNCCallbackAdapterPortType + */ + @WebEndpoint(name = "SDNCCallbackAdapterSoapHttpPort") + public SDNCCallbackAdapterPortType getSDNCCallbackAdapterSoapHttpPort(WebServiceFeature... features) { + return super.getPort(SDNCCallbackAdapterSoapHttpPort, SDNCCallbackAdapterPortType.class, features); + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java new file mode 100644 index 0000000000..368c824caa --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java @@ -0,0 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package org.onap.so.adapters.sdnc.client; + diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java new file mode 100644 index 0000000000..e45c4ce569 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.exception; + +public class SDNCAdapterException extends Exception { + + private static final long serialVersionUID = -7913634772004514998L; + + public SDNCAdapterException(String message) { + super(message); + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java new file mode 100644 index 0000000000..d114788267 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.impl; + + +public interface Constants { + + public static final String BPEL_REST_URL_PROP = "org.onap.so.adapters.sdnc.rest.bpelurl"; + public static final String BPEL_URL_PROP = "org.onap.so.adapters.sdnc.bpelurl"; + public static final String DEFAULT_BPEL_URL = "http://localhost:8080//active-bpel/services/SDNCAdapterCallbackV1"; + + public static final String MY_URL_PROP = "org.onap.so.adapters.sdnc.myurl"; + public static final String DEFAULT_MY_URL = "https://localhost:8443/adapters/rest/SDNCNotify"; + + public static final String SDNC_AUTH_PROP = "org.onap.so.adapters.sdnc.sdncauth"; + public static final String DEFAULT_SDNC_AUTH = "406B2AE613211B6FB52466DE6E1769AC"; + + public static final String DEFAULT_BPEL_AUTH = "05FDA034C27D1CA51AAB8FAE512EDE45241E16FC8C137D292AA3A964431C82DB"; + public static final String BPEL_AUTH_PROP = "org.onap.so.adapters.sdnc.bpelauth"; + + + public static final String SDNC_SVCCFGRESP_ROOT = "input"; + public static final String SDNC_REQ_ID = "/svc-request-id"; + public static final String SDNC_RESP_CODE = "/response-code"; + public static final String SDNC_RESP_MSG = "/response-message"; + public static final String SDNC_CONNECTTIME_PROP = "org.onap.so.adapters.sdnc.sdncconnecttime"; + public static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; + + public static final String REQUEST_TUNABLES = "org.onap.so.adapters.sdnc"; +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java new file mode 100644 index 0000000000..b456fb2336 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.impl; + +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class MapRequestTunables { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,MapRequestTunables.class); + public static final String GENERATED_KEY = "Generated key: "; + + @Autowired + private Environment env; + + public RequestTunables setTunables(RequestTunables reqTunableOriginal) + { + RequestTunables reqTunable = new RequestTunables(reqTunableOriginal); + String error = null; + String key; + if ("query".equals(reqTunable.getAction())) { //due to variable format for reqTunable.getOperation() eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9 + key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + ".." + reqTunable.getAction(); + msoLogger.debug(GENERATED_KEY + key); + } + else if ("put".equals(reqTunable.getAction()) || "restdelete".equals(reqTunable.getAction())) { //due to variable format for reqTunable.getOperation() eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9 + key = Constants.REQUEST_TUNABLES + "..." + reqTunable.getAction(); + msoLogger.debug(GENERATED_KEY + key); + } else { + key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + "." + reqTunable.getOperation() +"." + reqTunable.getAction(); + msoLogger.debug(GENERATED_KEY + key); + } + + String value; + value = env.getProperty(key, ""); + + if (value != null && value.length() > 0) { + + String[] parts = value.split("\\|"); //escape pipe + if (parts.length < 3) { + msoLogger.warn(MessageEnum.RA_SDNC_INVALID_CONFIG, key, value, "SDNC", "", MsoLogger.ErrorCode.DataError, "Invalid config"); + } + + for (int i = 0; i < parts.length; i++) { + if (i == 0) { + reqTunable.setReqMethod(parts[i]) ; + msoLogger.debug("Request Method is set to: " + reqTunable.getReqMethod()); + } else if (i == 1) { + reqTunable.setTimeout( parts[i]); + msoLogger.debug("Timeout is set to: " + reqTunable.getTimeout()); + } else if (i == 2) { + reqTunable.setSdncUrl(env.getProperty(Constants.REQUEST_TUNABLES + "." + parts[i],"")); + if (reqTunable.getOperation() != null && reqTunable.getSdncUrl() != null) { + reqTunable.setSdncUrl(reqTunable.getSdncUrl() + reqTunable.getOperation()); + } + msoLogger.debug("SDNC Url is set to: " + reqTunable.getSdncUrl()); + } else if (i == 3) { + reqTunable.setHeaderName(parts[i]); + msoLogger.debug("HeaderName is set to: " + reqTunable.getHeaderName()); + } else if (i == 4) { + reqTunable.setNamespace(parts[i]); + msoLogger.debug("NameSpace is set to: " + reqTunable.getNamespace()); + } else if (i == 5) { + reqTunable.setAsyncInd(parts[i]); + msoLogger.debug("AsyncInd is set to: " + reqTunable.getAsyncInd()); + } + } + + if (reqTunable.getSdncUrl() == null || reqTunable.getSdncUrl().equals("")) { + error = "Invalid configuration, sdncUrl required for:" + key + " value:" + value; + } + } else { + error = "Missing configuration for:" + key; + } + if (error != null) { + msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, key, "SDNC", "", MsoLogger.ErrorCode.DataError, "Missing config param"); + } + msoLogger.debug ("RequestTunables Key:" + key + " Value:" + value + " Tunables:" + this.toString()); + return reqTunable; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java new file mode 100644 index 0000000000..5ed9763b71 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java @@ -0,0 +1,161 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.impl; + + + +import org.onap.so.logger.MsoLogger; +public class RequestTunables { + + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,RequestTunables.class); + + public static final String GENERATED_KEY = "Generated key: "; + + //criteria + private String reqId = ""; + private String msoAction = ""; + private String operation = ""; + private String action = ""; + + //tunables + private String reqMethod = "POST"; + private String sdncUrl = null; + private String timeout = "60000"; + private String headerName = "sdnc-request-header"; + private String namespace = ""; + private String asyncInd = "N"; //future use + + private String sdncaNotificationUrl = null; + + public RequestTunables(String reqId, String msoAction, String operation, String action) { + super(); + if (reqId != null) { + this.reqId = reqId; + } + if (msoAction != null) { + this.msoAction = msoAction; + } + if (operation != null) { + this.operation = operation; + } + if (action != null) { + this.action = action; + } + } + + public RequestTunables(RequestTunables original) { + this.reqId = original.reqId; + this.action = original.action; + this.msoAction = original.msoAction; + this.operation = original.operation; + this.reqMethod = original.reqMethod; + this.sdncUrl = original.sdncUrl; + this.timeout = original.timeout; + this.headerName = original.headerName; + this.namespace = original.namespace; + this.asyncInd = original.asyncInd; + this.sdncaNotificationUrl = original.sdncaNotificationUrl; + } + + public String getReqId() { + return reqId; + } + public void setReqId(String reqId) { + this.reqId = reqId; + } + public String getReqMethod() { + return reqMethod; + } + public void setReqMethod(String reqMethod) { + this.reqMethod = reqMethod; + } + public String getMsoAction() { + return msoAction; + } + public void setMsoAction(String msoAction) { + this.msoAction = msoAction; + } + public String getAction() { + return action; + } + public void setAction(String action) { + this.action = action; + } + public String getOperation() { + return operation; + } + public void setOperation(String operation) { + this.operation = operation; + } + public String getSdncUrl() { + return sdncUrl; + } + public void setSdncUrl(String sdncUrl) { + this.sdncUrl = sdncUrl; + } + public String getTimeout() { + return timeout; + } + public void setTimeout(String timeout) { + this.timeout = timeout; + } + public String getAsyncInd() { + return asyncInd; + } + public void setAsyncInd(String asyncInd) { + this.asyncInd = asyncInd; + } + public String getHeaderName() { + return headerName; + } + public void setHeaderName(String headerName) { + this.headerName = headerName; + } + + + public String getSdncaNotificationUrl() { + return sdncaNotificationUrl; + } + + public void setSdncaNotificationUrl(String sdncaNotificationUrl) { + this.sdncaNotificationUrl = sdncaNotificationUrl; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + @Override + public String toString() { + return "RequestTunables [reqId=" + reqId + ", msoAction=" + msoAction + + ", operation=" + operation + ", action=" + action + + ", reqMethod=" + reqMethod + ", sdncUrl=" + sdncUrl + + ", timeout=" + timeout + ", headerName=" + headerName + + ", sdncaNotificationUrl=" + sdncaNotificationUrl + + ", namespace=" + namespace + "]"; + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java new file mode 100644 index 0000000000..8000e3ab8e --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.impl; + +import javax.annotation.PostConstruct; +import javax.jws.WebService; +import javax.servlet.http.HttpServletResponse; + +import org.onap.so.adapters.sdnc.SDNCAdapterPortType; +import org.onap.so.adapters.sdnc.SDNCAdapterRequest; +import org.onap.so.adapters.sdnc.SDNCAdapterResponse; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +//BPEL SDNCAdapter SOAP Web Service implementation +@WebService(serviceName = "SDNCAdapterService", endpointInterface = "org.onap.so.adapters.sdnc.SDNCAdapterPortType", targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1") +@Component +public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { + + + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCAdapterPortTypeImpl.class); + private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + + @Autowired + private SDNCRestClient sdncClient; + + @PostConstruct + public void init () { + msoLogger.info(MessageEnum.RA_INIT_SDNC_ADAPTER, "SDNC", "SDNCAdapterPortType", ""); + } + + /** + * Health Check web method. Does nothing but return to show the adapter is deployed. + */ + @Override + public void healthCheck () + { + msoLogger.debug("Health check call in SDNC Adapter"); + } + + + @Override + public SDNCAdapterResponse sdncAdapter(SDNCAdapterRequest bpelRequest) { + String bpelReqId = bpelRequest.getRequestHeader().getRequestId(); + String callbackUrl = bpelRequest.getRequestHeader().getCallbackUrl(); + try { + sdncClient.executeRequest(bpelRequest); + } + catch (Exception e){ + String respMsg = "Error sending request to SDNC. Failed to start SDNC Client thread " + e.getMessage(); + msoLogger.error(MessageEnum.RA_SEND_REQUEST_SDNC_ERR, "SDNC", "", MsoLogger.ErrorCode.DataError, respMsg, e); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, respMsg); + SDNCResponse sdncResp = new SDNCResponse(bpelReqId); + sdncResp.setRespCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + sdncResp.setRespMsg(respMsg); + sdncClient.sendRespToBpel(callbackUrl, sdncResp); + } + + SDNCAdapterResponse wsResp = new SDNCAdapterResponse(); + return wsResp; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java new file mode 100644 index 0000000000..c0a737cf78 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.impl; + + +import java.io.Serializable; + +public class SDNCResponse implements Serializable { + + private static final long serialVersionUID = 1L; + private String reqId = null; + private int respCode = 0; + private String respMsg = null; + private String sdncRespXml = null; + + public SDNCResponse(String reqId) { + this.reqId = reqId; + } + public SDNCResponse(String reqId, int respCode, String respMsg) { + this.reqId = reqId; + this.respCode = respCode; + this.respMsg = respMsg; + } + + public String getReqId() { + return reqId; + } + public void setReqId(String reqId) { + this.reqId = reqId; + } + public int getRespCode() { + return respCode; + } + public void setRespCode(int respCode) { + this.respCode = respCode; + } + public String getRespMsg() { + return respMsg; + } + public void setRespMsg(String respMsg) { + this.respMsg = respMsg; + } + public String getSdncRespXml() { + return sdncRespXml; + } + public void setSdncRespXml(String sdncRespXml) { + this.sdncRespXml = sdncRespXml; + } + + @Override + public String toString() { + return "SDNCResponse [reqId=" + reqId + ", respCode=" + respCode + + ", respMsg=" + respMsg + ", sdncRespXml=" + sdncRespXml + "]"; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java new file mode 100644 index 0000000000..58feaac0e7 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java @@ -0,0 +1,333 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.impl; + + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.XMLConstants; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.ws.BindingProvider; +import javax.xml.ws.handler.MessageContext; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; +import org.onap.so.utils.CryptoUtils; +import org.onap.so.adapters.sdnc.SDNCAdapterRequest; +import org.onap.so.adapters.sdnc.client.CallbackHeader; +import org.onap.so.adapters.sdnc.client.SDNCAdapterCallbackRequest; +import org.onap.so.adapters.sdnc.client.SDNCCallbackAdapterPortType; +import org.onap.so.adapters.sdnc.client.SDNCCallbackAdapterService; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +@Component +public class SDNCRestClient{ + + @Autowired + private Environment env; + + @Autowired + private MapRequestTunables tunablesMapper; + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCRestClient.class); + private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + + @Async + public void executeRequest(SDNCAdapterRequest bpelRequest) + { + + msoLogger.debug("BPEL Request:" + bpelRequest.toString()); + + String action = bpelRequest.getRequestHeader().getSvcAction(); + String operation = bpelRequest.getRequestHeader().getSvcOperation(); + String bpelReqId = bpelRequest.getRequestHeader().getRequestId(); + String callbackUrl = bpelRequest.getRequestHeader().getCallbackUrl(); + + String sdncReqBody = null; + + + + RequestTunables rt = new RequestTunables(bpelReqId, + bpelRequest.getRequestHeader().getMsoAction(), + bpelRequest.getRequestHeader().getSvcOperation(), + bpelRequest.getRequestHeader().getSvcAction()); + rt = tunablesMapper.setTunables(rt); + rt.setSdncaNotificationUrl(env.getProperty(Constants.MY_URL_PROP)); + + + if ("POST".equals(rt.getReqMethod())) + { + Node node = (Node) bpelRequest.getRequestData(); + Document reqDoc = node.getOwnerDocument(); + sdncReqBody = Utils.genSdncReq(reqDoc, rt); + } + else if("PUT".equals(rt.getReqMethod())){ + Node node = (Node) bpelRequest.getRequestData(); + Document reqDoc = node.getOwnerDocument(); + sdncReqBody = Utils.genSdncPutReq(reqDoc, rt); + } + long sdncStartTime = System.currentTimeMillis(); + SDNCResponse sdncResp = getSdncResp(sdncReqBody, rt); + msoLogger.recordMetricEvent (sdncStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from SDNC", "SDNC", action + "." + operation, null); + msoLogger.debug ("Got the SDNC Response: " + sdncResp.getSdncRespXml()); + long bpelStartTime = System.currentTimeMillis(); + sendRespToBpel(callbackUrl, sdncResp); + msoLogger.recordMetricEvent (bpelStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully send reauest to BPEL", "BPMN", callbackUrl, null); + return; + } + + public SDNCResponse getSdncResp(String sdncReqBody, RequestTunables rt) + { + + URL url; + HttpURLConnection con = null; + DataOutputStream out = null; + BufferedReader in = null; + SDNCResponse sdncResp = new SDNCResponse(rt.getReqId()); + StringBuilder response = new StringBuilder(); + + msoLogger.info(MessageEnum.RA_SEND_REQUEST_SDNC.name() + ":\n" + rt.toString(), "SDNC", ""); + msoLogger.trace("SDNC Request Body:\n" + sdncReqBody); + + try { + + url = new URL(rt.getSdncUrl()); + + con = (HttpURLConnection) url.openConnection(); + con.setConnectTimeout(Integer.parseInt(env.getProperty(Constants.SDNC_CONNECTTIME_PROP))); + con.setReadTimeout(Integer.parseInt(rt.getTimeout())); + con.setRequestProperty("Accept", "application/yang.data+xml"); //for response in xml + String userCredentials = CryptoUtils.decryptProperty(env.getProperty(Constants.SDNC_AUTH_PROP), Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY); + + String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + con.setRequestProperty ("Authorization", basicAuth); + con.setRequestMethod(rt.getReqMethod()); + + // Add request headers + if ("POST".equals(rt.getReqMethod()) || "PUT".equals(rt.getReqMethod())) + { + con.setRequestProperty("Content-type", "application/xml"); + con.setRequestProperty("Content-length",String.valueOf(sdncReqBody.length())); + con.setDoOutput(true); + out = new DataOutputStream(con.getOutputStream()); + out.writeBytes(sdncReqBody); + out.flush(); + out.close(); + } + + //Get response + sdncResp.setRespCode(con.getResponseCode()); + sdncResp.setRespMsg(con.getResponseMessage()); + + if (con.getResponseCode()>= 200 && con.getResponseCode()<=299) { + in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + //Not parsing the response -it contains a responseHdr section and data section + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } + + sdncResp.setSdncRespXml(response.toString()); + msoLogger.info(MessageEnum.RA_RESPONSE_FROM_SDNC.name() + ":\n" + sdncResp.toString(), "SDNC", ""); + return(sdncResp); + } + catch (Exception e) + { + msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception processing request to SDNC", e); + //default + sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR); + String respMsg = "Error processing request to SDNC. "; + StringBuilder sdncErrMsg = new StringBuilder(); + + if (e instanceof java.net.SocketTimeoutException ) + { + sdncResp.setRespCode(HttpURLConnection.HTTP_CLIENT_TIMEOUT); + respMsg = "Request to SDNC timed out. "; + } + if (con != null) + { + try { //e1 + if (con.getResponseCode() != HttpURLConnection.HTTP_OK) //seen in SocketException connection reset + sdncResp.setRespCode(con.getResponseCode()); + respMsg = respMsg + con.getResponseMessage() + ". "; + InputStream is = con.getErrorStream(); + if (is != null) + { + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature (XMLConstants.FEATURE_SECURE_PROCESSING, true); + dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); + dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + DocumentBuilder db; + Document doc = null; + try { //e2 + db = dbf.newDocumentBuilder(); + doc = db.parse(is); + NodeList errors = (NodeList)xpath.evaluate("errors/error", doc, XPathConstants.NODESET); + for (int i = 0; i < errors.getLength(); i++) + { + Element error = (Element) errors.item(i); + String eType = null; + try { + eType = xpath.evaluate("error-type", error); + sdncErrMsg = new StringBuilder(". SDNC Returned-[error-type:" + eType); + } catch (Exception e3) { + msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3); + } + + String eTag = null; + try { + eTag = xpath.evaluate( "error-tag", error); + sdncErrMsg.append(", error-tag:").append(eTag); + } catch (Exception e3) { + msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3); + } + + String eMsg = null; + try { + eMsg = xpath.evaluate("error-message", error); + sdncErrMsg.append(", error-message:").append(eMsg).append("]"); + } catch (Exception e3) { + msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3); + } + } + } catch (Exception e2) { + msoLogger.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while analyse error", e2); + } + } //is != null + } catch (Exception e1) { + msoLogger.error (MessageEnum.RA_ERROR_GET_RESPONSE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception while get SDNC response", e1); + } + } //con != null + + if (e.getMessage() != null) { + respMsg = respMsg + e.getMessage(); + } + respMsg = respMsg + sdncErrMsg; + + sdncResp.setRespMsg(respMsg); + + msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with SDNC", e); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, respMsg); + return sdncResp; + } + finally + { + if (con != null) { + con.disconnect(); + } + } + } + + public void sendRespToBpel(String bpelUrl, SDNCResponse sdncResp) + { + String error; + try + { + SDNCAdapterCallbackRequest cbReq = new SDNCAdapterCallbackRequest(); + cbReq.setCallbackHeader(new CallbackHeader(sdncResp.getReqId(), Integer.toString(sdncResp.getRespCode()), sdncResp.getRespMsg())); + if (sdncResp.getSdncRespXml() != null) + { + cbReq.setRequestData(sdncResp.getSdncRespXml()); + } + msoLogger.info(MessageEnum.RA_CALLBACK_BPEL.name() + ":\n" + cbReq.toString(), "Camunda", ""); + + URL wsdlUrl = null; + try { + wsdlUrl = new URL (bpelUrl); + } catch (MalformedURLException e1) { + error = "Caught exception initializing Callback wsdl " + e1.getMessage(); + msoLogger.error(MessageEnum.RA_INIT_CALLBACK_WSDL_ERR, "Camunda", "", MsoLogger.ErrorCode.DataError, "Exception initializing Callback wsdl", e1); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, error); + } + + SDNCCallbackAdapterService cbSvc = new SDNCCallbackAdapterService(); + + SDNCCallbackAdapterPortType cbPort = cbSvc.getSDNCCallbackAdapterSoapHttpPort(); + + BindingProvider bp = (BindingProvider)cbPort; + + if(null != wsdlUrl) { + bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, wsdlUrl.toExternalForm()); + } + else { + msoLogger.debug("wsdlUrl is NULL:"); + } + + //authentication + try + { + Map<String, Object> reqCtx = bp.getRequestContext(); + Map<String, List<String>> headers = new HashMap<>(); + String userCredentials = CryptoUtils.decryptProperty(env.getProperty(Constants.BPEL_AUTH_PROP), Constants.DEFAULT_BPEL_AUTH, Constants.ENCRYPTION_KEY); + + String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); + headers.put ("Authorization", Collections.singletonList(basicAuth)); + } + catch (Exception e2) { + error = "Unable to set authorization in callback request " + e2.getMessage(); + msoLogger.error(MessageEnum.RA_SET_CALLBACK_AUTH_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - Unable to set authorization in callback request", e2); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, error); + } + + msoLogger.debug("Invoking Bpel Callback. BpelCallbackUrl:" + bpelUrl); + cbPort.sdncAdapterCallback(cbReq); + + } + catch (Exception e) + { + error = "Error sending BpelCallback request" + e.getMessage(); + msoLogger.error("Error " + MsoLogger.ErrorCode.BusinessProcesssError + " - " + MessageEnum.RA_CALLBACK_BPEL_EXC + " - " + error, e); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, error); + } + msoLogger.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE.name(), "Camunda", ""); + return; + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java new file mode 100644 index 0000000000..55af0d7cad --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.impl; + + +import java.io.StringWriter; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +public class Utils { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, Utils.class); + + private Utils() { + } + + public static String genSdncReq(Document reqDoc, RequestTunables rt) { + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + //NewDoc for output + //Root + Document newdoc = db.newDocument(); + Element root = newdoc.createElementNS(rt.getNamespace(), "input"); + newdoc.appendChild(root); + + //Header + Element hdr = newdoc.createElement(rt.getHeaderName()); + root.appendChild(hdr); + + String elemData = rt.getReqId(); + Element hdrChild; + if (elemData != null && elemData.length() > 0) + { + hdrChild = newdoc.createElement("svc-request-id"); + hdrChild.appendChild(newdoc.createTextNode(elemData)); + hdr.appendChild(hdrChild); + } + + elemData = rt.getAction(); + if (elemData != null && elemData.length() > 0) + { + hdrChild = newdoc.createElement("svc-action"); + hdrChild.appendChild(newdoc.createTextNode(elemData)); + hdr.appendChild(hdrChild); + } + + elemData = rt.getSdncaNotificationUrl(); + if (elemData != null && elemData.length() > 0) + { + hdrChild = newdoc.createElement("svc-notification-url"); + hdrChild.appendChild(newdoc.createTextNode(elemData)); + hdr.appendChild(hdrChild); + } + + //RequestData + NodeList nodes = reqDoc.getDocumentElement().getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + Node n = nodes.item(i); + Node newNode = newdoc.importNode(n, true); + root.appendChild(newNode); + } + + String s = domToStr(newdoc); + msoLogger.debug("Formatted SdncReq:\n" + s); + return s; + + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in genSdncReq", e); + } + return null; + } + + public static String genSdncPutReq(Document reqDoc, RequestTunables rt) { + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + //NewDoc for output + //Root + Document newdoc = db.newDocument(); + + //RequestData + NodeList nodes = reqDoc.getDocumentElement().getChildNodes(); + + Element root = newdoc.createElementNS(nodes.item(0).getNamespaceURI(), nodes.item(0).getNodeName()); + newdoc.appendChild(root); + + NodeList childNodes = nodes.item(0).getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node n = childNodes.item(i); + Node newNode = newdoc.importNode(n, true); + root.appendChild(newNode); + } + + String s = domToStr(newdoc); + msoLogger.debug("Formatted SdncPutReq:\n" + s); + return s; + + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception in genSdncPutReq", e); + } + return null; + } + + public static String genMsoFailResp(SDNCResponse resp) { + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + //NewDoc for output + //Root + Document newdoc = db.newDocument(); + Element root = newdoc.createElement("output"); + newdoc.appendChild(root); + + Element elem1 = newdoc.createElement("svc-request-id"); + elem1.appendChild(newdoc.createTextNode(resp.getReqId())); + root.appendChild(elem1); + + Element elem2 = newdoc.createElement("response-code"); + elem2.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespCode()))); + root.appendChild(elem2); + + Element elem3 = newdoc.createElement("response-message"); + elem3.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespMsg()))); + root.appendChild(elem3); + + String s = domToStr(newdoc); + msoLogger.debug("Formatted SdncReq:" + s); + return s; + + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception in genMsoFailResp", e); + } + return null; + } + + + public static String domToStr(Document doc) + { + if (doc != null) + { + try { + DOMSource ds = new DOMSource(doc); + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + TransformerFactory tf = TransformerFactory.newInstance(); + tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer t = tf.newTransformer(); + //t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//<?xml version="1.0" encoding="UTF-8"?> + t.transform(ds, sr); + String s = sw.toString(); + + // This is an awful fix for now but we don't want that xmlns="" to be generated + s = s.replaceAll("xmlns=\"\"", ""); + return s; + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CONVERT_XML2STR, "", "", MsoLogger.ErrorCode.DataError, "Exception - domToStr", e); + } + } + return null; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java new file mode 100644 index 0000000000..bd1f34eadd --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java @@ -0,0 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package org.onap.so.adapters.sdnc; + diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java new file mode 100644 index 0000000000..576d7846cd --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.onap.so.adapters.sdnc.impl.Constants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.onap.so.utils.CryptoUtils; +import org.springframework.core.env.Environment; + +/** + * Sends asynchronous messages to the BPMN WorkflowMessage service. + */ +@Component +public class BPRestCallback { + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,BPRestCallback.class); + private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger(); + + @Autowired + private Environment env; + + /** + * Sends a message to the BPMN workflow message service. The URL path is + * constructed using the specified message type and correlator. + * @param workflowMessageUrl the base BPMN WorkflowMessage URL + * @param messageType the message type + * @param correlator the message correlator + * @param message the JSON content + * @return true if the message was consumed successfully by the endpoint + */ + public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) { + LOGGER.debug(getClass().getSimpleName() + ".send(" + + "workflowMessageUrl=" + workflowMessageUrl + + " messageType=" + messageType + + " correlator=" + correlator + + " message=" + message + + ")"); + + while (workflowMessageUrl.endsWith("/")) { + workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length()-1); + } + + String endpoint = workflowMessageUrl + "/" + SDNCAdapterUtils.encodeURLPathSegment(messageType) + + "/" + SDNCAdapterUtils.encodeURLPathSegment(correlator); + + return send(endpoint, message); + } + + /** + * Sends a message to the BPMN workflow message service. The specified URL + * must have the message type and correlator already embedded in it. + * @param url the endpoint URL + * @param message the JSON content + * @return true if the message was consumed successfully by the endpoint + */ + public boolean send(String url, String message) { + LOGGER.debug(getClass().getSimpleName() + ".send(" + + "url=" + url + + " message=" + message + + ")"); + + LOGGER.info(MessageEnum.RA_CALLBACK_BPEL, message == null ? "[no content]" : message, "Camunda", ""); + + HttpPost method = null; + HttpResponse httpResponse = null; + + try { + int timeout = 60 * 1000; + + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(timeout) + .setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout) + .build(); + + HttpClient client = HttpClientBuilder.create().build(); + method = new HttpPost(url); + method.setConfig(requestConfig); + + if (message != null) { + method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON)); + } + + boolean error = false; + + try { + String userCredentials = CryptoUtils.decryptProperty(env.getProperty(Constants.BPEL_AUTH_PROP), + Constants.DEFAULT_BPEL_AUTH, Constants.ENCRYPTION_KEY); + String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + method.setHeader("Authorization", authorization); + } catch (Exception e) { + LOGGER.error(MessageEnum.RA_SET_CALLBACK_AUTH_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, + "Unable to set authorization in callback request", e); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, + "Unable to set authorization in callback request: " + e.getMessage()); + error = true; + } + + if (!error) { + httpResponse = client.execute(method); + + @SuppressWarnings("unused") + String responseContent = null; + + if (httpResponse.getEntity() != null) { + responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); + } + + if (httpResponse.getStatusLine().getStatusCode() >= 300) { + String msg = "Received error response to callback request: " + httpResponse.getStatusLine(); + LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, msg); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, msg); + } + } + return true; + } catch (Exception e) { + LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, + "Error sending callback request", e); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, + "Error sending callback request: " + e.getMessage()); + return false; + } finally { + if (httpResponse != null) { + try { + EntityUtils.consume(httpResponse.getEntity()); + httpResponse = null; + } catch (Exception e) { + LOGGER.debug("Exception:", e); + } + } + + if (method != null) { + try { + method.reset(); + } catch (Exception e) { + LOGGER.debug("Exception:", e); + } + } + LOGGER.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE, "Camunda", "",""); + } + } +}
\ No newline at end of file diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java new file mode 100644 index 0000000000..8541889d8e --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import org.onap.so.adapters.sdnc.exception.SDNCAdapterException; +import org.onap.so.adapters.sdnc.impl.Constants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class MapTypedRequestTunablesData { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,MapTypedRequestTunablesData.class); + + private static final MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + + @Autowired + private Environment env; + + + public TypedRequestTunables setTunables(TypedRequestTunables reqTunableOriginal) throws SDNCAdapterException { + TypedRequestTunables reqTunable = new TypedRequestTunables(reqTunableOriginal); + + String error; + String value = env.getProperty(reqTunable.getKey().toLowerCase(), ""); + + if ("".equals(value)) { + error= "Missing configuration for: " + reqTunable.getKey(); + msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, reqTunable.getKey(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Missing config param"); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, reqTunable.getError()); + throw new SDNCAdapterException(error); + } + + String[] parts = value.split("\\|"); + + if (parts.length != 5) { + error="Invalid configuration for: " + reqTunable.getKey(); + msoLogger.error(MessageEnum.RA_SDNC_INVALID_CONFIG, reqTunable.getKey(), value, "SDNC", "", MsoLogger.ErrorCode.DataError, "Invalid config"); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, reqTunable.getError()); + throw new SDNCAdapterException(error); + } + + reqTunable.setReqMethod(parts[0]); + msoLogger.trace("Request Method is set to: " + reqTunable.getReqMethod()); + + reqTunable.setTimeout(parts[1]); + msoLogger.trace("Timeout is set to: " + reqTunable.getTimeout()); + + String urlPropKey = Constants.REQUEST_TUNABLES + "." + parts[2]; + reqTunable.setSdncUrl(env.getProperty(urlPropKey, "")); + + if ("".equals(reqTunable.getSdncUrl())) { + error="Missing configuration for: " + urlPropKey; + msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, urlPropKey, "SDNC", "", MsoLogger.ErrorCode.DataError, "Missing config param"); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, reqTunable.getError()); + throw new SDNCAdapterException(error); + } + + msoLogger.trace("SDNC Url is set to: " + reqTunable.getSdncUrl()); + + reqTunable.setHeaderName(parts[3]); + msoLogger.trace("Header Name is set to: " + reqTunable.getHeaderName()); + + reqTunable.setNamespace(parts[4]); + msoLogger.trace("Namespace is set to: " + reqTunable.getNamespace()); + + reqTunable.setMyUrl(env.getProperty(Constants.MY_URL_PROP, "")); + + if ("".equals(reqTunable.getMyUrl())) { + error="Missing configuration for: " + Constants.MY_URL_PROP; + msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, Constants.MY_URL_PROP, "SDNC", "", + MsoLogger.ErrorCode.DataError, "Missing config param"); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, reqTunable.getError()); + throw new SDNCAdapterException(error); + } + + while (reqTunable.getMyUrl().endsWith("/")) { + reqTunable.setMyUrl(reqTunable.getMyUrl().substring(0, reqTunable.getMyUrl().length()-1)); + } + + reqTunable.setMyUrl(reqTunable.getMyUrl().concat(reqTunable.getMyUrlSuffix())); + + msoLogger.debug(reqTunable.toString()); + return reqTunable; + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java new file mode 100644 index 0000000000..05e272f867 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import org.onap.so.logger.MsoLogger; +import org.springframework.web.util.UriUtils; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Utility methods used by SDNCAdapterRest. + */ +public final class SDNCAdapterUtils { + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, SDNCAdapterUtils.class); + /** + * Instantiation is not allowed. + */ + private SDNCAdapterUtils() { + } + + /** + * Returns a node's child elements in a list. + */ + public static List<Element> childElements(Node node) { + List<Element> elements = new ArrayList<>(); + + NodeList nodeList = node.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node child = nodeList.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + elements.add((Element) child); + } + } + + return elements; + } + + /** + * Encodes a URL path segment according to RFC 3986 Section 2. + * @param pathSegment the path segment to encode + * @return the encoded path segment + */ + public static String encodeURLPathSegment(String pathSegment) { + try { + return UriUtils.encodePathSegment(pathSegment, "UTF-8"); + } catch (UnsupportedEncodingException e) { + LOGGER.debug("Exception:", e); + throw new RuntimeException("UTF-8 encoding is not supported"); + } + } +}
\ No newline at end of file diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java new file mode 100644 index 0000000000..6bd7037ca1 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java @@ -0,0 +1,329 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import java.io.StringReader; +import java.net.HttpURLConnection; +import java.net.SocketTimeoutException; + +import javax.xml.XMLConstants; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.onap.so.adapters.sdnc.impl.Constants; +import org.onap.so.adapters.sdncrest.SDNCErrorCommon; +import org.onap.so.adapters.sdncrest.SDNCResponseCommon; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.onap.so.utils.CryptoUtils; +import org.springframework.core.env.Environment; + +/** + * Sends requests to SDNC and processes the responses. + */ +@Component +public abstract class SDNCConnector { + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCConnector.class); + private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger(); + + @Autowired + private Environment env; + + public SDNCResponseCommon send(String content, TypedRequestTunables rt) { + LOGGER.debug("SDNC URL: " + rt.getSdncUrl()); + LOGGER.debug("SDNC Request Body:\n" + content); + + HttpRequestBase method = null; + HttpResponse httpResponse = null; + + try { + int timeout = Integer.parseInt(rt.getTimeout()); + + RequestConfig requestConfig = RequestConfig.custom() + .setSocketTimeout(timeout) + .setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout) + .build(); + + HttpClient client = HttpClientBuilder.create().build(); + + if ("POST".equals(rt.getReqMethod())) { + HttpPost httpPost = new HttpPost(rt.getSdncUrl()); + httpPost.setConfig(requestConfig); + httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_XML)); + method = httpPost; + } else if ("PUT".equals(rt.getReqMethod())) { + HttpPut httpPut = new HttpPut(rt.getSdncUrl()); + httpPut.setConfig(requestConfig); + httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_XML)); + method = httpPut; + } else if ("GET".equals(rt.getReqMethod())) { + HttpGet httpGet = new HttpGet(rt.getSdncUrl()); + httpGet.setConfig(requestConfig); + method = httpGet; + } else if ("DELETE".equals(rt.getReqMethod())) { + HttpDelete httpDelete = new HttpDelete(rt.getSdncUrl()); + httpDelete.setConfig(requestConfig); + method = httpDelete; + } + + + String userCredentials = CryptoUtils.decryptProperty(env.getProperty(Constants.SDNC_AUTH_PROP), + Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY); + String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + if(null != method) { + method.setHeader("Authorization", authorization); + method.setHeader("Accept", "application/yang.data+xml"); + } + else { + LOGGER.debug("method is NULL:"); + } + + + + httpResponse = client.execute(method); + + String responseContent = null; + if (httpResponse.getEntity() != null) { + responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); + } + + int statusCode = httpResponse.getStatusLine().getStatusCode(); + String statusMessage = httpResponse.getStatusLine().getReasonPhrase(); + + LOGGER.debug("SDNC Response: " + statusCode + " " + statusMessage + + (responseContent == null ? "" : System.lineSeparator() + responseContent)); + + if (httpResponse.getStatusLine().getStatusCode() >= 300) { + String errMsg = "SDNC returned " + statusCode + " " + statusMessage; + + String errors = analyzeErrors(responseContent); + if (errors != null) { + errMsg += " " + errors; + } + + logError(errMsg); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg); + return createErrorResponse(statusCode, errMsg, rt); + } + + httpResponse = null; + + if(null != method) { + method.reset(); + } + else { + LOGGER.debug("method is NULL:"); + } + + method = null; + + LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", ""); + return createResponseFromContent(statusCode, statusMessage, responseContent, rt); + + } catch (SocketTimeoutException | ConnectTimeoutException e) { + String errMsg = "Request to SDNC timed out"; + logError(errMsg, e); + return createErrorResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg, rt); + + } catch (Exception e) { + String errMsg = "Error processing request to SDNC"; + logError(errMsg, e); + return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg, rt); + + } finally { + if (httpResponse != null) { + try { + EntityUtils.consume(httpResponse.getEntity()); + } catch (Exception e) { + LOGGER.debug("Exception:", e); + } + } + + if (method != null) { + try { + method.reset(); + } catch (Exception e) { + LOGGER.debug("Exception:", e); + } + } + } + } + + protected void logError(String errMsg) { + LOGGER.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", + MsoLogger.ErrorCode.AvailabilityError, errMsg); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg); + } + + protected void logError(String errMsg, Throwable t) { + LOGGER.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", + MsoLogger.ErrorCode.AvailabilityError, errMsg, t); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg); + } + + /** + * Generates a response object from content received from SDNC. The response + * object may be a success response object or an error response object. This + * method must be overridden by the subclass to return the correct object type. + * @param statusCode the response status code from SDNC (e.g. 200) + * @param statusMessage the response status message from SDNC (e.g. "OK") + * @param responseContent the body of the response from SDNC (possibly null) + * @param rt request tunables + * @return a response object + */ + protected abstract SDNCResponseCommon createResponseFromContent(int statusCode, + String statusMessage, String responseContent, TypedRequestTunables rt); + + /** + * Generates an error response object. This method must be overridden by the + * subclass to return the correct object type. + * @param statusCode the response status code (from SDNC, or internally generated) + * @param errMsg the error message (normally a verbose explanation of the error) + * @param rt request tunables + * @return an error response object + */ + protected abstract SDNCErrorCommon createErrorResponse(int statusCode, + String errMsg, TypedRequestTunables rt); + + /** + * Called by the send() method to analyze errors that may be encoded in the + * content of non-2XX responses. By default, this method tries to parse the + * content as a restconf error. + * <pre> + * xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf" + * </pre> + * If an error (or errors) can be obtained from the content, then the result + * is a string in this format: + * <pre> + * [error-type:TYPE, error-tag:TAG, error-message:MESSAGE] ... + * </pre> + * If no error could be obtained from the content, then the result is null. + * <p> + * The subclass can override this method to provide another implementation. + */ + protected String analyzeErrors(String content) { + if (content == null || content.isEmpty()) { + return null; + } + + // Confirmed with Andrew Shen on 11/1/16 that SDNC will send content like + // this in error responses (non-2XX response codes) to "agnostic" service + // requests. + // + // <errors xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf"> + // <error> + // <error-type>protocol</error-type> + // <error-tag>malformed-message</error-tag> + // <error-message>Error parsing input: The element type "input" must be terminated by the matching end-tag "</input>".</error-message> + // </error> + // </errors> + + StringBuilder output = null; + + try { + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); + documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + InputSource source = new InputSource(new StringReader(content)); + Document doc = documentBuilderFactory.newDocumentBuilder().parse(source); + NodeList errors = (NodeList) xpath.evaluate("errors/error", doc, XPathConstants.NODESET); + + for (int i = 0; i < errors.getLength(); i++) + { + Element error = (Element) errors.item(i); + + String info = ""; + + try { + String errorType = xpath.evaluate("error-type", error); + info += "error-type:" + errorType; + } catch (XPathExpressionException e) { + LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "", + MsoLogger.ErrorCode.DataError, "XPath Exception", e); + } + + try { + String errorTag = xpath.evaluate( "error-tag", error); + if (!info.isEmpty()) { + info += ", "; + } + info += "error-tag:" + errorTag; + } catch (XPathExpressionException e) { + LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "", + MsoLogger.ErrorCode.DataError, "XPath Exception", e); + } + + try { + String errorMessage = xpath.evaluate("error-message", error); + if (!info.isEmpty()) { + info += ", "; + } + info += "error-message:" + errorMessage; + } catch (Exception e) { + LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "", + MsoLogger.ErrorCode.DataError, "XPath Exception", e); + } + + if (!info.isEmpty()) { + if (output == null) { + output = new StringBuilder("[" + info + "]"); + } else { + output.append(" [").append(info).append("]"); + } + } + } + } catch (Exception e) { + LOGGER.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "", + MsoLogger.ErrorCode.DataError, "Exception while analyzing errors", e); + } + + return output.toString(); + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java new file mode 100644 index 0000000000..2fd39df4e9 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import java.io.IOException; +import java.io.StringReader; +import java.net.HttpURLConnection; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.onap.so.adapters.sdncrest.SDNCErrorCommon; +import org.onap.so.adapters.sdncrest.SDNCResponseCommon; +import org.onap.so.adapters.sdncrest.SDNCServiceError; +import org.onap.so.adapters.sdncrest.SDNCServiceResponse; +import org.onap.so.logger.MsoLogger; +import org.springframework.stereotype.Component; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * SDNCConnector for "agnostic" API services. + */ + +@Component +public class SDNCServiceRequestConnector extends SDNCConnector { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,SDNCServiceRequestConnector.class); + @Override + protected SDNCResponseCommon createResponseFromContent(int statusCode, String statusMessage, + String responseContent, TypedRequestTunables rt) { + try { + return parseResponseContent(responseContent); + } catch (ParseException e) { + LOGGER.error(e); + return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt); + }catch (Exception e) { + LOGGER.error(e); + return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt); + } + } + + @Override + protected SDNCErrorCommon createErrorResponse(int statusCode, String errMsg, + TypedRequestTunables rt) { + return new SDNCServiceError(rt.getReqId(), String.valueOf(statusCode), errMsg, "Y"); + } + + /** + * Parses SDNC synchronous service response content or service notification content. + * If the content can be parsed and contains all required elements, then an object + * is returned. The type of the returned object depends on the response code + * contained in the content. For 2XX response codes, an SDNCServiceResponse is + * returned. Otherwise, an SDNCServiceError is returned. If the content cannot + * be parsed, or if the content does not contain all required elements, a parse + * exception is thrown. This method performs no logging or alarming. + * @throws ParseException on error + */ + public static SDNCResponseCommon parseResponseContent(String responseContent) + throws ParseException,ParserConfigurationException, SAXException, IOException{ + + // Note: this document builder is not namespace-aware, so namespaces are ignored. + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); + documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + InputSource source = new InputSource(new StringReader(responseContent)); + Document doc = documentBuilderFactory.newDocumentBuilder().parse(source); + + // Find the configuration-response-common child under the root element. + // The root element is expected to be an "output" element, but we don't really care. + + Element root = doc.getDocumentElement(); + Element configurationResponseCommon = null; + + for (Element child : SDNCAdapterUtils.childElements(root)) { + if ("configuration-response-common".equals(child.getNodeName())) { + configurationResponseCommon = child; + break; + } + } + + if (configurationResponseCommon == null) { + throw new ParseException("No configuration-response-common element in SDNC response", 0); + } + + // Process the children of configuration-response-common. + + String responseCode = null; + String responseMessage = null; + String svcRequestId = null; + String ackFinalIndicator = null; + List<Element> responseParameters = new ArrayList<>(); + + for (Element child : SDNCAdapterUtils.childElements(configurationResponseCommon)) { + if ("response-code".equals(child.getNodeName())) { + responseCode = child.getTextContent(); + } else if ("response-message".equals(child.getNodeName())) { + responseMessage = child.getTextContent(); + } else if ("svc-request-id".equals(child.getNodeName())) { + svcRequestId = child.getTextContent(); + } else if ("ack-final-indicator".equals(child.getNodeName())) { + ackFinalIndicator = child.getTextContent(); + } else if ("response-parameters".equals(child.getNodeName())) { + responseParameters.add(child); + } + } + + // svc-request-id is mandatory. + + if (svcRequestId == null || svcRequestId.isEmpty()) { + throw new ParseException("No svc-request-id in SDNC response", 0); + } + + // response-code is mandatory. + + if (responseCode == null || responseCode.isEmpty()) { + throw new ParseException("No response-code in SDNC response", 0); + } + + // ack-final-indicator is optional: default to "Y". + + if (ackFinalIndicator == null || ackFinalIndicator.trim().isEmpty()) { + ackFinalIndicator = "Y"; + } + + if (!ackFinalIndicator.equals("Y") && !"N".equals(ackFinalIndicator)) { + throw new ParseException("Invalid ack-final-indicator in SDNC response: '" + ackFinalIndicator + "'", 0); + } + + // response-message is optional. If the value is empty, omit it from the response object. + + if (responseMessage != null && responseMessage.isEmpty()) { + responseMessage = null; + } + + // If the response code in the message from SDNC was not 2XX, return SDNCServiceError. + + if (!responseCode.matches("2[0-9][0-9]") && !responseCode.equals("0")) { + // Not a 2XX response. Return SDNCServiceError. + return new SDNCServiceError(svcRequestId, responseCode, responseMessage, ackFinalIndicator); + } + + // Create a success response object. + + SDNCServiceResponse response = new SDNCServiceResponse(svcRequestId, + responseCode, responseMessage, ackFinalIndicator); + + // Process any response-parameters that might be present. + + for (Element element : responseParameters) { + String tagName = null; + String tagValue = null; + + for (Element child : SDNCAdapterUtils.childElements(element)) { + if ("tag-name".equals(child.getNodeName())) { + tagName = child.getTextContent(); + } else if ("tag-value".equals(child.getNodeName())) { + tagValue = child.getTextContent(); + } + } + + // tag-name is mandatory + + if (tagName == null) { + throw new ParseException("Missing tag-name in SDNC response parameter", 0); + } + + // tag-value is optional. If absent, make it an empty string so we don't + // end up with null values in the parameter map. + + if (tagValue == null) { + tagValue = ""; + } + + response.addParam(tagName, tagValue); + } + + return response; + + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java new file mode 100644 index 0000000000..270b1bd99c --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java @@ -0,0 +1,230 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import java.io.StringWriter; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.http.HttpStatus; +import org.onap.so.adapters.sdnc.exception.SDNCAdapterException; +import org.onap.so.adapters.sdncrest.RequestInformation; +import org.onap.so.adapters.sdncrest.SDNCErrorCommon; +import org.onap.so.adapters.sdncrest.SDNCResponseCommon; +import org.onap.so.adapters.sdncrest.SDNCServiceError; +import org.onap.so.adapters.sdncrest.SDNCServiceRequest; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +@Component +public class SDNCServiceRequestTask { + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCServiceRequestTask.class); + + @Autowired + private SDNCServiceRequestConnector connector; + + @Autowired + MapTypedRequestTunablesData mapTunables; + + @Autowired + private BPRestCallback bpRestCallback; + + @Async + public void runRequest(SDNCServiceRequest request,String msoRequestId,String msoServiceInstanceId,String myUrlSuffix) throws SDNCAdapterException + { + MsoLogger.setLogContext(msoRequestId, msoServiceInstanceId); + MsoLogger.setServiceName(getClass().getSimpleName()); + + String sdncRequestId = request.getSdncRequestId(); + String sdncService = request.getSdncService(); + String sdncOperation = request.getSdncOperation(); + + TypedRequestTunables rt = new TypedRequestTunables(sdncRequestId, myUrlSuffix); + rt.setServiceKey(sdncService, sdncOperation); + TypedRequestTunables mappedTunables = mapTunables.setTunables(rt); + if (!mappedTunables.getError().isEmpty()) { + // Note that the error was logged and alarmed by setTunables() + SDNCServiceError error = new SDNCServiceError(request.getSdncRequestId(), + String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR), mappedTunables.getError(), "Y"); + bpRestCallback.send(request.getBPNotificationUrl(), error.toJson()); + return; + } + + String xml = genSdncReq(request, mappedTunables); + + long sdncStartTime = System.currentTimeMillis(); + SDNCResponseCommon response = connector.send(xml, mappedTunables); + + if (response instanceof SDNCErrorCommon) { + LOGGER.recordMetricEvent(sdncStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + "Received success response from SDNC", "SDNC", sdncService + "." + sdncOperation, null); + } else { + LOGGER.recordMetricEvent(sdncStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, + "Received error response from SDNC", "SDNC", sdncService + "." + sdncOperation, null); + } + + long bpStartTime = System.currentTimeMillis(); + boolean callbackSuccess = bpRestCallback.send(request.getBPNotificationUrl(), response.toJson()); + + if (callbackSuccess) { + LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + "Sent notification", "BPMN", request.getBPNotificationUrl(), null); + } else { + LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, + "Failed to send notification", "BPMN", request.getBPNotificationUrl(), null); + } + } + + private Element addChild(Element parent, String tag) { + Element child = parent.getOwnerDocument().createElement(tag); + parent.appendChild(child); + return child; + } + + private void addTextChild(Element parent, String tag, String text) { + if (text != null) { + Element child = parent.getOwnerDocument().createElement(tag); + child.setTextContent(text); + parent.appendChild(child); + } + } + + private String genSdncReq(SDNCServiceRequest request, TypedRequestTunables rt) { + Document doc; + + try { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + + doc = documentBuilder.newDocument(); + Element root = doc.createElementNS(rt.getNamespace(), "input"); + doc.appendChild(root); + + Element hdr = addChild(root, rt.getHeaderName()); + addTextChild(hdr, "svc-request-id", rt.getReqId()); + addTextChild(hdr, "svc-notification-url", rt.getMyUrl()); + + RequestInformation requestInfo = request.getRequestInformation(); + Element requestInformation = addChild(root, "request-information"); + addTextChild(requestInformation, "request-id", requestInfo.getRequestId()); + + + if(requestInfo.getRequestAction()!= null) { + addTextChild(requestInformation, "request-action", + requestInfo.getRequestAction()); + } + if(requestInfo.getRequestSubAction()!= null) { + addTextChild(requestInformation, "request-sub-action", + requestInfo.getRequestSubAction()); + } + if(requestInfo.getOrderNumber() != null && + !requestInfo.getOrderNumber().isEmpty() ) { + addTextChild(requestInformation, "order-number", + requestInfo.getOrderNumber()); + } + + if(requestInfo.getOrderVersion() != null && + !requestInfo.getOrderVersion().isEmpty() ) { + addTextChild(requestInformation, "order-version", + requestInfo.getOrderVersion()); + } + + + addTextChild(requestInformation, "source", requestInfo.getSource()); + addTextChild(requestInformation, "notification-url", requestInfo.getNotificationUrl()); + + Element serviceInformation = addChild(root, "service-information"); + addTextChild(serviceInformation, "service-type", request.getServiceInformation().getServiceType()); + addTextChild(serviceInformation, "service-instance-id", request.getServiceInformation().getServiceInstanceId()); + addTextChild(serviceInformation, "subscriber-name", request.getServiceInformation().getSubscriberName()); + addTextChild(serviceInformation, "subscriber-global-id", request.getServiceInformation().getSubscriberGlobalId()); + + Element agnosticServiceInformation = addChild(root, "agnostic-service-information"); + addTextChild(agnosticServiceInformation, "operation", request.getSdncOperation()); + addTextChild(agnosticServiceInformation, "service", request.getSdncService()); + + // anydata is mandatory in the SDNC schema, so if the data we got is null, + // set use an empty string instead to ensure we generate an empty element. + + String anydata = request.getSdncServiceData(); + if (anydata == null) { + anydata = ""; + } + + // content-type is also mandatory. + + String contentType = request.getSdncServiceDataType(); + + if (contentType == null || contentType.isEmpty()) { + if (anydata.isEmpty()) { + contentType = "XML"; + } else { + if (anydata.startsWith("<")) { + contentType = "XML"; + } else { + contentType = "JSON"; + } + } + } + + addTextChild(agnosticServiceInformation, "content-type", contentType); + addTextChild(agnosticServiceInformation, "anydata", anydata); + } catch (Exception e) { + LOGGER.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", + MsoLogger.ErrorCode.BusinessProcesssError, "Exception in genSdncReq", e); + return null; + } + + String xml; + + try { + StringWriter writer = new StringWriter(); + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,""); + Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + transformer.transform(new DOMSource(doc), new StreamResult(writer)); + xml = writer.toString(); + } catch (Exception e) { + LOGGER.error(MessageEnum.RA_ERROR_CONVERT_XML2STR, "", "", + MsoLogger.ErrorCode.DataError, "Exception - domToStr", e); + return null; + } + + LOGGER.trace("Formatted SDNC service request XML:\n" + xml); + return xml; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java new file mode 100644 index 0000000000..72a23282d9 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.onap.so.adapters.sdnc.impl.Constants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoAlarmLogger; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** + * A temporary interface to support notifications from SNIRO to BPMN. + * We added this to the SDNC adapter because we didn't have time to + * develop a SNIRO adapter in 1702. + */ +@Path("/") +@Component +public class SNIROResponse { + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SNIROResponse.class); + private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger(); + + @Autowired + private Environment env; + + @Autowired + private BPRestCallback callback; + + @POST + @Path("/SDNCNotify/SNIROResponse/{correlator}") + @Consumes("*/*") + @Produces({MediaType.TEXT_PLAIN}) + public Response serviceNotification(@PathParam("correlator") String correlator, String content) { + LOGGER.info(MessageEnum.RA_RECEIVE_SDNC_NOTIF, content, "SDNC", "SDNCNotify/SNIROResponse"); + + long startTime = System.currentTimeMillis(); + + String bpUrl = env.getProperty(Constants.BPEL_REST_URL_PROP, ""); + + if (bpUrl == null || bpUrl.equals("")) { + String error = "Missing configuration for: " + Constants.BPEL_REST_URL_PROP; + LOGGER.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, Constants.BPEL_REST_URL_PROP, "SDNC", "", + MsoLogger.ErrorCode.DataError, "Missing config param"); + ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, error); + return Response.status(HttpServletResponse.SC_BAD_REQUEST).entity(error).build(); + } + + long bpStartTime = System.currentTimeMillis(); + boolean callbackSuccess = callback.send(bpUrl, "SNIROResponse", correlator, content); + + if (callbackSuccess) { + LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + "Sent notification", "BPMN", bpUrl, null); + LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful"); + } else { + LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, + "Failed to send notification", "BPMN", bpUrl, null); + LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, + "Failed to send notification"); + } + + return Response.status(204).build(); + } +}
\ No newline at end of file diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java new file mode 100644 index 0000000000..6331d6aaae --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.sdncrest; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.onap.so.adapters.sdnc.impl.Constants; +import org.onap.so.logger.MsoLogger; + +/** + * Typed Request Tunables. Each entry is identified by a TYPE in the property name. + * Different types can have different keys. + * <p> + * General format: + * <pre> + * org.onap.so.adapters.sdnc.TYPE.KEY1[.KEY2...]=METHOD|TIMEOUT|URL|HEADER|NAMESPACE + * </pre> + * Currently supported type(s): service + * <pre> + * org.onap.so.adapters.sdnc.service.SERVICE.OPERATION=METHOD|TIMEOUT|URL|HEADER|NAMESPACE + * </pre> + */ +public class TypedRequestTunables { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, TypedRequestTunables.class); + + private String reqId; + private String myUrlSuffix; + private String key = null; + private String error = ""; + + // tunables (all are required) + private String reqMethod = null; + private String timeout = null; + private String sdncUrl = null; + private String headerName = null; + private String namespace = null; + private String myUrl = null; + + public TypedRequestTunables(TypedRequestTunables reqTunableOriginal) { + this.reqId = reqTunableOriginal.getReqId(); + this.myUrlSuffix = reqTunableOriginal.getMyUrlSuffix(); + this.key = reqTunableOriginal.getKey(); + this.error = reqTunableOriginal.getError(); + this.reqMethod = reqTunableOriginal.getReqMethod(); + this.timeout = reqTunableOriginal.getTimeout(); + this.sdncUrl = reqTunableOriginal.getSdncUrl(); + this.headerName = reqTunableOriginal.getHeaderName(); + this.namespace = reqTunableOriginal.getNamespace(); + this.myUrl = reqTunableOriginal.getMyUrl(); + } + + public TypedRequestTunables(String reqId, String myUrlSuffix) { + this.reqId = reqId; + this.myUrlSuffix = myUrlSuffix; + } + + /** + * Sets the key for a service request: + * <pre> + * org.onap.so.adapters.sdnc.service.SERVICE.OPERATION + * </pre> + * @param service the sdncService + * @param operation the sdncOperation + */ + public void setServiceKey(String service, String operation) { + key = Constants.REQUEST_TUNABLES + ".service." + service + "." + operation; + LOGGER.debug("Generated " + getClass().getSimpleName() + " key: " + key); + } + + /** + * Gets the SDNC request ID. + */ + public String getReqId() { + return reqId; + } + + /** + * Gets the generated key. + */ + public String getKey() { + return key; + } + + /** + * Gets the most recent error, or null if there was no error. + */ + public String getError() { + return error; + } + + public String getReqMethod() { + return reqMethod; + } + + public String getTimeout() { + return timeout; + } + + public String getSdncUrl() { + return sdncUrl; + } + + public String getHeaderName() { + return headerName; + } + + public String getNamespace() { + return namespace; + } + + /** + * Gets the SDNC adapter notification URL, trimmed of trailing '/' characters. + */ + public String getMyUrl() { + return myUrl; + } + + public String getMyUrlSuffix() { + return myUrlSuffix; + } + + public void setKey(String key) { + this.key = key; + } + + public void setError(String error) { + this.error = error; + } + + public void setReqMethod(String reqMethod) { + this.reqMethod = reqMethod; + } + + public void setTimeout(String timeout) { + this.timeout = timeout; + } + + public void setSdncUrl(String sdncUrl) { + this.sdncUrl = sdncUrl; + } + + public void setHeaderName(String headerName) { + this.headerName = headerName; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public void setMyUrl(String myUrl) { + this.myUrl = myUrl; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("reqId", reqId).append("myUrlSuffix", myUrlSuffix).append("key", key) + .append("error", error).append("reqMethod", reqMethod).append("timeout", timeout) + .append("sdncUrl", sdncUrl).append("headerName", headerName).append("namespace", namespace) + .append("myUrl", myUrl).toString(); + } + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java new file mode 100644 index 0000000000..991126f868 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc.util; + + +public class SDNCRequestIdUtil { + // Add private constructor to prevent instance creation. + private SDNCRequestIdUtil () {} + + public static String getSDNCOriginalRequestId (String newRequestId) { + + // Camunda scripts will add postfix, such as -1, -2, on the original requestID, to make sure requestID is unique while sending request to SDNC + // In order to use the unique requestID in logging, need to remove the postfix added by the Camunda scripts + // Verify whether the requestId is a valid UUID with postfix (-1, -2). If yes, it should contain 5 times char '-', since valid UUID contains 4 times '-' + // If the requestId is not a valid UUID with postfix, we do nothing + if (newRequestId.split("-").length == 6) { + return newRequestId.substring(0, newRequestId.lastIndexOf('-')); + } + return newRequestId; + } +} |