2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.rest;
25 import org.apache.camel.Exchange;
26 import org.apache.camel.impl.DefaultProducer;
27 import org.eclipse.jetty.util.security.Password;
28 import org.openecomp.cl.api.Logger;
29 import org.openecomp.cl.eelf.LoggerFactory;
30 import org.openecomp.event.EventBusConsumer;
32 import org.openecomp.restclient.client.Headers;
33 import org.openecomp.restclient.client.OperationResult;
34 import org.openecomp.restclient.client.RestClient;
35 import org.openecomp.restclient.rest.HttpUtil;
37 import java.util.Arrays;
38 import java.util.HashMap;
39 import java.util.List;
42 import javax.ws.rs.core.MediaType;
43 import javax.ws.rs.core.Response;
47 * The EcompRest producer.
49 public class RestClientProducer extends DefaultProducer {
51 private static enum Operation {
52 GET, PUT, POST, DELETE
55 private RestClientEndpoint endpoint;
57 /** REST client used for sending HTTP requests. */
58 private RestClient restClient;
60 private Logger logger = LoggerFactory.getInstance().getLogger(RestClientProducer.class);
63 public RestClientProducer(RestClientEndpoint endpoint) {
65 this.endpoint = endpoint;
69 public void process(Exchange exchange) {
71 // Extract the URL for our REST request from the IN message header.
72 String url = exchange.getIn().getHeader(RestClientEndpoint.IN_HEADER_URL).toString();
74 // Populate the HTTP Request header values from any values passed in via the
75 // IN message headers.
76 Map<String, List<String>> headers = populateRestHeaders(exchange);
78 if (logger.isDebugEnabled()) {
79 StringBuilder sb = new StringBuilder();
80 sb.append("Process REST request - operation=").append(getOperation(exchange));
81 sb.append(" headers=[");
82 for (String key : headers.keySet()) {
83 sb.append("{").append(key).append("->").append(headers.get(key)).append("} ");
86 sb.append(" content: ").append(exchange.getIn().getBody());
87 logger.debug(sb.toString());
90 // Now, invoke the REST client to perform the operation.
91 OperationResult result = null;
92 switch (getOperation(exchange)) {
95 result = getRestClient().get(url, headers, MediaType.APPLICATION_JSON_TYPE);
99 result = getRestClient().put(url, exchange.getIn().getBody().toString(), headers,
100 MediaType.APPLICATION_JSON_TYPE, null);
104 result = getRestClient().post(url, exchange.getIn().getBody().toString(), headers,
105 MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
109 result = getRestClient().delete(url, headers, MediaType.APPLICATION_JSON_TYPE);
113 // The supplied operation is not supported.
114 result = new OperationResult();
115 result.setResultCode(Response.Status.BAD_REQUEST.getStatusCode());
116 result.setFailureCause("Unsupported HTTP Operation: " + getOperation(exchange));
121 // Populate the OUT message with our result.
122 exchange.getOut().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_CODE,
123 result.getResultCode());
124 if (HttpUtil.isHttpResponseClassSuccess(result.getResultCode())) {
125 exchange.getOut().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_MSG,
126 responseStatusStringFromResult(result));
127 exchange.getOut().setBody(result.getResult());
129 exchange.getOut().setHeader(RestClientEndpoint.OUT_HEADER_RESPONSE_MSG,
130 result.getFailureCause());
137 * Extracts the requested REST operation from the exchange message.
139 * @param exchange - The Camel exchange to pull the operation from.
141 * @return - The REST operation being requested.
143 private Operation getOperation(Exchange exchange) {
145 String toEndpoint = ((String) exchange.getProperty(Exchange.TO_ENDPOINT));
147 String operation = toEndpoint.substring((toEndpoint.lastIndexOf("://") + 3));
149 int position = operation.indexOf('?');
151 operation = operation.substring(0, position);
154 return Operation.valueOf(operation.toUpperCase());
160 * This method extracts values from the IN message which are intended to be used to populate the
161 * HTTP Header entries for our REST request.
163 * @param exchange - The Camel exchange to extract the HTTP header parameters from.
165 * @return - A map of HTTP header names and values.
167 private Map<String, List<String>> populateRestHeaders(Exchange exchange) {
169 Map<String, List<String>> headers = new HashMap<>();
171 if (exchange.getIn().getHeader(Headers.FROM_APP_ID) != null) {
172 headers.put(Headers.FROM_APP_ID,
173 Arrays.asList(exchange.getIn().getHeader(Headers.FROM_APP_ID).toString()));
175 if (exchange.getIn().getHeader(Headers.TRANSACTION_ID) != null) {
176 headers.put(Headers.TRANSACTION_ID,
177 Arrays.asList(exchange.getIn().getHeader(Headers.TRANSACTION_ID).toString()));
179 if (exchange.getIn().getHeader(Headers.RESOURCE_VERSION) != null) {
180 headers.put(Headers.RESOURCE_VERSION,
181 Arrays.asList(exchange.getIn().getHeader(Headers.RESOURCE_VERSION).toString()));
183 if (exchange.getIn().getHeader(Headers.ETAG) != null) {
184 headers.put(Headers.ETAG, Arrays.asList(exchange.getIn().getHeader(Headers.ETAG).toString()));
186 if (exchange.getIn().getHeader(Headers.IF_MATCH) != null) {
187 headers.put(Headers.IF_MATCH,
188 Arrays.asList(exchange.getIn().getHeader(Headers.IF_MATCH).toString()));
190 if (exchange.getIn().getHeader(Headers.IF_NONE_MATCH) != null) {
191 headers.put(Headers.IF_NONE_MATCH,
192 Arrays.asList(exchange.getIn().getHeader(Headers.IF_NONE_MATCH).toString()));
194 if (exchange.getIn().getHeader(Headers.ACCEPT) != null) {
195 headers.put(Headers.ACCEPT,
196 Arrays.asList(exchange.getIn().getHeader(Headers.ACCEPT).toString()));
198 if (exchange.getIn().getHeader("Content-Type") != null) {
199 headers.put("Content-Type",
200 Arrays.asList(exchange.getIn().getHeader("Content-Type").toString()));
208 * This helper method converts an HTTP response code into the associated string.
210 * @param result - A result object to get the response code from.
212 * @return - The string message associated with the supplied response code.
214 private String responseStatusStringFromResult(OperationResult result) {
216 // Not every valid response code is actually represented by the Response.Status
217 // object, so we need to guard against missing codes, otherwise we throw null
218 // pointer exceptions when we try to generate our metrics logs...
219 Response.Status responseStatus = Response.Status.fromStatusCode(result.getResultCode());
220 String responseStatusCodeString = "";
221 if (responseStatus != null) {
222 responseStatusCodeString = responseStatus.toString();
225 return responseStatusCodeString;
229 * Instantiate the REST client that will be used for sending our HTTP requests.
231 * @return - An instance of the REST client.
233 private RestClient getRestClient() {
235 if (restClient == null) {
237 String keystoreFilename = endpoint.getEcompKeystore();
238 String keystorePassword = endpoint.getEcompKeystorePassword();
239 String clientCertFilename = endpoint.getEcompClientCert();
241 if (logger.isDebugEnabled()) {
242 logger.debug("Instantiating REST Client with client_cert=" + clientCertFilename
243 + " keystore=" + keystoreFilename + " keystorePassword=" + keystorePassword);
246 // Create REST client for search service
247 restClient = new RestClient().validateServerHostname(false).validateServerCertChain(true)
248 .clientCertFile(clientCertFilename)
249 .clientCertPassword(Password.deobfuscate(keystorePassword)).trustStore(keystoreFilename);