fae0bd955eb9afd5cb84e587c3323babd8196d21
[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.client.methods.HttpRequestBase;
37 import org.apache.http.entity.StringEntity;
38 import org.apache.http.impl.client.HttpClients;
39 import org.apache.http.util.EntityUtils;
40 import org.glassfish.grizzly.http.util.HttpStatus;
41 import org.json.JSONObject;
42 import org.openecomp.appc.Constants;
43 import org.openecomp.appc.adapter.rest.RestAdapter;
44 import org.openecomp.appc.adapter.rest.RequestFactory;
45 import org.openecomp.appc.configuration.Configuration;
46 import org.openecomp.appc.configuration.ConfigurationFactory;
47 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
48
49 import java.util.Iterator;
50 import java.util.Map;
51 import java.util.function.Supplier;
52
53 /**
54  * This class implements the {@link RestAdapter} interface. This interface
55  * defines the behaviors that our service 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
83      * wasnt getting called
84      */
85     public RestAdapterImpl() {
86         initialize();
87
88     }
89
90     /**
91      * Returns the symbolic name of the adapter
92      *
93      * @return The adapter name
94      * @see org.openecomp.appc.adapter.rest.RestAdapter#getAdapterName()
95      */
96     @Override
97     public String getAdapterName() {
98         return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
99     }
100
101     public void commonGet(Map<String, String> params, SvcLogicContext ctx) {
102         logger.info("Run get method");
103
104         RequestContext rc = new RequestContext(ctx);
105         rc.isAlive();
106
107         HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc);
108         executeHttpRequest(httpGet, rc);
109     }
110
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     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     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             status = "500";
154         }
155         svcLogic.setStatus(OUTCOME_FAILURE);
156         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
157         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
158         svcLogic.setAttribute("org.openecomp.rest.result.code", status);
159         svcLogic.setAttribute("org.openecomp.rest.result.message", msg);
160     }
161
162
163     /**
164      * @param rc
165      *            The request context that manages the state and recovery of the
166      *            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     public void executeHttpRequest(HttpRequestBase httpRequest, RequestContext rc){
180         try {
181             HttpClient 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         }
192         catch (Exception ex) {
193             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.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.openecomp.appc.instance.URI");
201             String haveHeader = params.get("org.openecomp.appc.instance.haveHeader");
202             String headers = params.get("org.openecomp.appc.instance.headers");
203
204             Supplier<RequestFactory> requestFactory =  RequestFactory::new;
205             httpRequest = requestFactory.get().getHttpRequest(method, tUrl);
206
207             if (haveHeader.equals("true")) {
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.openecomp.appc.instance.requestBody")) {
217                 String body = params.get("org.openecomp.appc.instance.requestBody");
218                 StringEntity bodyParams = new StringEntity (body,"UTF-8");
219                 if (method.equals("PUT")){
220                     HttpPut httpPut = (HttpPut) httpRequest;
221                     httpPut.setEntity(bodyParams);
222                 }
223                 if (method.equals("POST")){
224                     HttpPost httpPost = (HttpPost) httpRequest;
225                     httpPost.setEntity(bodyParams);
226                 }
227             }
228         } catch (Exception ex) {
229             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.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("init rest adapter!!!!!");
242     }
243
244 }