5062018704b50b6c939750f640994af9ef83deae
[aai/router-core.git] / src / main / java / org / onap / aai / rest / RestClientProducer.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.rest;
22
23 import org.apache.camel.Exchange;
24 import org.apache.camel.impl.DefaultProducer;
25 import org.eclipse.jetty.util.security.Password;
26 import org.onap.aai.event.EventBusConsumer;
27 import org.onap.aai.restclient.client.Headers;
28 import org.onap.aai.restclient.client.OperationResult;
29 import org.onap.aai.restclient.client.RestClient;
30 import org.onap.aai.restclient.enums.RestAuthenticationMode;
31 import org.onap.aai.restclient.rest.HttpUtil;
32 import org.onap.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34
35 import java.util.Arrays;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39
40 import javax.ws.rs.core.MediaType;
41 import javax.ws.rs.core.Response;
42
43
44 /**
45  * The EcompRest producer.
46  */
47 public class RestClientProducer extends DefaultProducer {
48
49   private enum Operation {
50     GET, PUT, POST, DELETE
51   }
52
53   private RestClientEndpoint endpoint;
54
55   /** REST client used for sending HTTP requests. */
56   private RestClient restClient;
57
58   private Logger logger = LoggerFactory.getInstance().getLogger(RestClientProducer.class);
59
60
61   public RestClientProducer(RestClientEndpoint endpoint) {
62     super(endpoint);
63     this.endpoint = endpoint;
64   }
65
66   @Override
67   public void process(Exchange exchange) {
68
69     // Extract the URL for our REST request from the IN message header.
70     String url = exchange.getIn().getHeader(RestClientEndpoint.IN_HEADER_URL).toString();
71
72     // Populate the HTTP Request header values from any values passed in via the
73     // IN message headers.
74     Map<String, List<String>> headers = populateRestHeaders(exchange);
75
76     if (logger.isDebugEnabled()) {
77       StringBuilder sb = new StringBuilder();
78       sb.append("Process REST request - operation=").append(getOperation(exchange));
79       sb.append(" headers=[");
80       for (String key : headers.keySet()) {
81         sb.append("{").append(key).append("->").append(headers.get(key)).append("} ");
82       }
83       sb.append("]");
84       sb.append(" content: ").append(exchange.getIn().getBody());
85       logger.debug(sb.toString());
86     }
87
88     // Now, invoke the REST client to perform the operation.
89     OperationResult result;
90     switch (getOperation(exchange)) {
91
92       case GET:
93         result = getRestClient().get(url, headers, MediaType.APPLICATION_JSON_TYPE);
94         break;
95
96       case PUT:
97         result = getRestClient().put(url, exchange.getIn().getBody().toString(), headers,
98             MediaType.APPLICATION_JSON_TYPE, null);
99         break;
100
101       case POST:
102         result = getRestClient().post(url, exchange.getIn().getBody().toString(), headers,
103             MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
104         break;
105
106       case DELETE:
107         result = getRestClient().delete(url, headers, MediaType.APPLICATION_JSON_TYPE);
108         break;
109
110       default:
111         // The supplied operation is not supported.
112         result = new OperationResult();
113         result.setResultCode(Response.Status.BAD_REQUEST.getStatusCode());
114         result.setFailureCause("Unsupported HTTP Operation: " + getOperation(exchange));
115
116         break;
117     }
118
119     /** Just use IN headers as camel does not pass incoming headers from IN to OUT so they might be lost .
120     Reference : http://camel.apache.org/using-getin-or-getout-methods-on-exchange.html **/
121     exchange.getIn().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_CODE,
122         result.getResultCode());
123     if (HttpUtil.isHttpResponseClassSuccess(result.getResultCode())) {
124       exchange.getIn().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_MSG,
125           responseStatusStringFromResult(result));
126       exchange.getIn().setBody(result.getResult());
127     } else {
128       exchange.getIn().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_MSG,
129           result.getFailureCause());
130     }
131
132   }
133
134
135   /**
136    * Extracts the requested REST operation from the exchange message.
137    * 
138    * @param exchange - The Camel exchange to pull the operation from.
139    * 
140    * @return - The REST operation being requested.
141    */
142   private Operation getOperation(Exchange exchange) {
143
144     String toEndpoint = ((String) exchange.getProperty(Exchange.TO_ENDPOINT));
145
146     String operation = toEndpoint.substring((toEndpoint.lastIndexOf("://") + 3));
147
148     int position = operation.indexOf('?');
149     if (position >= 0) {
150       operation = operation.substring(0, position);
151     }
152
153     return Operation.valueOf(operation.toUpperCase());
154   }
155
156
157
158   /**
159    * This method extracts values from the IN message which are intended to be used to populate the
160    * HTTP Header entries for our REST request.
161    * 
162    * @param exchange - The Camel exchange to extract the HTTP header parameters from.
163    * 
164    * @return - A map of HTTP header names and values.
165    */
166   private Map<String, List<String>> populateRestHeaders(Exchange exchange) {
167
168     Map<String, List<String>> headers = new HashMap<>();
169
170     if (exchange.getIn().getHeader(Headers.FROM_APP_ID) != null) {
171       headers.put(Headers.FROM_APP_ID,
172           Arrays.asList(exchange.getIn().getHeader(Headers.FROM_APP_ID).toString()));
173     }
174     if (exchange.getIn().getHeader(Headers.TRANSACTION_ID) != null) {
175       headers.put(Headers.TRANSACTION_ID,
176           Arrays.asList(exchange.getIn().getHeader(Headers.TRANSACTION_ID).toString()));
177     }
178     if (exchange.getIn().getHeader(Headers.RESOURCE_VERSION) != null) {
179       headers.put(Headers.RESOURCE_VERSION,
180           Arrays.asList(exchange.getIn().getHeader(Headers.RESOURCE_VERSION).toString()));
181     }
182     if (exchange.getIn().getHeader(Headers.ETAG) != null) {
183       headers.put(Headers.ETAG, Arrays.asList(exchange.getIn().getHeader(Headers.ETAG).toString()));
184     }
185     if (exchange.getIn().getHeader(Headers.IF_MATCH) != null) {
186       headers.put(Headers.IF_MATCH,
187           Arrays.asList(exchange.getIn().getHeader(Headers.IF_MATCH).toString()));
188     }
189     if (exchange.getIn().getHeader(Headers.IF_NONE_MATCH) != null) {
190       headers.put(Headers.IF_NONE_MATCH,
191           Arrays.asList(exchange.getIn().getHeader(Headers.IF_NONE_MATCH).toString()));
192     }
193     if (exchange.getIn().getHeader(Headers.ACCEPT) != null) {
194       headers.put(Headers.ACCEPT,
195           Arrays.asList(exchange.getIn().getHeader(Headers.ACCEPT).toString()));
196     }
197     if (exchange.getIn().getHeader("Content-Type") != null) {
198       headers.put("Content-Type",
199           Arrays.asList(exchange.getIn().getHeader("Content-Type").toString()));
200     }
201
202     return headers;
203   }
204
205
206   /**
207    * This helper method converts an HTTP response code into the associated string.
208    * 
209    * @param result - A result object to get the response code from.
210    * 
211    * @return - The string message associated with the supplied response code.
212    */
213   private String responseStatusStringFromResult(OperationResult result) {
214
215     // Not every valid response code is actually represented by the Response.Status
216     // object, so we need to guard against missing codes, otherwise we throw null
217     // pointer exceptions when we try to generate our metrics logs...
218     Response.Status responseStatus = Response.Status.fromStatusCode(result.getResultCode());
219     String responseStatusCodeString = "";
220     if (responseStatus != null) {
221       responseStatusCodeString = responseStatus.toString();
222     }
223
224     return responseStatusCodeString;
225   }
226
227   /**
228    * Instantiate the REST client that will be used for sending our HTTP requests.
229    * 
230    * @return - An instance of the REST client.
231    */
232   private RestClient getRestClient() {
233
234     if (restClient == null) {
235       
236       String keystorePassword = endpoint.getEcompKeystorePassword();
237       String clientCertFilename = endpoint.getEcompClientCert();
238
239       if (logger.isDebugEnabled()) {
240         logger.debug("Instantiating REST Client with client_cert=" + clientCertFilename
241             + " keystorePassword=" + keystorePassword);
242       }
243
244       String deobfuscatedCertPassword = keystorePassword.startsWith("OBF:")?Password.deobfuscate(keystorePassword):keystorePassword;
245       
246       // Create REST client for search service
247       restClient = new RestClient().authenticationMode(RestAuthenticationMode.SSL_CERT).validateServerHostname(false)
248               .validateServerCertChain(false).clientCertFile(clientCertFilename)
249               .clientCertPassword(deobfuscatedCertPassword);
250     }
251
252     return restClient;
253   }
254 }