2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License ati
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
25 package org.openecomp.rest;
27 import org.apache.camel.Exchange;
28 import org.apache.camel.impl.DefaultProducer;
29 import org.eclipse.jetty.util.security.Password;
30 import org.openecomp.cl.api.Logger;
31 import org.openecomp.cl.eelf.LoggerFactory;
32 import org.openecomp.event.EventBusConsumer;
34 import org.openecomp.restclient.client.Headers;
35 import org.openecomp.restclient.client.OperationResult;
36 import org.openecomp.restclient.client.RestClient;
37 import org.openecomp.restclient.rest.HttpUtil;
39 import java.util.Arrays;
40 import java.util.HashMap;
41 import java.util.List;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.Response;
49 * The EcompRest producer.
51 public class RestClientProducer extends DefaultProducer {
53 private static enum Operation {
54 GET, PUT, POST, DELETE
57 private RestClientEndpoint endpoint;
59 /** REST client used for sending HTTP requests. */
60 private RestClient restClient;
62 private Logger logger = LoggerFactory.getInstance().getLogger(RestClientProducer.class);
65 public RestClientProducer(RestClientEndpoint endpoint) {
67 this.endpoint = endpoint;
71 public void process(Exchange exchange) {
73 // Extract the URL for our REST request from the IN message header.
74 String url = exchange.getIn().getHeader(RestClientEndpoint.IN_HEADER_URL).toString();
76 // Populate the HTTP Request header values from any values passed in via the
77 // IN message headers.
78 Map<String, List<String>> headers = populateRestHeaders(exchange);
80 if (logger.isDebugEnabled()) {
81 StringBuilder sb = new StringBuilder();
82 sb.append("Process REST request - operation=").append(getOperation(exchange));
83 sb.append(" headers=[");
84 for (String key : headers.keySet()) {
85 sb.append("{").append(key).append("->").append(headers.get(key)).append("} ");
88 sb.append(" content: ").append(exchange.getIn().getBody());
89 logger.debug(sb.toString());
92 // Now, invoke the REST client to perform the operation.
93 OperationResult result = null;
94 switch (getOperation(exchange)) {
97 result = getRestClient().get(url, headers, MediaType.APPLICATION_JSON_TYPE);
101 result = getRestClient().put(url, exchange.getIn().getBody().toString(), headers,
102 MediaType.APPLICATION_JSON_TYPE, null);
106 result = getRestClient().post(url, exchange.getIn().getBody().toString(), headers,
107 MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
111 result = getRestClient().delete(url, headers, MediaType.APPLICATION_JSON_TYPE);
115 // The supplied operation is not supported.
116 result = new OperationResult();
117 result.setResultCode(Response.Status.BAD_REQUEST.getStatusCode());
118 result.setFailureCause("Unsupported HTTP Operation: " + getOperation(exchange));
123 // Populate the OUT message with our result.
124 exchange.getOut().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_CODE,
125 result.getResultCode());
126 if (HttpUtil.isHttpResponseClassSuccess(result.getResultCode())) {
127 exchange.getOut().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_MSG,
128 responseStatusStringFromResult(result));
129 exchange.getOut().setBody(result.getResult());
131 exchange.getOut().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_MSG,
132 result.getFailureCause());
139 * Extracts the requested REST operation from the exchange message.
141 * @param exchange - The Camel exchange to pull the operation from.
143 * @return - The REST operation being requested.
145 private Operation getOperation(Exchange exchange) {
147 String toEndpoint = ((String) exchange.getProperty(Exchange.TO_ENDPOINT));
149 String operation = toEndpoint.substring((toEndpoint.lastIndexOf("://") + 3));
151 int position = operation.indexOf('?');
153 operation = operation.substring(0, position);
156 return Operation.valueOf(operation.toUpperCase());
162 * This method extracts values from the IN message which are intended to be used to populate the
163 * HTTP Header entries for our REST request.
165 * @param exchange - The Camel exchange to extract the HTTP header parameters from.
167 * @return - A map of HTTP header names and values.
169 private Map<String, List<String>> populateRestHeaders(Exchange exchange) {
171 Map<String, List<String>> headers = new HashMap<>();
173 if (exchange.getIn().getHeader(Headers.FROM_APP_ID) != null) {
174 headers.put(Headers.FROM_APP_ID,
175 Arrays.asList(exchange.getIn().getHeader(Headers.FROM_APP_ID).toString()));
177 if (exchange.getIn().getHeader(Headers.TRANSACTION_ID) != null) {
178 headers.put(Headers.TRANSACTION_ID,
179 Arrays.asList(exchange.getIn().getHeader(Headers.TRANSACTION_ID).toString()));
181 if (exchange.getIn().getHeader(Headers.RESOURCE_VERSION) != null) {
182 headers.put(Headers.RESOURCE_VERSION,
183 Arrays.asList(exchange.getIn().getHeader(Headers.RESOURCE_VERSION).toString()));
185 if (exchange.getIn().getHeader(Headers.ETAG) != null) {
186 headers.put(Headers.ETAG, Arrays.asList(exchange.getIn().getHeader(Headers.ETAG).toString()));
188 if (exchange.getIn().getHeader(Headers.IF_MATCH) != null) {
189 headers.put(Headers.IF_MATCH,
190 Arrays.asList(exchange.getIn().getHeader(Headers.IF_MATCH).toString()));
192 if (exchange.getIn().getHeader(Headers.IF_NONE_MATCH) != null) {
193 headers.put(Headers.IF_NONE_MATCH,
194 Arrays.asList(exchange.getIn().getHeader(Headers.IF_NONE_MATCH).toString()));
196 if (exchange.getIn().getHeader(Headers.ACCEPT) != null) {
197 headers.put(Headers.ACCEPT,
198 Arrays.asList(exchange.getIn().getHeader(Headers.ACCEPT).toString()));
200 if (exchange.getIn().getHeader("Content-Type") != null) {
201 headers.put("Content-Type",
202 Arrays.asList(exchange.getIn().getHeader("Content-Type").toString()));
210 * This helper method converts an HTTP response code into the associated string.
212 * @param result - A result object to get the response code from.
214 * @return - The string message associated with the supplied response code.
216 private String responseStatusStringFromResult(OperationResult result) {
218 // Not every valid response code is actually represented by the Response.Status
219 // object, so we need to guard against missing codes, otherwise we throw null
220 // pointer exceptions when we try to generate our metrics logs...
221 Response.Status responseStatus = Response.Status.fromStatusCode(result.getResultCode());
222 String responseStatusCodeString = "";
223 if (responseStatus != null) {
224 responseStatusCodeString = responseStatus.toString();
227 return responseStatusCodeString;
231 * Instantiate the REST client that will be used for sending our HTTP requests.
233 * @return - An instance of the REST client.
235 private RestClient getRestClient() {
237 if (restClient == null) {
239 String keystoreFilename = endpoint.getEcompKeystore();
240 String keystorePassword = endpoint.getEcompKeystorePassword();
241 String clientCertFilename = endpoint.getEcompClientCert();
243 if (logger.isDebugEnabled()) {
244 logger.debug("Instantiating REST Client with client_cert=" + clientCertFilename
245 + " keystore=" + keystoreFilename + " keystorePassword=" + keystorePassword);
248 // Create REST client for search service
249 restClient = new RestClient().validateServerHostname(false).validateServerCertChain(true)
250 .clientCertFile(clientCertFilename)
251 .clientCertPassword(Password.deobfuscate(keystorePassword)).trustStore(keystoreFilename);