4b0aa66f81d55e66f450453ca8faea295dbf4d24
[appc.git] / appc-config / appc-flow-controller / provider / src / main / java / org / openecomp / appc / flow / controller / executorImpl / RestExecutor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property.  All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.appc.flow.controller.executorImpl;
22
23 import java.io.FileInputStream;
24 import java.io.InputStream;
25 import java.net.URI;
26 import java.nio.charset.Charset;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.Properties;
30
31 import javax.net.ssl.HostnameVerifier;
32 import javax.net.ssl.SSLContext;
33 import javax.ws.rs.HttpMethod;
34 import javax.ws.rs.core.MediaType;
35
36 import org.apache.commons.io.IOUtils;
37 import org.openecomp.appc.flow.controller.data.Response;
38 import org.openecomp.appc.flow.controller.data.Transaction;
39 import org.openecomp.appc.flow.controller.interfaces.FlowExecutorInterface;
40 import org.openecomp.appc.flow.controller.utils.FlowControllerConstants;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
42 import com.sun.jersey.api.client.Client;
43 import com.sun.jersey.api.client.ClientResponse;
44 import com.sun.jersey.api.client.WebResource;
45 import com.sun.jersey.api.client.config.DefaultClientConfig;
46 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
47 import com.att.eelf.configuration.EELFLogger;
48 import com.att.eelf.configuration.EELFManager;
49
50
51 public class RestExecutor implements FlowExecutorInterface {
52
53     private static final EELFLogger log = EELFManager.getInstance().getLogger(RestExecutor.class);
54     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
55     Properties props = new Properties();
56     public RestExecutor() throws Exception {    
57         String propDir = System.getenv(SDNC_CONFIG_DIR_VAR);
58         if (propDir == null)
59             throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
60         String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER;
61         InputStream propStream = new FileInputStream(propFile);
62         try{
63             props.load(propStream);
64         }
65         catch (Exception e){
66             throw new Exception("Could not load properties file " + propFile, e);
67         }
68         finally{
69             try{
70                 propStream.close();
71             }
72             catch (Exception e){
73                 log.warn("Could not close FileInputStream", e);
74             }
75         }        
76     }
77     @Override
78     public HashMap<String, String> execute(Transaction transaction, SvcLogicContext ctx) throws Exception{    
79         log.info("Configuring Rest Operation....." + transaction.toString());
80         Response response = new Response();
81         HashMap<String, String> outputMessage = new HashMap<String, String>();
82         Client client = null;
83         WebResource webResource = null;
84         ClientResponse clientResponse = null;
85         String responseDataType=MediaType.APPLICATION_JSON;
86         String requestDataType=MediaType.APPLICATION_JSON;
87         
88         
89         try{
90             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
91             System.setProperty("jsse.enableSNIExtension", "false");
92             SSLContext sslContext = null;
93             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
94             sslContext = SSLContext.getInstance("SSL");
95             sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null);
96             defaultClientConfig.getProperties().put(
97                     com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
98                     new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext));
99             client = Client.create(defaultClientConfig);
100             client.addFilter(new HTTPBasicAuthFilter(transaction.getuId(), transaction.getPswd()));
101             webResource = client.resource(new URI(transaction.getExecutionEndPoint()));
102             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
103
104             log.info("Starting Rest Operation.....");
105             if(HttpMethod.GET.equalsIgnoreCase(transaction.getExecutionRPC())){
106                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
107             }else if(HttpMethod.POST.equalsIgnoreCase(transaction.getExecutionRPC())){
108                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, transaction.getPayload());
109             }else if(HttpMethod.PUT.equalsIgnoreCase(transaction.getExecutionRPC())){
110                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class,transaction.getPayload());
111             }else if(HttpMethod.DELETE.equalsIgnoreCase(transaction.getExecutionRPC())){
112                 clientResponse = webResource.delete(ClientResponse.class);
113             }
114
115             if(clientResponse.getStatus() == 200){
116                 response.setResponseCode(String.valueOf(clientResponse.getStatus()));
117                 ArrayList<Response> responses = new ArrayList<Response>();
118                 responses.add(response);
119                 transaction.setResponses(responses);    
120                 outputMessage.put("restResponse", clientResponse.getEntity(String.class));
121             }
122             else{
123                 throw new Exception("Can not determine the state of : " + transaction.getActionLevel()  + " HTTP error code : "
124                         + clientResponse.getStatus());
125                 
126             }
127             
128             log.info("Completed Rest Operation.....");
129
130         }catch (Exception e) {
131             e.printStackTrace();
132             log.debug("failed in RESTCONT Action ("+transaction.getExecutionRPC()+") for the resource " + transaction.getExecutionEndPoint() + ", falut message :"+e.getMessage());
133             throw new Exception("Error While Sending Rest Request" + e.getMessage());
134         }
135         finally {
136             // clean up.
137             webResource = null;
138             if(client != null){
139                 client.destroy();
140                 client = null;
141             }
142         }
143
144         return outputMessage;
145     }
146     
147 private HostnameVerifier getHostnameVerifier() {
148     return new HostnameVerifier() {
149         @Override
150         public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
151             return true;
152         }
153     };
154 }
155
156 }