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