Apply defect and Fortify fixes to config bundle code
[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.ClientConfig;
24 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
25 import org.glassfish.jersey.client.ClientProperties;
26
27 import javax.ws.rs.client.Client;
28 import javax.ws.rs.client.ClientBuilder;
29 import javax.ws.rs.client.Entity;
30 import javax.ws.rs.client.WebTarget;
31 import javax.ws.rs.core.Response.Status;
32 import javax.ws.rs.core.Feature;
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         String woPswd = transaction.toString().replaceAll("pswd=(.*?), ", "pswd=XXXX, ");
56         log.info("Configuring Rest Operation....." + woPswd);
57         Map<String, String> outputMessage = new HashMap<>();
58         Client client = null;
59
60         try {
61             System.setProperty("jsse.enableSNIExtension", "false");
62             SSLContext sslContext = SSLContext.getInstance("SSL");
63             sslContext.init(null, new javax.net.ssl.TrustManager[] {new SecureRestClientTrustManager()}, null);
64             client = createClient(sslContext);
65             if ((transaction.getuId() != null) && (transaction.getPswd() != null)) {
66                 client.register(HttpAuthenticationFeature.basic(transaction.getuId(), transaction.getPswd()));
67             }
68             WebTarget webResource = client.target(new URI(transaction.getExecutionEndPoint()));
69             webResource.property("Content-Type", "application/json;charset=UTF-8");
70
71             javax.ws.rs.core.Response 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.close();
86             }
87         }
88         return outputMessage;
89     }
90
91     private HostnameVerifier getHostnameVerifier() {
92         return (hostname, sslSession) -> true;
93     }
94
95     Client createClient(SSLContext ctx) {
96         return ClientBuilder.newBuilder().sslContext(ctx).hostnameVerifier(getHostnameVerifier()).build();
97     }
98
99     private Optional<javax.ws.rs.core.Response> getClientResponse(Transaction transaction, WebTarget webResource) {
100         String responseDataType = MediaType.APPLICATION_JSON;
101         String requestDataType = MediaType.APPLICATION_JSON;
102         javax.ws.rs.core.Response clientResponse = null;
103
104         log.info("Starting Rest Operation.....");
105         if (HttpMethod.GET.equalsIgnoreCase(transaction.getExecutionRPC())) {
106             clientResponse = webResource.request(responseDataType).get(javax.ws.rs.core.Response.class);
107         } else if (HttpMethod.POST.equalsIgnoreCase(transaction.getExecutionRPC())) {
108             clientResponse = webResource.request(requestDataType).post(Entity.json(transaction.getPayload()),
109          javax.ws.rs.core.Response.class);
110         } else if (HttpMethod.PUT.equalsIgnoreCase(transaction.getExecutionRPC())) {
111             clientResponse = webResource.request(requestDataType).put(Entity.json(transaction.getPayload()),
112                 javax.ws.rs.core.Response.class);
113         } else if (HttpMethod.DELETE.equalsIgnoreCase(transaction.getExecutionRPC())) {
114             clientResponse = webResource.request(requestDataType).delete(javax.ws.rs.core.Response.class);
115         }
116         return Optional.ofNullable(clientResponse);
117     }
118
119     private void processClientResponse(javax.ws.rs.core.Response clientResponse, Transaction transaction,
120             Map<String, String> outputMessage) throws Exception {
121
122         if (clientResponse.getStatus() == Status.OK.getStatusCode()) {
123             Response response = new Response();
124             response.setResponseCode(String.valueOf(Status.OK.getStatusCode()));
125             transaction.setResponses(Collections.singletonList(response));
126             outputMessage.put("restResponse", clientResponse.readEntity(String.class));
127         } else {
128             String errorMsg = clientResponse.readEntity(String.class);
129             if (StringUtils.isNotBlank(errorMsg)) {
130                 log.debug("Error Message from Client Response" + errorMsg);
131             }
132             throw new Exception("Cannot determine the state of : " + transaction.getActionLevel()
133                     + " HTTP error code : " + clientResponse.getStatus());
134         }
135     }
136 }