0f901e0fe67b272fce4bac8b8fa7e415f7e65495
[appc.git] / appc-config / appc-flow-controller / provider / src / main / java / org / onap / 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.onap.appc.flow.controller.executorImpl;
22
23 import java.io.FileInputStream;
24 import java.io.InputStream;
25 import java.net.URI;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.Properties;
29
30 import javax.net.ssl.HostnameVerifier;
31 import javax.net.ssl.SSLContext;
32 import javax.ws.rs.HttpMethod;
33 import javax.ws.rs.core.MediaType;
34
35 import org.apache.commons.lang3.StringUtils;
36 import org.onap.appc.flow.controller.data.Response;
37 import org.onap.appc.flow.controller.data.Transaction;
38 import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface;
39 import org.onap.appc.flow.controller.utils.FlowControllerConstants;
40 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
41 import com.sun.jersey.api.client.Client;
42 import com.sun.jersey.api.client.ClientResponse;
43 import com.sun.jersey.api.client.WebResource;
44 import com.sun.jersey.api.client.config.DefaultClientConfig;
45 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
46 import com.att.eelf.configuration.EELFLogger;
47 import com.att.eelf.configuration.EELFManager;
48
49
50 public class RestExecutor implements FlowExecutorInterface {
51
52     private static final EELFLogger log = EELFManager.getInstance().getLogger(RestExecutor.class);
53     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
54     Properties props = new Properties();
55     public RestExecutor() throws Exception {
56         String propDir = System.getenv(SDNC_CONFIG_DIR_VAR);
57         if (propDir == null)
58             throw new Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
59         String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER;
60         InputStream propStream = new FileInputStream(propFile);
61         try{
62             props.load(propStream);
63         }
64         catch (Exception e){
65             throw new Exception("Could not load properties file " + propFile, e);
66         }
67         finally{
68             try{
69                 propStream.close();
70             }
71             catch (Exception e){
72                 log.warn("Could not close FileInputStream", e);
73             }
74         }
75     }
76     @Override
77     public HashMap<String, String> execute(Transaction transaction, SvcLogicContext ctx) throws Exception{
78         log.info("Configuring Rest Operation....." + transaction.toString());
79         Response response = new Response();
80         HashMap<String, String> outputMessage = new HashMap<String, String>();
81         Client client = null;
82         WebResource webResource = null;
83         ClientResponse clientResponse = null;
84         String responseDataType=MediaType.APPLICATION_JSON;
85         String requestDataType=MediaType.APPLICATION_JSON;
86
87
88         try{
89             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
90             System.setProperty("jsse.enableSNIExtension", "false");
91             SSLContext sslContext = null;
92             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
93             sslContext = SSLContext.getInstance("SSL");
94             sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null);
95             defaultClientConfig.getProperties().put(
96                     com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
97                     new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext));
98             client = Client.create(defaultClientConfig);
99             client.addFilter(new HTTPBasicAuthFilter(transaction.getuId(), transaction.getPswd()));
100             webResource = client.resource(new URI(transaction.getExecutionEndPoint()));
101             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
102
103             log.info("Starting Rest Operation.....");
104             if(HttpMethod.GET.equalsIgnoreCase(transaction.getExecutionRPC())){
105                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
106             }else if(HttpMethod.POST.equalsIgnoreCase(transaction.getExecutionRPC())){
107                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, transaction.getPayload());
108             }else if(HttpMethod.PUT.equalsIgnoreCase(transaction.getExecutionRPC())){
109                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class,transaction.getPayload());
110             }else if(HttpMethod.DELETE.equalsIgnoreCase(transaction.getExecutionRPC())){
111                 clientResponse = webResource.delete(ClientResponse.class);
112             }
113
114             if(clientResponse.getStatus() == 200){
115                 response.setResponseCode(String.valueOf(clientResponse.getStatus()));
116                 ArrayList<Response> responses = new ArrayList<Response>();
117                 responses.add(response);
118                 transaction.setResponses(responses);
119                 outputMessage.put("restResponse", clientResponse.getEntity(String.class));
120             }
121             else{
122
123                 String errorMsg = clientResponse.getEntity(String.class);
124                 if (StringUtils.isNotBlank(errorMsg)) {
125                     log.debug("Error Message from Client Response" + errorMsg);
126                 }
127
128                 throw new Exception("Can not determine the state of : " + transaction.getActionLevel()  + " HTTP error code : "
129                         + clientResponse.getStatus());
130
131             }
132
133             log.info("Completed Rest Operation.....");
134
135         }catch (Exception e) {
136             e.printStackTrace();
137             log.debug("failed in RESTCONT Action ("+transaction.getExecutionRPC()+") for the resource " + transaction.getExecutionEndPoint() + ", falut message :"+e.getMessage());
138             throw new Exception("Error While Sending Rest Request" + e.getMessage());
139         }
140         finally {
141             // clean up.
142             webResource = null;
143             if(client != null){
144                 client.destroy();
145                 client = null;
146             }
147         }
148
149         return outputMessage;
150     }
151
152 private HostnameVerifier getHostnameVerifier() {
153     return new HostnameVerifier() {
154         @Override
155         public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
156             return true;
157         }
158     };
159 }
160
161 }