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