Changed to unmaintained
[appc.git] / appc-config / appc-flow-controller / provider / src / main / java / org / onap / appc / flow / controller / executorImpl / RestExecutor.java
1 /*
2  * ONAP : APPC
3  * ================================================================================
4  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
5  * =============================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * * ============LICENSE_END=========================================================
18  */
19 package org.onap.appc.flow.controller.executorImpl;
20
21 import com.att.eelf.configuration.EELFLogger;
22 import com.att.eelf.configuration.EELFManager;
23 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
24
25 import javax.ws.rs.client.Client;
26 import javax.ws.rs.client.ClientBuilder;
27 import javax.ws.rs.client.Entity;
28 import javax.ws.rs.client.WebTarget;
29 import javax.ws.rs.core.Response.Status;
30 import java.net.URI;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.Map;
34 import java.util.Optional;
35 import javax.net.ssl.HostnameVerifier;
36 import javax.net.ssl.SSLContext;
37 import javax.ws.rs.HttpMethod;
38 import javax.ws.rs.core.MediaType;
39 import org.apache.commons.lang3.StringUtils;
40 import org.onap.appc.flow.controller.data.Response;
41 import org.onap.appc.flow.controller.data.Transaction;
42 import org.onap.appc.flow.controller.interfaces.FlowExecutorInterface;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
44
45
46 public class RestExecutor implements FlowExecutorInterface {
47
48     private static final EELFLogger log = EELFManager.getInstance().getLogger(RestExecutor.class);
49
50     @Override
51     public Map<String, String> execute(Transaction transaction, SvcLogicContext ctx) throws Exception {
52         String woPswd = transaction.toString().replaceAll("pswd=(.*?), ", "pswd=XXXX, ");
53         log.info("Configuring Rest Operation....." + woPswd);
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             client = createClient(sslContext);
62             if ((transaction.getuId() != null) && (transaction.getPswd() != null)) {
63                 client.register(HttpAuthenticationFeature.basic(transaction.getuId(), transaction.getPswd()));
64             }
65             WebTarget webResource = client.target(new URI(transaction.getExecutionEndPoint()));
66             webResource.property("Content-Type", "application/json;charset=UTF-8");
67
68             javax.ws.rs.core.Response clientResponse = getClientResponse(transaction, webResource).orElseThrow(() -> new Exception(
69                     "Cannot determine the state of : " + transaction.getActionLevel() + " HTTP response is null"));
70
71             processClientResponse(clientResponse, transaction, outputMessage);
72
73             log.info("Completed Rest Operation.....");
74
75         } catch (Exception e) {
76             log.debug("failed in RESTCONT Action (" + transaction.getExecutionRPC() + ") for the resource "
77                     + transaction.getExecutionEndPoint() + ", fault message :" + e.getMessage());
78             throw new Exception("Error While Sending Rest Request", e);
79
80         } finally {
81             if (client != null) {
82                 client.close();
83             }
84         }
85         return outputMessage;
86     }
87
88     private HostnameVerifier getHostnameVerifier() {
89         return (hostname, sslSession) -> true;
90     }
91
92     Client createClient(SSLContext ctx) {
93         return ClientBuilder.newBuilder().sslContext(ctx).hostnameVerifier(getHostnameVerifier()).build();
94     }
95
96     private Optional<javax.ws.rs.core.Response> getClientResponse(Transaction transaction, WebTarget webResource) {
97         String responseDataType = MediaType.APPLICATION_JSON;
98         String requestDataType = MediaType.APPLICATION_JSON;
99         javax.ws.rs.core.Response clientResponse = null;
100
101         log.info("Starting Rest Operation.....");
102         if (HttpMethod.GET.equalsIgnoreCase(transaction.getExecutionRPC())) {
103             clientResponse = webResource.request(responseDataType).get(javax.ws.rs.core.Response.class);
104         } else if (HttpMethod.POST.equalsIgnoreCase(transaction.getExecutionRPC())) {
105             clientResponse = webResource.request(requestDataType).post(Entity.json(transaction.getPayload()),
106          javax.ws.rs.core.Response.class);
107         } else if (HttpMethod.PUT.equalsIgnoreCase(transaction.getExecutionRPC())) {
108             clientResponse = webResource.request(requestDataType).put(Entity.json(transaction.getPayload()),
109                 javax.ws.rs.core.Response.class);
110         } else if (HttpMethod.DELETE.equalsIgnoreCase(transaction.getExecutionRPC())) {
111             clientResponse = webResource.request(requestDataType).delete(javax.ws.rs.core.Response.class);
112         }
113         return Optional.ofNullable(clientResponse);
114     }
115
116     private void processClientResponse(javax.ws.rs.core.Response clientResponse, Transaction transaction,
117             Map<String, String> outputMessage) throws Exception {
118
119         if (clientResponse.getStatus() == Status.OK.getStatusCode()) {
120             Response response = new Response();
121             response.setResponseCode(String.valueOf(Status.OK.getStatusCode()));
122             transaction.setResponses(Collections.singletonList(response));
123             outputMessage.put("restResponse", clientResponse.readEntity(String.class));
124         } else {
125             String errorMsg = clientResponse.readEntity(String.class);
126             if (StringUtils.isNotBlank(errorMsg)) {
127                 log.debug("Error Message from Client Response" + errorMsg);
128             }
129             throw new Exception("Cannot determine the state of : " + transaction.getActionLevel()
130                     + " HTTP error code : " + clientResponse.getStatus());
131         }
132     }
133 }