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