87b45eab215a1513c1cf0b698e372fb4a5fdd1a3
[appc.git] / appc-inbound / appc-design-services / provider / src / main / java / org / onap / appc / design / services / util / ArtifactHandlerClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.design.services.util;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.fasterxml.jackson.databind.JsonNode;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import com.fasterxml.jackson.databind.node.ObjectNode;
32 import com.sun.jersey.api.client.Client;
33 import com.sun.jersey.api.client.ClientResponse;
34 import com.sun.jersey.api.client.WebResource;
35 import com.sun.jersey.api.client.config.DefaultClientConfig;
36 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
37 import com.sun.jersey.client.urlconnection.HTTPSProperties;
38 import java.io.FileInputStream;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.net.URI;
42 import java.util.HashMap;
43 import java.util.Map;
44 import java.util.Properties;
45 import javax.net.ssl.HostnameVerifier;
46 import javax.net.ssl.SSLContext;
47 import javax.ws.rs.HttpMethod;
48 import javax.ws.rs.core.MediaType;
49
50
51 public class ArtifactHandlerClient {
52
53     private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerClient.class);
54     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
55     private Properties props = new Properties();
56
57     public ArtifactHandlerClient() throws IOException {
58         String propDir = System.getenv(SDNC_CONFIG_DIR_VAR);
59         if (propDir == null) {
60             throw new IOException(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
61         }
62         String propFile = propDir + "/" + DesignServiceConstants.DESIGN_SERVICE_PROPERTIES;
63         InputStream propStream = new FileInputStream(propFile);
64         try {
65             props.load(propStream);
66         } catch (Exception e) {
67             throw new IOException("Could not load properties file " + propFile, e);
68         } finally {
69             try {
70                 propStream.close();
71             } catch (Exception e) {
72                 log.warn("Could not close FileInputStream", e);
73             }
74         }
75     }
76
77     public String createArtifactData(String payload, String requestID) throws IOException {
78
79         ObjectMapper objectMapper = new ObjectMapper();
80         JsonNode payloadObject = objectMapper.readTree(payload);
81
82         ObjectNode json = objectMapper.createObjectNode();
83         String artifactName = payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue();
84         String artifactVersion = payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN).textValue();
85         String artifactContents = payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS).textValue();
86
87         ObjectNode requestInfo = objectMapper.createObjectNode();
88         requestInfo.put(DesignServiceConstants.REQUETS_ID, requestID);
89         requestInfo.put(DesignServiceConstants.REQUEST_ACTION, "StoreSdcDocumentRequest");
90         requestInfo.put(DesignServiceConstants.SOURCE, DesignServiceConstants.DESIGN_TOOL);
91
92         ObjectNode docParams = objectMapper.createObjectNode();
93         docParams.put(DesignServiceConstants.ARTIFACT_VERSOIN, artifactVersion);
94         docParams.put(DesignServiceConstants.ARTIFACT_NAME, artifactName);
95         docParams.put(DesignServiceConstants.ARTIFACT_CONTENTS, artifactContents);
96
97         json.put(DesignServiceConstants.REQUEST_INFORMATION, requestInfo);
98         json.put(DesignServiceConstants.DOCUMENT_PARAMETERS, docParams);
99         log.info("Final data =" + json.toString());
100         return String.format("{\"input\": %s}", json.toString());
101     }
102
103     public Map<String, String> execute(String payload, String rpc) throws IOException {
104         log.info("Configuring Rest Operation for Payload " + payload + " RPC : " + rpc);
105         Map<String, String> outputMessage = new HashMap<>();
106         Client client = null;
107         WebResource webResource;
108         ClientResponse clientResponse = null;
109         EncryptionTool et = EncryptionTool.getInstance();
110         String responseDataType = MediaType.APPLICATION_JSON;
111         String requestDataType = MediaType.APPLICATION_JSON;
112
113         try {
114             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
115             System.setProperty("jsse.enableSNIExtension", "false");
116             SSLContext sslContext;
117             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
118             sslContext = SSLContext.getInstance("SSL");
119             sslContext.init(null, new javax.net.ssl.TrustManager[]{secureRestClientTrustManager}, null);
120
121             defaultClientConfig
122                 .getProperties()
123                 .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(getHostnameVerifier(), sslContext));
124
125             client = Client.create(defaultClientConfig);
126             String password = et.decrypt(props.getProperty("appc.upload.pass"));
127             client.addFilter(new HTTPBasicAuthFilter(props.getProperty("appc.upload.user"), password));
128             webResource = client.resource(new URI(props.getProperty("appc.upload.provider.url")));
129             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
130             log.info("Starting Rest Operation.....");
131             if (HttpMethod.GET.equalsIgnoreCase(rpc)) {
132                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
133             } else if (HttpMethod.POST.equalsIgnoreCase(rpc)) {
134                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, payload);
135             } else if (HttpMethod.PUT.equalsIgnoreCase(rpc)) {
136                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class, payload);
137             } else if (HttpMethod.DELETE.equalsIgnoreCase(rpc)) {
138                 clientResponse = webResource.delete(ClientResponse.class);
139             }
140             validateClientResponse(clientResponse);
141             log.info("Completed Rest Operation.....");
142
143         } catch (Exception e) {
144             log.debug("failed in RESTCONT Action", e);
145             throw new IOException("Error While Sending Rest Request" + e.getMessage());
146         } finally {
147             // clean up.
148             if (client != null) {
149                 client.destroy();
150             }
151         }
152         return outputMessage;
153     }
154
155     private void validateClientResponse(ClientResponse clientResponse) throws ArtifactHandlerInternalException {
156         if (clientResponse == null) {
157             throw new ArtifactHandlerInternalException("Failed to create client response");
158         }
159         if (clientResponse.getStatus() != 200) {
160             throw new ArtifactHandlerInternalException("HTTP error code : " + clientResponse.getStatus());
161         }
162     }
163
164     private HostnameVerifier getHostnameVerifier() {
165         return (hostname, sslSession) -> true;
166     }
167 }