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