Changed to unmaintained
[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-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2018 Samsung
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.adapter.rest.impl;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import java.util.Iterator;
31 import java.util.Map;
32 import java.util.function.Supplier;
33 import org.apache.http.HttpEntity;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.client.methods.HttpDelete;
36 import org.apache.http.client.methods.HttpGet;
37 import org.apache.http.client.methods.HttpPost;
38 import org.apache.http.client.methods.HttpPut;
39 import org.apache.http.client.methods.HttpRequestBase;
40 import org.apache.http.entity.StringEntity;
41 import org.apache.http.impl.client.CloseableHttpClient;
42 import org.apache.http.impl.client.HttpClients;
43 import org.apache.http.util.EntityUtils;
44 import org.glassfish.grizzly.http.util.HttpStatus;
45 import org.json.JSONObject;
46 import org.onap.appc.Constants;
47 import org.onap.appc.adapter.rest.RequestFactory;
48 import org.onap.appc.adapter.rest.RestAdapter;
49 import org.onap.appc.configuration.Configuration;
50 import org.onap.appc.configuration.ConfigurationFactory;
51 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
52
53 /**
54  * This class implements the {@link RestAdapter} interface. This interface defines the behaviors that our service
55  * provides.
56  */
57 public class RestAdapterImpl implements RestAdapter {
58
59     /**
60      * The constant for the status code for a failed outcome
61      */
62     @SuppressWarnings("nls")
63     private static final String OUTCOME_FAILURE = "failure";
64
65     /**
66      * The constant for the status code for a successful outcome
67      */
68     @SuppressWarnings("nls")
69     private static final String OUTCOME_SUCCESS = "success";
70
71     /**
72      * The logger to be used
73      */
74     private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class);
75
76     /**
77      * A reference to the adapter configuration object.
78      */
79     private Configuration configuration;
80
81     /**
82      * This default constructor is used as a work around because the activator wasnt getting called
83      */
84     public RestAdapterImpl() {
85         initialize();
86     }
87
88     /**
89      * Returns the symbolic name of the adapter
90      *
91      * @return The adapter name
92      * @see org.onap.appc.adapter.rest.RestAdapter#getAdapterName()
93      */
94     @Override
95     public String getAdapterName() {
96         return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
97     }
98
99     @Override
100     public void commonGet(Map<String, String> params, SvcLogicContext ctx) {
101         logger.info("Run get method");
102
103         RequestContext rc = new RequestContext(ctx);
104         rc.isAlive();
105
106         HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc);
107         executeHttpRequest(httpGet, rc);
108     }
109
110     @Override
111     public void commonDelete(Map<String, String> params, SvcLogicContext ctx) {
112         logger.info("Run Delete method");
113
114         RequestContext rc = new RequestContext(ctx);
115         rc.isAlive();
116
117         HttpDelete httpDelete = (HttpDelete) createHttpRequest("DELETE", params, rc);
118         executeHttpRequest(httpDelete, rc);
119     }
120
121     @Override
122     public void commonPost(Map<String, String> params, SvcLogicContext ctx) {
123         logger.info("Run post method");
124
125         RequestContext rc = new RequestContext(ctx);
126         rc.isAlive();
127
128         HttpPost httpPost = (HttpPost) createHttpRequest("POST", params, rc);
129         executeHttpRequest(httpPost, rc);
130     }
131
132     @Override
133     public void commonPut(Map<String, String> params, SvcLogicContext ctx) {
134         logger.info("Run put method");
135
136         RequestContext rc = new RequestContext(ctx);
137         rc.isAlive();
138
139         HttpPut httpPut = (HttpPut) createHttpRequest("PUT", params, rc);
140         executeHttpRequest(httpPut, rc);
141     }
142
143     @SuppressWarnings("static-method")
144     private void doFailure(RequestContext rc, HttpStatus code, String message) {
145         SvcLogicContext svcLogic = rc.getSvcLogicContext();
146         String msg = (message == null) ? code.getReasonPhrase() : message;
147         if (msg.contains("\n")) {
148             msg = msg.substring(msg.indexOf('\n'));
149         }
150
151         String status;
152         try {
153             status = Integer.toString(code.getStatusCode());
154         } catch (Exception e) {
155             logger.error("Exception occurred", e);
156             status = "500";
157         }
158         svcLogic.setStatus(OUTCOME_FAILURE);
159         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
160         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
161         svcLogic.setAttribute(Constants.CONTEXT_ERROR_CODE, status);
162         svcLogic.setAttribute(Constants.CONTEXT_ERROR_MESSAGE, msg);
163     }
164
165
166     /**
167      * @param rc The request context that manages the state and recovery of the request for the life of its processing.
168      */
169     @SuppressWarnings("static-method")
170     private void doSuccess(RequestContext rc, int code, String message) {
171         SvcLogicContext svcLogic = rc.getSvcLogicContext();
172         svcLogic.setStatus(OUTCOME_SUCCESS);
173         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
174         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, message);
175         svcLogic.setAttribute(Constants.CONTEXT_AGENT_ERROR_CODE, Integer.toString(code));
176         svcLogic.setAttribute(Constants.CONTEXT_AGENT_ERROR_MESSAGE, message);
177         svcLogic.setAttribute(Constants.CONTEXT_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
178     }
179
180     private void executeHttpRequest(HttpRequestBase httpRequest, RequestContext rc) {
181         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
182             HttpResponse response = httpClient.execute(httpRequest);
183             int responseCode = response.getStatusLine().getStatusCode();
184             HttpEntity entity = response.getEntity();
185             String responseOutput = EntityUtils.toString(entity);
186             if (responseCode == 200) {
187                 doSuccess(rc, responseCode, responseOutput);
188             } else {
189                 doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase());
190             }
191         } catch (Exception e) {
192             logger.error("An error occurred when executing http request", e);
193             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, e.toString());
194         }
195     }
196
197     public HttpRequestBase createHttpRequest(String method, Map<String, String> params, RequestContext rc) {
198         HttpRequestBase httpRequest = null;
199         try {
200             String tUrl = params.get("org.onap.appc.instance.URI");
201             String haveHeader = params.get("org.onap.appc.instance.haveHeader");
202             String headers = params.get("org.onap.appc.instance.headers");
203
204             Supplier<RequestFactory> requestFactory = RequestFactory::new;
205             httpRequest = requestFactory.get().getHttpRequest(method, tUrl);
206
207             if ("true".equals(haveHeader)) {
208                 JSONObject jsonHeaders = new JSONObject(headers);
209                 Iterator keys = jsonHeaders.keys();
210                 while (keys.hasNext()) {
211                     String string1 = (String) keys.next();
212                     String string2 = jsonHeaders.getString(string1);
213                     httpRequest.addHeader(string1, string2);
214                 }
215             }
216             if (params.containsKey("org.onap.appc.instance.requestBody")) {
217                 String body = params.get("org.onap.appc.instance.requestBody");
218                 StringEntity bodyParams = new StringEntity(body, "UTF-8");
219                 if ("PUT".equals(method)) {
220                     HttpPut httpPut = (HttpPut) httpRequest;
221                     httpPut.setEntity(bodyParams);
222                 }
223                 if ("POST".equals(method)) {
224                     HttpPost httpPost = (HttpPost) httpRequest;
225                     httpPost.setEntity(bodyParams);
226                 }
227             }
228         } catch (Exception e) {
229             logger.error("An error occurred when creating http request", e);
230             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, e.toString());
231         }
232         return httpRequest;
233     }
234
235
236     /**
237      * initialize the provider adapter by building the context cache
238      */
239     private void initialize() {
240         configuration = ConfigurationFactory.getConfiguration();
241
242         logger.info("Rest adapter has been initialized");
243     }
244
245 }