Update license header in appc-inbound files
[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  * 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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.design.services.util;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.fasterxml.jackson.databind.node.ObjectNode;
31 import com.sun.jersey.api.client.Client;
32 import com.sun.jersey.api.client.ClientResponse;
33 import com.sun.jersey.api.client.WebResource;
34 import com.sun.jersey.api.client.config.DefaultClientConfig;
35 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
36 import com.sun.jersey.client.urlconnection.HTTPSProperties;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.net.URI;
41 import java.util.HashMap;
42 import java.util.Map;
43 import java.util.Properties;
44 import javax.net.ssl.HostnameVerifier;
45 import javax.net.ssl.SSLContext;
46 import javax.ws.rs.HttpMethod;
47 import javax.ws.rs.core.MediaType;
48
49
50 public class ArtifactHandlerClient {
51
52     private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerClient.class);
53     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
54     private Properties props = new Properties();
55
56     public ArtifactHandlerClient() throws IOException {
57         String propDir = System.getenv(SDNC_CONFIG_DIR_VAR);
58         if (propDir == null) {
59             throw new IOException(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
60         }
61         String propFile = propDir + "/" + DesignServiceConstants.DESIGN_SERVICE_PROPERTIES;
62         InputStream propStream = new FileInputStream(propFile);
63         try {
64             props.load(propStream);
65         } catch (Exception e) {
66             throw new IOException("Could not load properties file " + propFile, e);
67         } finally {
68             try {
69                 propStream.close();
70             } catch (Exception e) {
71                 log.warn("Could not close FileInputStream", e);
72             }
73         }
74     }
75
76     public String createArtifactData(String payload, String requestID) throws IOException {
77
78         ObjectMapper objectMapper = new ObjectMapper();
79         JsonNode payloadObject = objectMapper.readTree(payload);
80
81         ObjectNode json = objectMapper.createObjectNode();
82         String artifactName = payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue();
83         String artifactVersion = payloadObject.get(DesignServiceConstants.ARTIFACT_VERSOIN).textValue();
84         String artifactContents = payloadObject.get(DesignServiceConstants.ARTIFACT_CONTENTS).textValue();
85
86         ObjectNode requestInfo = objectMapper.createObjectNode();
87         requestInfo.put(DesignServiceConstants.REQUETS_ID, requestID);
88         requestInfo.put(DesignServiceConstants.REQUEST_ACTION, "StoreSdcDocumentRequest");
89         requestInfo.put(DesignServiceConstants.SOURCE, DesignServiceConstants.DESIGN_TOOL);
90
91         ObjectNode docParams = objectMapper.createObjectNode();
92         docParams.put(DesignServiceConstants.ARTIFACT_VERSOIN, artifactVersion);
93         docParams.put(DesignServiceConstants.ARTIFACT_NAME, artifactName);
94         docParams.put(DesignServiceConstants.ARTIFACT_CONTENTS, artifactContents);
95
96         json.put(DesignServiceConstants.REQUEST_INFORMATION, requestInfo);
97         json.put(DesignServiceConstants.DOCUMENT_PARAMETERS, docParams);
98         log.info("Final data =" + json.toString());
99         return String.format("{\"input\": %s}", json.toString());
100     }
101
102     public Map<String, String> execute(String payload, String rpc) throws IOException {
103         log.info("Configuring Rest Operation for Payload " + payload + " RPC : " + rpc);
104         Map<String, String> outputMessage = new HashMap<>();
105         Client client = null;
106         WebResource webResource;
107         ClientResponse clientResponse = null;
108         EncryptionTool et = EncryptionTool.getInstance();
109         String responseDataType = MediaType.APPLICATION_JSON;
110         String requestDataType = MediaType.APPLICATION_JSON;
111
112         try {
113             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
114             System.setProperty("jsse.enableSNIExtension", "false");
115             SSLContext sslContext;
116             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
117             sslContext = SSLContext.getInstance("SSL");
118             sslContext.init(null, new javax.net.ssl.TrustManager[]{secureRestClientTrustManager}, null);
119
120             defaultClientConfig
121                 .getProperties()
122                 .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(getHostnameVerifier(), sslContext));
123
124             client = Client.create(defaultClientConfig);
125             String password = et.decrypt(props.getProperty("appc.upload.pass"));
126             client.addFilter(new HTTPBasicAuthFilter(props.getProperty("appc.upload.user"), password));
127             webResource = client.resource(new URI(props.getProperty("appc.upload.provider.url")));
128             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
129             log.info("Starting Rest Operation.....");
130             if (HttpMethod.GET.equalsIgnoreCase(rpc)) {
131                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
132             } else if (HttpMethod.POST.equalsIgnoreCase(rpc)) {
133                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, payload);
134             } else if (HttpMethod.PUT.equalsIgnoreCase(rpc)) {
135                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class, payload);
136             } else if (HttpMethod.DELETE.equalsIgnoreCase(rpc)) {
137                 clientResponse = webResource.delete(ClientResponse.class);
138             }
139             validateClientResponse(clientResponse);
140             log.info("Completed Rest Operation.....");
141
142         } catch (Exception e) {
143             log.debug("failed in RESTCONT Action", e);
144             throw new IOException("Error While Sending Rest Request" + e.getMessage());
145         } finally {
146             // clean up.
147             if (client != null) {
148                 client.destroy();
149             }
150         }
151         return outputMessage;
152     }
153
154     private void validateClientResponse(ClientResponse clientResponse) throws ArtifactHandlerInternalException {
155         if (clientResponse == null) {
156             throw new ArtifactHandlerInternalException("Failed to create client response");
157         }
158         if (clientResponse.getStatus() != 200) {
159             throw new ArtifactHandlerInternalException("HTTP error code : " + clientResponse.getStatus());
160         }
161     }
162
163     private HostnameVerifier getHostnameVerifier() {
164         return (hostname, sslSession) -> true;
165     }
166 }