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