2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 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 at
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.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.adapter.rest.impl;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import java.util.Iterator;
31 import java.util.function.Supplier;
32 import org.apache.http.HttpEntity;
33 import org.apache.http.HttpResponse;
34 import org.apache.http.client.methods.HttpDelete;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.client.methods.HttpRequestBase;
39 import org.apache.http.entity.StringEntity;
40 import org.apache.http.impl.client.CloseableHttpClient;
41 import org.apache.http.impl.client.HttpClients;
42 import org.apache.http.util.EntityUtils;
43 import org.glassfish.grizzly.http.util.HttpStatus;
44 import org.json.JSONObject;
45 import org.onap.appc.Constants;
46 import org.onap.appc.adapter.rest.RequestFactory;
47 import org.onap.appc.adapter.rest.RestAdapter;
48 import org.onap.appc.configuration.Configuration;
49 import org.onap.appc.configuration.ConfigurationFactory;
50 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
53 * This class implements the {@link RestAdapter} interface. This interface defines the behaviors that our service
56 public class RestAdapterImpl implements RestAdapter {
59 * The constant for the status code for a failed outcome
61 @SuppressWarnings("nls")
62 private static final String OUTCOME_FAILURE = "failure";
65 * The constant for the status code for a successful outcome
67 @SuppressWarnings("nls")
68 private static final String OUTCOME_SUCCESS = "success";
71 * The logger to be used
73 private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class);
76 * A reference to the adapter configuration object.
78 private Configuration configuration;
81 * This default constructor is used as a work around because the activator wasnt getting called
83 public RestAdapterImpl() {
88 * Returns the symbolic name of the adapter
90 * @return The adapter name
91 * @see org.onap.appc.adapter.rest.RestAdapter#getAdapterName()
94 public String getAdapterName() {
95 return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
99 public void commonGet(Map<String, String> params, SvcLogicContext ctx) {
100 logger.info("Run get method");
102 RequestContext rc = new RequestContext(ctx);
105 HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc);
106 executeHttpRequest(httpGet, rc);
110 public void commonDelete(Map<String, String> params, SvcLogicContext ctx) {
111 logger.info("Run Delete method");
113 RequestContext rc = new RequestContext(ctx);
116 HttpDelete httpDelete = (HttpDelete) createHttpRequest("DELETE", params, rc);
117 executeHttpRequest(httpDelete, rc);
121 public void commonPost(Map<String, String> params, SvcLogicContext ctx) {
122 logger.info("Run post method");
124 RequestContext rc = new RequestContext(ctx);
127 HttpPost httpPost = (HttpPost) createHttpRequest("POST", params, rc);
128 executeHttpRequest(httpPost, rc);
132 public void commonPut(Map<String, String> params, SvcLogicContext ctx) {
133 logger.info("Run put method");
135 RequestContext rc = new RequestContext(ctx);
138 HttpPut httpPut = (HttpPut) createHttpRequest("PUT", params, rc);
139 executeHttpRequest(httpPut, rc);
142 @SuppressWarnings("static-method")
143 private void doFailure(RequestContext rc, HttpStatus code, String message) {
144 SvcLogicContext svcLogic = rc.getSvcLogicContext();
145 String msg = (message == null) ? code.getReasonPhrase() : message;
146 if (msg.contains("\n")) {
147 msg = msg.substring(msg.indexOf('\n'));
152 status = Integer.toString(code.getStatusCode());
153 } catch (Exception e) {
154 logger.error("Exception occurred", e);
157 svcLogic.setStatus(OUTCOME_FAILURE);
158 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
159 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
160 svcLogic.setAttribute("org.openecomp.rest.result.code", status);
161 svcLogic.setAttribute("org.openecomp.rest.result.message", msg);
166 * @param rc The request context that manages the state and recovery of the request for the life of its processing.
168 @SuppressWarnings("static-method")
169 private void doSuccess(RequestContext rc, int code, String message) {
170 SvcLogicContext svcLogic = rc.getSvcLogicContext();
171 svcLogic.setStatus(OUTCOME_SUCCESS);
172 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
173 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, message);
174 svcLogic.setAttribute("org.openecomp.rest.agent.result.code", Integer.toString(code));
175 svcLogic.setAttribute("org.openecomp.rest.agent.result.message", message);
176 svcLogic.setAttribute("org.openecomp.rest.result.code", Integer.toString(HttpStatus.OK_200.getStatusCode()));
179 private void executeHttpRequest(HttpRequestBase httpRequest, RequestContext rc) {
180 try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
181 HttpResponse response = httpClient.execute(httpRequest);
182 int responseCode = response.getStatusLine().getStatusCode();
183 HttpEntity entity = response.getEntity();
184 String responseOutput = EntityUtils.toString(entity);
185 if (responseCode == 200) {
186 doSuccess(rc, responseCode, responseOutput);
188 doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase());
190 } catch (Exception e) {
191 logger.error("An error occurred when executing http request", e);
192 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, e.toString());
196 public HttpRequestBase createHttpRequest(String method, Map<String, String> params, RequestContext rc) {
197 HttpRequestBase httpRequest = null;
199 String tUrl = params.get("org.onap.appc.instance.URI");
200 String haveHeader = params.get("org.onap.appc.instance.haveHeader");
201 String headers = params.get("org.onap.appc.instance.headers");
203 Supplier<RequestFactory> requestFactory = RequestFactory::new;
204 httpRequest = requestFactory.get().getHttpRequest(method, tUrl);
206 if ("true".equals(haveHeader)) {
207 JSONObject jsonHeaders = new JSONObject(headers);
208 Iterator keys = jsonHeaders.keys();
209 while (keys.hasNext()) {
210 String string1 = (String) keys.next();
211 String string2 = jsonHeaders.getString(string1);
212 httpRequest.addHeader(string1, string2);
215 if (params.containsKey("org.onap.appc.instance.requestBody")) {
216 String body = params.get("org.onap.appc.instance.requestBody");
217 StringEntity bodyParams = new StringEntity(body, "UTF-8");
218 if ("PUT".equals(method)) {
219 HttpPut httpPut = (HttpPut) httpRequest;
220 httpPut.setEntity(bodyParams);
222 if ("POST".equals(method)) {
223 HttpPost httpPost = (HttpPost) httpRequest;
224 httpPost.setEntity(bodyParams);
227 } catch (Exception e) {
228 logger.error("An error occurred when creating http request", e);
229 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, e.toString());
236 * initialize the provider adapter by building the context cache
238 private void initialize() {
239 configuration = ConfigurationFactory.getConfiguration();
241 logger.info("Rest adapter has been initialized");