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