0d7357a4a39ad25a187e50d7754350fcfef95e8c
[appc.git] /
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         EncryptionTool et = EncryptionTool.getInstance();
119         String responseDataType=MediaType.APPLICATION_JSON;
120         String requestDataType=MediaType.APPLICATION_JSON;
121
122         try{
123             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
124             System.setProperty("jsse.enableSNIExtension", "false");
125             SSLContext sslContext = null;
126             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
127             sslContext = SSLContext.getInstance("SSL");
128             sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null);
129             defaultClientConfig.getProperties().put(
130                     com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
131                     new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext));
132             client = Client.create(defaultClientConfig);
133         String password = et.decrypt(props.getProperty("appc.upload.pass"));
134         client.addFilter(new HTTPBasicAuthFilter(props.getProperty("appc.upload.user"),password));
135             webResource = client.resource(new URI(props.getProperty("appc.upload.provider.url")));
136             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
137             log.info("Starting Rest Operation.....");
138             if(HttpMethod.GET.equalsIgnoreCase(rpc)){
139                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
140             }else if(HttpMethod.POST.equalsIgnoreCase(rpc)){
141                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, payload);
142             }else if(HttpMethod.PUT.equalsIgnoreCase(rpc)){
143                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class,payload);
144             }else if(HttpMethod.DELETE.equalsIgnoreCase(rpc)){
145                 clientResponse = webResource.delete(ClientResponse.class);
146             }
147
148             if(!(clientResponse.getStatus() == 200))
149                                 throw new Exception("HTTP error code : " + clientResponse.getStatus());
150
151             
152             log.info("Completed Rest Operation.....");
153
154         }catch (Exception e) {
155             e.printStackTrace();
156             log.debug("failed in RESTCONT Action with falut message :"+e.getMessage());
157             throw new Exception("Error While Sending Rest Request" + e.getMessage());
158         }
159         finally {
160             // clean up.
161             webResource = null;
162             if(client != null){
163                 client.destroy();
164                 client = null;
165             }
166         }
167
168         return outputMessage;
169     }
170     private String getRandom() {
171         SecureRandom random = new SecureRandom();
172         int num = random.nextInt(100000);
173         String formatted = String.format("%05d", num); 
174         return formatted;
175     }
176     
177     private HostnameVerifier getHostnameVerifier() {
178         return new HostnameVerifier() {
179             @Override
180             public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
181                 return true;
182             }
183         };
184     }
185 }