Change to CCSDK and ODL Carbon
[appc.git] / appc-adapters / appc-rest-adapter / appc-rest-adapter-bundle / src / main / java / org / openecomp / 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.openecomp.appc.adapter.rest.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.http.HttpEntity;
30 import org.apache.http.HttpResponse;
31 import org.apache.http.client.HttpClient;
32 import org.apache.http.client.methods.HttpDelete;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.client.methods.HttpPost;
35 import org.apache.http.client.methods.HttpPut;
36 import org.apache.http.entity.StringEntity;
37 import org.apache.http.impl.client.HttpClients;
38 import org.apache.http.util.EntityUtils;
39 import org.glassfish.grizzly.http.util.HttpStatus;
40 import org.json.JSONObject;
41 import org.openecomp.appc.Constants;
42 import org.openecomp.appc.adapter.rest.RestAdapter;
43 import org.openecomp.appc.configuration.Configuration;
44 import org.openecomp.appc.configuration.ConfigurationFactory;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
46
47 import java.util.Iterator;
48 import java.util.Map;
49
50 /**
51  * This class implements the {@link RestAdapter} interface. This interface
52  * defines the behaviors that our service provides.
53  */
54 public class RestAdapterImpl implements RestAdapter {
55
56     /**
57      * The constant for the status code for a failed outcome
58      */
59     @SuppressWarnings("nls")
60     private static final String OUTCOME_FAILURE = "failure";
61
62     /**
63      * The constant for the status code for a successful outcome
64      */
65     @SuppressWarnings("nls")
66     private static final String OUTCOME_SUCCESS = "success";
67
68     /**
69      * The logger to be used
70      */
71     private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class);
72
73     /**
74      * A reference to the adapter configuration object.
75      */
76     private Configuration configuration;
77
78     /**
79      * This default constructor is used as a work around because the activator
80      * wasnt getting called
81      */
82     public RestAdapterImpl() {
83         initialize();
84
85     }
86
87     /**
88      * Returns the symbolic name of the adapter
89      *
90      * @return The adapter name
91      * @see org.openecomp.appc.adapter.rest.RestAdapter#getAdapterName()
92      */
93     @Override
94     public String getAdapterName() {
95         return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
96     }
97
98     public void commonGet(Map<String, String> params, SvcLogicContext ctx) {
99         logger.info("Run get method");
100         String haveHeader;
101         String tUrl=params.get("org.openecomp.appc.instance.URI");
102         haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
103         String headers=params.get("org.openecomp.appc.instance.headers");
104         RequestContext rc = new RequestContext(ctx);
105         rc.isAlive();
106
107         try {
108             HttpGet httpGet = new HttpGet(tUrl);
109
110             if(haveHeader.equals("true"))
111             {
112                 JSONObject JsonHeaders= new JSONObject(headers);
113                 Iterator keys = JsonHeaders.keys();
114                 while(keys.hasNext()) {
115                     String String1 = (String)keys.next();
116                     String String2 = JsonHeaders.getString(String1);
117                     httpGet.addHeader(String1,String2);
118                 }
119
120             }
121
122             HttpClient httpClient = HttpClients.createDefault();
123             HttpResponse response;
124             response = httpClient.execute(httpGet);
125             int responseCode=response.getStatusLine().getStatusCode();
126             HttpEntity entity = response.getEntity();
127             String responseOutput=EntityUtils.toString(entity);
128             doSuccess(rc,responseCode,responseOutput);
129         } catch (Exception ex) {
130             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
131         }
132     }
133
134     public void commonDelete(Map<String, String> params, SvcLogicContext ctx) {
135         logger.info("Run Delete method");
136         String haveHeader;
137         String tUrl=params.get("org.openecomp.appc.instance.URI");
138         haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
139         String headers=params.get("org.openecomp.appc.instance.headers");
140         RequestContext rc = new RequestContext(ctx);
141         rc.isAlive();
142
143         try {
144             HttpDelete httpDelete = new HttpDelete(tUrl);
145             if(haveHeader.equals("true"))
146             {
147                 JSONObject JsonHeaders= new JSONObject(headers);
148                 Iterator keys = JsonHeaders.keys();
149                 while(keys.hasNext()) {
150                     String String1 = (String)keys.next();
151                     String String2 = JsonHeaders.getString(String1);
152                     httpDelete.addHeader(String1,String2);
153                 }
154
155             }
156             HttpClient httpClient = HttpClients.createDefault();
157             HttpResponse response = httpClient.execute(httpDelete);
158             int responseCode=response.getStatusLine().getStatusCode();
159             HttpEntity entity = response.getEntity();
160             String responseOutput=EntityUtils.toString(entity);
161             doSuccess(rc,responseCode,responseOutput);
162         } catch (Exception ex) {
163             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
164         }
165     }
166
167     public void commonPost(Map<String, String> params, SvcLogicContext ctx) {
168         logger.info("Run post method");
169         String tUrl=params.get("org.openecomp.appc.instance.URI");
170         String body=params.get("org.openecomp.appc.instance.requestBody");
171         String haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
172         String headers=params.get("org.openecomp.appc.instance.headers");
173         RequestContext rc = new RequestContext(ctx);
174         rc.isAlive();
175
176         try {
177             HttpPost httpPost = new HttpPost(tUrl);
178             if(haveHeader.equals("true"))
179             {
180                 JSONObject JsonHeaders= new JSONObject(headers);
181                 Iterator keys = JsonHeaders.keys();
182                 while(keys.hasNext()) {
183                     String String1 = (String)keys.next();
184                     String String2 = JsonHeaders.getString(String1);
185                     httpPost.addHeader(String1,String2);
186                 }
187
188             }
189             StringEntity bodyParams =new StringEntity (body,"UTF-8");
190             httpPost.setEntity(bodyParams);
191             HttpClient httpClient = HttpClients.createDefault();
192             HttpResponse response = httpClient.execute(httpPost);
193             int responseCode=response.getStatusLine().getStatusCode();
194             HttpEntity entity = response.getEntity();
195             String responseOutput=EntityUtils.toString(entity);
196             doSuccess(rc,responseCode,responseOutput);
197         } catch (Exception ex) {
198             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
199         }
200     }
201
202     public void commonPut(Map<String, String> params, SvcLogicContext ctx) {
203         logger.info("Run put method");
204         String tUrl=params.get("org.openecomp.appc.instance.URI");
205         String body=params.get("org.openecomp.appc.instance.requestBody");
206         String haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
207         String headers=params.get("org.openecomp.appc.instance.headers");
208         RequestContext rc = new RequestContext(ctx);
209         rc.isAlive();
210
211     try {
212             HttpPut httpPut = new HttpPut(tUrl);
213             if(haveHeader.equals("true"))
214             {
215                 JSONObject JsonHeaders= new JSONObject(headers);
216                 Iterator keys = JsonHeaders.keys();
217                 while(keys.hasNext()) {
218                     String String1 = (String)keys.next();
219                     String String2 = JsonHeaders.getString(String1);
220                     httpPut.addHeader(String1,String2);
221                 }
222
223             }
224             StringEntity bodyParams =new StringEntity (body,"UTF-8");
225             httpPut.setEntity(bodyParams);
226             HttpClient httpClient = HttpClients.createDefault();
227             HttpResponse response = httpClient.execute(httpPut);
228             int responseCode=response.getStatusLine().getStatusCode();
229             HttpEntity entity = response.getEntity();
230             String responseOutput=EntityUtils.toString(entity);
231             if(responseCode == 200){
232                 doSuccess(rc,responseCode,responseOutput);
233             } else {
234                 doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase());
235             }
236         }
237         catch (Exception ex) {
238             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
239         }
240     }
241
242     @SuppressWarnings("static-method")
243     private void doFailure(RequestContext rc, HttpStatus code, String message) {
244         SvcLogicContext svcLogic = rc.getSvcLogicContext();
245         String msg = (message == null) ? code.getReasonPhrase() : message;
246         if (msg.contains("\n")) {
247             msg = msg.substring(msg.indexOf("\n"));
248         }
249
250         String status;
251         try {
252             status = Integer.toString(code.getStatusCode());
253         } catch (Exception e) {
254             status = "500";
255         }
256         svcLogic.setStatus(OUTCOME_FAILURE);
257         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
258         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
259         svcLogic.setAttribute("org.openecomp.rest.result.code", status);
260         svcLogic.setAttribute("org.openecomp.rest.result.message", msg);
261     }
262
263
264     /**
265      * @param rc
266      *            The request context that manages the state and recovery of the
267      *            request for the life of its processing.
268      */
269     @SuppressWarnings("static-method")
270     private void doSuccess(RequestContext rc, int code, String message) {
271         SvcLogicContext svcLogic = rc.getSvcLogicContext();
272         svcLogic.setStatus(OUTCOME_SUCCESS);
273         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
274         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, message);
275         svcLogic.setAttribute("org.openecomp.rest.agent.result.code",Integer.toString(code));
276         svcLogic.setAttribute("org.openecomp.rest.agent.result.message",message);
277         svcLogic.setAttribute("org.openecomp.rest.result.code",Integer.toString(HttpStatus.OK_200.getStatusCode()));
278     }
279
280
281     /**
282      * initialize the provider adapter by building the context cache
283      */
284     private void initialize() {
285         configuration = ConfigurationFactory.getConfiguration();
286
287         logger.info("init rest adapter!!!!!");
288     }
289
290 }