2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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 * ============LICENSE_END=========================================================
24 package org.onap.appc.adapter.rest.impl;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import java.util.Iterator;
30 import java.util.function.Supplier;
31 import org.apache.http.HttpEntity;
32 import org.apache.http.HttpResponse;
33 import org.apache.http.client.methods.HttpDelete;
34 import org.apache.http.client.methods.HttpGet;
35 import org.apache.http.client.methods.HttpPost;
36 import org.apache.http.client.methods.HttpPut;
37 import org.apache.http.client.methods.HttpRequestBase;
38 import org.apache.http.entity.StringEntity;
39 import org.apache.http.impl.client.CloseableHttpClient;
40 import org.apache.http.impl.client.HttpClients;
41 import org.apache.http.util.EntityUtils;
42 import org.glassfish.grizzly.http.util.HttpStatus;
43 import org.json.JSONObject;
44 import org.onap.appc.Constants;
45 import org.onap.appc.adapter.rest.RequestFactory;
46 import org.onap.appc.adapter.rest.RestAdapter;
47 import org.onap.appc.configuration.Configuration;
48 import org.onap.appc.configuration.ConfigurationFactory;
49 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
52 * This class implements the {@link RestAdapter} interface. This interface defines the behaviors that our service
55 public class RestAdapterImpl implements RestAdapter {
58 * The constant for the status code for a failed outcome
60 @SuppressWarnings("nls")
61 private static final String OUTCOME_FAILURE = "failure";
64 * The constant for the status code for a successful outcome
66 @SuppressWarnings("nls")
67 private static final String OUTCOME_SUCCESS = "success";
70 * The logger to be used
72 private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class);
75 * A reference to the adapter configuration object.
77 private Configuration configuration;
80 * This default constructor is used as a work around because the activator wasnt getting called
82 public RestAdapterImpl() {
87 * Returns the symbolic name of the adapter
89 * @return The adapter name
90 * @see org.onap.appc.adapter.rest.RestAdapter#getAdapterName()
93 public String getAdapterName() {
94 return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
98 public void commonGet(Map<String, String> params, SvcLogicContext ctx) {
99 logger.info("Run get method");
101 RequestContext rc = new RequestContext(ctx);
104 HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc);
105 executeHttpRequest(httpGet, rc);
109 public void commonDelete(Map<String, String> params, SvcLogicContext ctx) {
110 logger.info("Run Delete method");
112 RequestContext rc = new RequestContext(ctx);
115 HttpDelete httpDelete = (HttpDelete) createHttpRequest("DELETE", params, rc);
116 executeHttpRequest(httpDelete, rc);
120 public void commonPost(Map<String, String> params, SvcLogicContext ctx) {
121 logger.info("Run post method");
123 RequestContext rc = new RequestContext(ctx);
126 HttpPost httpPost = (HttpPost) createHttpRequest("POST", params, rc);
127 executeHttpRequest(httpPost, rc);
131 public void commonPut(Map<String, String> params, SvcLogicContext ctx) {
132 logger.info("Run put method");
134 RequestContext rc = new RequestContext(ctx);
137 HttpPut httpPut = (HttpPut) createHttpRequest("PUT", params, rc);
138 executeHttpRequest(httpPut, rc);
141 @SuppressWarnings("static-method")
142 private void doFailure(RequestContext rc, HttpStatus code, String message) {
143 SvcLogicContext svcLogic = rc.getSvcLogicContext();
144 String msg = (message == null) ? code.getReasonPhrase() : message;
145 if (msg.contains("\n")) {
146 msg = msg.substring(msg.indexOf('\n'));
151 status = Integer.toString(code.getStatusCode());
152 } catch (Exception e) {
153 logger.error("Exception occurred", e);
156 svcLogic.setStatus(OUTCOME_FAILURE);
157 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
158 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
159 svcLogic.setAttribute("org.openecomp.rest.result.code", status);
160 svcLogic.setAttribute("org.openecomp.rest.result.message", msg);
165 * @param rc The request context that manages the state and recovery of the request for the life of its processing.
167 @SuppressWarnings("static-method")
168 private void doSuccess(RequestContext rc, int code, String message) {
169 SvcLogicContext svcLogic = rc.getSvcLogicContext();
170 svcLogic.setStatus(OUTCOME_SUCCESS);
171 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
172 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, message);
173 svcLogic.setAttribute("org.openecomp.rest.agent.result.code", Integer.toString(code));
174 svcLogic.setAttribute("org.openecomp.rest.agent.result.message", message);
175 svcLogic.setAttribute("org.openecomp.rest.result.code", Integer.toString(HttpStatus.OK_200.getStatusCode()));
178 private void executeHttpRequest(HttpRequestBase httpRequest, RequestContext rc) {
179 try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
180 HttpResponse response = httpClient.execute(httpRequest);
181 int responseCode = response.getStatusLine().getStatusCode();
182 HttpEntity entity = response.getEntity();
183 String responseOutput = EntityUtils.toString(entity);
184 if (responseCode == 200) {
185 doSuccess(rc, responseCode, responseOutput);
187 doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase());
189 } catch (Exception e) {
190 logger.error("An error occurred when executing http request", e);
191 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, e.toString());
195 public HttpRequestBase createHttpRequest(String method, Map<String, String> params, RequestContext rc) {
196 HttpRequestBase httpRequest = null;
198 String tUrl = params.get("org.onap.appc.instance.URI");
199 String haveHeader = params.get("org.onap.appc.instance.haveHeader");
200 String headers = params.get("org.onap.appc.instance.headers");
202 Supplier<RequestFactory> requestFactory = RequestFactory::new;
203 httpRequest = requestFactory.get().getHttpRequest(method, tUrl);
205 if ("true".equals(haveHeader)) {
206 JSONObject jsonHeaders = new JSONObject(headers);
207 Iterator keys = jsonHeaders.keys();
208 while (keys.hasNext()) {
209 String string1 = (String) keys.next();
210 String string2 = jsonHeaders.getString(string1);
211 httpRequest.addHeader(string1, string2);
214 if (params.containsKey("org.onap.appc.instance.requestBody")) {
215 String body = params.get("org.onap.appc.instance.requestBody");
216 StringEntity bodyParams = new StringEntity(body, "UTF-8");
217 if ("PUT".equals(method)) {
218 HttpPut httpPut = (HttpPut) httpRequest;
219 httpPut.setEntity(bodyParams);
221 if ("POST".equals(method)) {
222 HttpPost httpPost = (HttpPost) httpRequest;
223 httpPost.setEntity(bodyParams);
226 } catch (Exception e) {
227 logger.error("An error occurred when creating http request", e);
228 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, e.toString());
235 * initialize the provider adapter by building the context cache
237 private void initialize() {
238 configuration = ConfigurationFactory.getConfiguration();
240 logger.info("Rest adapter has been initialized");