2f64a21c6e80024474bf82281c067868d383a68c
[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 : APPC
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  *
19  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  * ============LICENSE_END=========================================================
21  */
22 package org.onap.appc.flow.controller.executorImpl;
23
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import com.sun.jersey.api.client.Client;
27 import com.sun.jersey.api.client.ClientResponse;
28 import com.sun.jersey.api.client.ClientResponse.Status;
29 import com.sun.jersey.api.client.WebResource;
30 import com.sun.jersey.api.client.config.DefaultClientConfig;
31 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
32 import com.sun.jersey.client.urlconnection.HTTPSProperties;
33 import java.net.URI;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.Map;
37 import java.util.Optional;
38 import javax.net.ssl.HostnameVerifier;
39 import javax.net.ssl.SSLContext;
40 import javax.ws.rs.HttpMethod;
41 import javax.ws.rs.core.MediaType;
42 import org.apache.commons.lang3.StringUtils;
43 import org.onap.appc.flow.controller.data.Response;
44 import org.onap.appc.flow.controller.data.Transaction;
45 import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface;
46 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
47
48
49 public class RestExecutor implements FlowExecutorInterface {
50
51     private static final EELFLogger log = EELFManager.getInstance().getLogger(RestExecutor.class);
52
53     @Override
54     public Map<String, String> execute(Transaction transaction, SvcLogicContext ctx) throws Exception{
55         log.info("Configuring Rest Operation....." + transaction.toString());
56         Map<String, String> outputMessage = new HashMap<>();
57         Client client = null;
58
59         try {
60             System.setProperty("jsse.enableSNIExtension", "false");
61             SSLContext sslContext = SSLContext.getInstance("SSL");
62             sslContext.init(null, new javax.net.ssl.TrustManager[] {new SecureRestClientTrustManager()}, null);
63             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
64             defaultClientConfig.getProperties().put(
65                     HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
66                     new HTTPSProperties(getHostnameVerifier(), sslContext));
67             client = createClient(defaultClientConfig);
68             client.addFilter(new HTTPBasicAuthFilter(transaction.getId(), transaction.getPswd()));
69             WebResource webResource = client.resource(new URI(transaction.getExecutionEndPoint()));
70             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
71
72             ClientResponse clientResponse = getClientResponse(transaction, webResource)
73                     .orElseThrow(() -> new Exception(
74                     "Cannot determine the state of : "
75                     + transaction.getActionLevel()
76                     + " HTTP response is null"));
77
78             processClientResponse(clientResponse, transaction, outputMessage);
79
80             log.info("Completed Rest Operation.....");
81
82         } catch (Exception e) {
83             log.debug("failed in RESTCONT Action ("
84                     + transaction.getExecutionRPC()
85                     + ") for the resource "
86                     + transaction.getExecutionEndPoint()
87                     + ", fault message :"
88                     + e.getMessage());
89             throw new Exception("Error While Sending Rest Request", e);
90
91         } finally {
92             if(client != null) {
93                 client.destroy();
94             }
95         }
96         return outputMessage;
97     }
98
99     private HostnameVerifier getHostnameVerifier() {
100         return (hostname, sslSession) -> true;
101     }
102
103     Client createClient(DefaultClientConfig defaultClientConfig) {
104         return Client.create(defaultClientConfig);
105     }
106
107     private Optional<ClientResponse> getClientResponse(Transaction transaction, WebResource webResource) {
108         String responseDataType=MediaType.APPLICATION_JSON;
109         String requestDataType=MediaType.APPLICATION_JSON;
110         ClientResponse clientResponse = null;
111
112         log.info("Starting Rest Operation.....");
113         if(HttpMethod.GET.equalsIgnoreCase(transaction.getExecutionRPC())) {
114             clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
115         }else if(HttpMethod.POST.equalsIgnoreCase(transaction.getExecutionRPC())) {
116             clientResponse = webResource.type(requestDataType).post(ClientResponse.class, transaction.getPayload());
117         }else if(HttpMethod.PUT.equalsIgnoreCase(transaction.getExecutionRPC())) {
118             clientResponse = webResource.type(requestDataType).put(ClientResponse.class, transaction.getPayload());
119         }else if(HttpMethod.DELETE.equalsIgnoreCase(transaction.getExecutionRPC())) {
120             clientResponse = webResource.delete(ClientResponse.class);
121         }
122         return Optional.ofNullable(clientResponse);
123     }
124
125     private void processClientResponse (ClientResponse clientResponse,
126                                         Transaction transaction,
127                                         Map<String, String> outputMessage ) throws Exception {
128
129         if(clientResponse.getStatus() == Status.OK.getStatusCode()) {
130             Response response = new Response();
131             response.setResponseCode(String.valueOf(Status.OK.getStatusCode()));
132             transaction.setResponses(Collections.singletonList(response));
133             outputMessage.put("restResponse", clientResponse.getEntity(String.class));
134         } else {
135             String errorMsg = clientResponse.getEntity(String.class);
136             if (StringUtils.isNotBlank(errorMsg)) {
137                 log.debug("Error Message from Client Response" + errorMsg);
138             }
139             throw new Exception("Cannot determine the state of : "
140                     + transaction.getActionLevel()
141                     + " HTTP error code : "
142                     + clientResponse.getStatus());
143         }
144     }
145 }