2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.rest;
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.rest.HttpUtil;
31 import org.onap.aai.cl.api.Logger;
32 import org.onap.aai.cl.eelf.LoggerFactory;
34 import java.util.Arrays;
35 import java.util.HashMap;
36 import java.util.List;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.Response;
44 * The EcompRest producer.
46 public class RestClientProducer extends DefaultProducer {
48 private enum Operation {
49 GET, PUT, POST, DELETE
52 private RestClientEndpoint endpoint;
54 /** REST client used for sending HTTP requests. */
55 private RestClient restClient;
57 private Logger logger = LoggerFactory.getInstance().getLogger(RestClientProducer.class);
60 public RestClientProducer(RestClientEndpoint endpoint) {
62 this.endpoint = endpoint;
66 public void process(Exchange exchange) {
68 // Extract the URL for our REST request from the IN message header.
69 String url = exchange.getIn().getHeader(RestClientEndpoint.IN_HEADER_URL).toString();
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);
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("} ");
83 sb.append(" content: ").append(exchange.getIn().getBody());
84 logger.debug(sb.toString());
87 // Now, invoke the REST client to perform the operation.
88 OperationResult result;
89 switch (getOperation(exchange)) {
92 result = getRestClient().get(url, headers, MediaType.APPLICATION_JSON_TYPE);
96 result = getRestClient().put(url, exchange.getIn().getBody().toString(), headers,
97 MediaType.APPLICATION_JSON_TYPE, null);
101 result = getRestClient().post(url, exchange.getIn().getBody().toString(), headers,
102 MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
106 result = getRestClient().delete(url, headers, MediaType.APPLICATION_JSON_TYPE);
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));
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());
127 exchange.getIn().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_MSG,
128 result.getFailureCause());
135 * Extracts the requested REST operation from the exchange message.
137 * @param exchange - The Camel exchange to pull the operation from.
139 * @return - The REST operation being requested.
141 private Operation getOperation(Exchange exchange) {
143 String toEndpoint = ((String) exchange.getProperty(Exchange.TO_ENDPOINT));
145 String operation = toEndpoint.substring((toEndpoint.lastIndexOf("://") + 3));
147 int position = operation.indexOf('?');
149 operation = operation.substring(0, position);
152 return Operation.valueOf(operation.toUpperCase());
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.
161 * @param exchange - The Camel exchange to extract the HTTP header parameters from.
163 * @return - A map of HTTP header names and values.
165 private Map<String, List<String>> populateRestHeaders(Exchange exchange) {
167 Map<String, List<String>> headers = new HashMap<>();
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()));
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()));
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()));
181 if (exchange.getIn().getHeader(Headers.ETAG) != null) {
182 headers.put(Headers.ETAG, Arrays.asList(exchange.getIn().getHeader(Headers.ETAG).toString()));
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()));
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()));
192 if (exchange.getIn().getHeader(Headers.ACCEPT) != null) {
193 headers.put(Headers.ACCEPT,
194 Arrays.asList(exchange.getIn().getHeader(Headers.ACCEPT).toString()));
196 if (exchange.getIn().getHeader("Content-Type") != null) {
197 headers.put("Content-Type",
198 Arrays.asList(exchange.getIn().getHeader("Content-Type").toString()));
206 * This helper method converts an HTTP response code into the associated string.
208 * @param result - A result object to get the response code from.
210 * @return - The string message associated with the supplied response code.
212 private String responseStatusStringFromResult(OperationResult result) {
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();
223 return responseStatusCodeString;
227 * Instantiate the REST client that will be used for sending our HTTP requests.
229 * @return - An instance of the REST client.
231 private RestClient getRestClient() {
233 if (restClient == null) {
235 String keystoreFilename = endpoint.getEcompKeystore();
236 String keystorePassword = endpoint.getEcompKeystorePassword();
237 String clientCertFilename = endpoint.getEcompClientCert();
239 if (logger.isDebugEnabled()) {
240 logger.debug("Instantiating REST Client with client_cert=" + clientCertFilename
241 + " keystore=" + keystoreFilename + " keystorePassword=" + keystorePassword);
244 // Create REST client for search service
245 restClient = new RestClient().validateServerHostname(false).validateServerCertChain(true)
246 .clientCertFile(clientCertFilename)
247 .clientCertPassword(Password.deobfuscate(keystorePassword)).trustStore(keystoreFilename);