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