32ea3563676dc61a51f40fc4c350a747499972d8
[appc.git] / appc-adapters / appc-rest-adapter / appc-rest-adapter-bundle / src / main / java / org / onap / appc / adapter / rest / impl / RestAdapterImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.rest.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import java.util.Iterator;
30 import java.util.Map;
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;
51
52 /**
53  * This class implements the {@link RestAdapter} interface. This interface defines the behaviors that our service
54  * provides.
55  */
56 public class RestAdapterImpl implements RestAdapter {
57
58     /**
59      * The constant for the status code for a failed outcome
60      */
61     @SuppressWarnings("nls")
62     private static final String OUTCOME_FAILURE = "failure";
63
64     /**
65      * The constant for the status code for a successful outcome
66      */
67     @SuppressWarnings("nls")
68     private static final String OUTCOME_SUCCESS = "success";
69
70     /**
71      * The logger to be used
72      */
73     private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class);
74
75     /**
76      * A reference to the adapter configuration object.
77      */
78     private Configuration configuration;
79
80     /**
81      * This default constructor is used as a work around because the activator wasnt getting called
82      */
83     public RestAdapterImpl() {
84         initialize();
85     }
86
87     /**
88      * Returns the symbolic name of the adapter
89      *
90      * @return The adapter name
91      * @see org.onap.appc.adapter.rest.RestAdapter#getAdapterName()
92      */
93     @Override
94     public String getAdapterName() {
95         return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
96     }
97
98     @Override
99     public void commonGet(Map<String, String> params, SvcLogicContext ctx) {
100         logger.info("Run get method");
101
102         RequestContext rc = new RequestContext(ctx);
103         rc.isAlive();
104
105         HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc);
106         executeHttpRequest(httpGet, rc);
107     }
108
109     @Override
110     public void commonDelete(Map<String, String> params, SvcLogicContext ctx) {
111         logger.info("Run Delete method");
112
113         RequestContext rc = new RequestContext(ctx);
114         rc.isAlive();
115
116         HttpDelete httpDelete = (HttpDelete) createHttpRequest("DELETE", params, rc);
117         executeHttpRequest(httpDelete, rc);
118     }
119
120     @Override
121     public void commonPost(Map<String, String> params, SvcLogicContext ctx) {
122         logger.info("Run post method");
123
124         RequestContext rc = new RequestContext(ctx);
125         rc.isAlive();
126
127         HttpPost httpPost = (HttpPost) createHttpRequest("POST", params, rc);
128         executeHttpRequest(httpPost, rc);
129     }
130
131     @Override
132     public void commonPut(Map<String, String> params, SvcLogicContext ctx) {
133         logger.info("Run put method");
134
135         RequestContext rc = new RequestContext(ctx);
136         rc.isAlive();
137
138         HttpPut httpPut = (HttpPut) createHttpRequest("PUT", params, rc);
139         executeHttpRequest(httpPut, rc);
140     }
141
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'));
148         }
149
150         String status;
151         try {
152             status = Integer.toString(code.getStatusCode());
153         } catch (Exception e) {
154             logger.error("Exception occurred", e);
155             status = "500";
156         }
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);
162     }
163
164
165     /**
166      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
167      */
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()));
177     }
178
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);
187             } else {
188                 doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase());
189             }
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());
193         }
194     }
195
196     public HttpRequestBase createHttpRequest(String method, Map<String, String> params, RequestContext rc) {
197         HttpRequestBase httpRequest = null;
198         try {
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");
202
203             Supplier<RequestFactory> requestFactory = RequestFactory::new;
204             httpRequest = requestFactory.get().getHttpRequest(method, tUrl);
205
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);
213                 }
214             }
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);
221                 }
222                 if ("POST".equals(method)) {
223                     HttpPost httpPost = (HttpPost) httpRequest;
224                     httpPost.setEntity(bodyParams);
225                 }
226             }
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());
230         }
231         return httpRequest;
232     }
233
234
235     /**
236      * initialize the provider adapter by building the context cache
237      */
238     private void initialize() {
239         configuration = ConfigurationFactory.getConfiguration();
240
241         logger.info("Rest adapter has been initialized");
242     }
243
244 }