Moving all files to root directory
[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  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.adapter.rest.impl;
23
24 import java.net.URI;
25 import java.util.*;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Properties;
31 import java.util.Set;
32 import java.util.regex.Pattern;
33
34 import org.openecomp.appc.Constants;
35 import org.openecomp.appc.adapter.rest.RestAdapter;
36 import org.openecomp.appc.configuration.Configuration;
37 import org.openecomp.appc.configuration.ConfigurationFactory;
38 import org.openecomp.appc.exceptions.APPCException;
39 import org.openecomp.appc.exceptions.UnknownProviderException;
40 import org.openecomp.appc.i18n.Msg;
41 import org.openecomp.appc.pool.Pool;
42 import org.openecomp.appc.pool.PoolExtensionException;
43 import org.openecomp.appc.util.StructuredPropertyHelper;
44 import org.openecomp.appc.util.StructuredPropertyHelper.Node;
45 import com.att.cdp.exceptions.ContextConnectionException;
46 import com.att.cdp.exceptions.ResourceNotFoundException;
47 import com.att.cdp.exceptions.TimeoutException;
48 import com.att.cdp.exceptions.ZoneException;
49 import com.att.cdp.pal.util.StringHelper;
50 import com.att.cdp.zones.ComputeService;
51 import com.att.cdp.zones.Context;
52 import com.att.cdp.zones.ImageService;
53 import com.att.cdp.zones.Provider;
54 import com.att.cdp.zones.model.Image;
55 import com.att.cdp.zones.model.Server;
56 import com.att.cdp.zones.model.Server.Status;
57 import com.att.cdp.zones.model.ServerBootSource;
58 import com.att.eelf.configuration.EELFLogger;
59 import com.att.eelf.configuration.EELFManager;
60 import com.att.eelf.i18n.EELFResourceManager;
61 import org.openecomp.sdnc.sli.SvcLogicContext;
62
63 import org.glassfish.grizzly.http.util.HttpStatus;
64 import org.slf4j.MDC;
65
66 import java.net.InetAddress;
67 import java.util.Locale;
68 import java.util.UUID;
69 import static com.att.eelf.configuration.Configuration.*;
70
71 import org.apache.http.*;
72 import org.apache.http.client.*;
73 import org.apache.http.client.methods.*;
74 import org.apache.http.impl.client.*;
75 import org.apache.http.util.EntityUtils;
76 import java.io.IOException;
77 import org.apache.http.entity.StringEntity;
78
79 import java.net.InetAddress;
80 import org.json.*;
81
82 /**
83  * This class implements the {@link RestAdapter} interface. This interface
84  * defines the behaviors that our service provides.
85  */
86 public class RestAdapterImpl implements RestAdapter {
87
88         /**
89          * The constant used to define the adapter name in the mapped diagnostic
90          * context
91          */
92         
93
94         @SuppressWarnings("nls")
95         public static final String MDC_ADAPTER = "adapter";
96
97         /**
98          * The constant used to define the service name in the mapped diagnostic
99          * context
100          */
101         @SuppressWarnings("nls")
102         public static final String MDC_SERVICE = "service";
103
104         /**
105          * The constant for the status code for a failed outcome
106          */
107         @SuppressWarnings("nls")
108         public static final String OUTCOME_FAILURE = "failure";
109
110         /**
111          * The constant for the status code for a successful outcome
112          */
113         @SuppressWarnings("nls")
114         public static final String OUTCOME_SUCCESS = "success";
115
116         /**
117          * A constant for the property token "provider" used in the structured
118          * property specifications
119          */
120         @SuppressWarnings("nls")
121         public static final String PROPERTY_PROVIDER = "provider";
122
123         /**
124          * A constant for the property token "identity" used in the structured
125          * property specifications
126          */
127         @SuppressWarnings("nls")
128         public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
129
130         /**
131          * A constant for the property token "name" used in the structured property
132          * specifications
133          */
134         @SuppressWarnings("nls")
135         public static final String PROPERTY_PROVIDER_NAME = "name";
136
137         /**
138          * A constant for the property token "tenant" used in the structured
139          * property specifications
140          */
141         @SuppressWarnings("nls")
142         public static final String PROPERTY_PROVIDER_TENANT = "tenant";
143
144         /**
145          * A constant for the property token "tenant name" used in the structured
146          * property specifications
147          */
148         @SuppressWarnings("nls")
149         public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
150
151         /**
152          * A constant for the property token "password" used in the structured
153          * property specifications
154          */
155         @SuppressWarnings("nls")
156         public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
157
158         /**
159          * A constant for the property token "userid" used in the structured
160          * property specifications
161          */
162         @SuppressWarnings("nls")
163         public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
164
165         /**
166          * A constant for the property token "type" used in the structured property
167          * specifications
168          */
169         @SuppressWarnings("nls")
170         public static final String PROPERTY_PROVIDER_TYPE = "type";
171
172         /**
173          * The name of the service to restart a server
174          */
175         @SuppressWarnings("nls")
176         public static final String PING_SERVICE = "pingServer";
177
178         /**
179          * The logger to be used
180          */
181         private static final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class);
182
183         /**
184          * The constant for a left parenthesis
185          */
186         private static final char LPAREN = '(';
187
188         /**
189          * The constant for a new line control code
190          */
191         private static final char NL = '\n';
192
193         /**
194          * The constant for a single quote
195          */
196         private static final char QUOTE = '\'';
197
198         /**
199          * The constant for a right parenthesis
200          */
201         private static final char RPAREN = ')';
202
203         /**
204          * The constant for a space
205          */
206         private static final char SPACE = ' ';
207
208         /**
209          * A reference to the adapter configuration object.
210          */
211         private Configuration configuration;
212
213         /**
214          * A cache of providers that are predefined.
215          */
216         // private Map<String /* provider name */, ProviderCache> providerCache;
217
218         /**
219          * This default constructor is used as a work around because the activator
220          * wasnt getting called
221          */
222         /**
223          * A cache of providers that are predefined.
224          */
225         // private Map<String /* provider name */, ProviderCache> providerCache;
226
227         /**
228          * This default constructor is used as a work around because the activator
229          * wasnt getting called
230          */
231         public RestAdapterImpl() {
232                 initialize();
233
234         }
235
236         /**
237          * This constructor is used primarily in the test cases to bypass
238          * initialization of the adapter for isolated, disconnected testing
239          * 
240          * @param initialize
241          *            True if the adapter is to be initialized, can false if not
242          */
243         public RestAdapterImpl(boolean initialize) {
244                 configuration = ConfigurationFactory.getConfiguration();
245                 if (initialize) {
246                         initialize();
247
248                 }
249         }
250
251         /**
252          * @param props
253          *            not used
254          */
255         public RestAdapterImpl(Properties props) {
256                 initialize();
257
258         }
259
260         /**
261          * Returns the symbolic name of the adapter
262          * 
263          * @return The adapter name
264          * @see org.openecomp.appc.adapter.rest.RestAdapter#getAdapterName()
265          */
266         @Override
267         public String getAdapterName() {
268                 return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
269         }
270
271         public HttpRequestBase addHeaders(HttpRequestBase method,String headers){
272                 if(headers.length()==0)
273                         {
274                                 return method;
275                         }else{
276                                 JSONObject JsonHeaders= new JSONObject(headers);
277                                 Iterator keys = JsonHeaders.keys();
278                                 while(keys.hasNext()) {
279                                 String String1 = (String)keys.next();
280                                 String String2 = JsonHeaders.getString(String1);
281                                 method.addHeader(String1,String2);
282                             }
283                                 return method;
284                         }
285         }
286         
287         
288         public void commonGet(Map<String, String> params, SvcLogicContext ctx) {
289                 logger.info("Run get method");
290                 String haveHeader="false";
291                 String tUrl=params.get("org.openecomp.appc.instance.URI");
292                 haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
293                 String headers=params.get("org.openecomp.appc.instance.headers");
294                 RequestContext rc = new RequestContext(ctx);
295                 rc.isAlive();
296         
297                 try {
298                         HttpGet httpGet = new HttpGet(tUrl);
299                         
300                         if(haveHeader.equals("true"))
301                         {
302                                 JSONObject JsonHeaders= new JSONObject(headers);
303                                 Iterator keys = JsonHeaders.keys();
304                                 while(keys.hasNext()) {
305                                 String String1 = (String)keys.next();
306                                 String String2 = JsonHeaders.getString(String1);
307                                 httpGet.addHeader(String1,String2);
308                             }
309
310                         }
311                         
312                         HttpClient httpClient = HttpClients.createDefault();
313                         HttpResponse response = null;
314                         response = httpClient.execute(httpGet);
315                         int responseCode=response.getStatusLine().getStatusCode();
316                         HttpEntity entity = response.getEntity();
317                         String responseOutput=EntityUtils.toString(entity);
318                         doSuccess(rc,responseCode,responseOutput);
319                 } catch (Exception ex) {
320                         doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
321                 }
322         }
323
324         
325         public void commonDelete(Map<String, String> params, SvcLogicContext ctx) {
326                 logger.info("Run Delete method");
327                 String haveHeader="false";
328                 String tUrl=params.get("org.openecomp.appc.instance.URI");
329                 haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
330                 String headers=params.get("org.openecomp.appc.instance.headers");
331                 RequestContext rc = new RequestContext(ctx);
332                 rc.isAlive();
333
334                 try {
335                         HttpDelete httpDelete = new HttpDelete(tUrl);
336                         if(haveHeader.equals("true"))
337                         {
338                                 JSONObject JsonHeaders= new JSONObject(headers);
339                                 Iterator keys = JsonHeaders.keys();
340                                 while(keys.hasNext()) {
341                                 String String1 = (String)keys.next();
342                                 String String2 = JsonHeaders.getString(String1);
343                                 httpDelete.addHeader(String1,String2);
344                             }
345
346                         }
347                         HttpClient httpClient = HttpClients.createDefault();
348                         HttpResponse response = null;
349                         response = httpClient.execute(httpDelete);
350                         int responseCode=response.getStatusLine().getStatusCode();
351                         HttpEntity entity = response.getEntity();
352                         String responseOutput=EntityUtils.toString(entity);
353                         doSuccess(rc,responseCode,responseOutput);
354                 } catch (Exception ex) {
355                         doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
356                 }
357         }
358         
359         
360         
361         public void commonPost(Map<String, String> params, SvcLogicContext ctx) {
362                 logger.info("Run post method");
363                 String haveHeader="false";
364                 String tUrl=params.get("org.openecomp.appc.instance.URI");
365                 String body=params.get("org.openecomp.appc.instance.requestBody");
366                 haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
367                 String headers=params.get("org.openecomp.appc.instance.headers");
368                 RequestContext rc = new RequestContext(ctx);
369                 rc.isAlive();
370                 
371                 try {
372                         HttpPost httpPost = new HttpPost(tUrl);
373                         if(haveHeader.equals("true"))
374                         {
375                                 JSONObject JsonHeaders= new JSONObject(headers);
376                                 Iterator keys = JsonHeaders.keys();
377                                 while(keys.hasNext()) {
378                                 String String1 = (String)keys.next();
379                                 String String2 = JsonHeaders.getString(String1);
380                                 httpPost.addHeader(String1,String2);
381                             }
382
383                         }
384                         StringEntity bodyParams =new StringEntity (body,"UTF-8");
385                         httpPost.setEntity(bodyParams);
386                         HttpClient httpClient = HttpClients.createDefault();
387                         HttpResponse response = null;
388                         response = httpClient.execute(httpPost);
389                         int responseCode=response.getStatusLine().getStatusCode();
390                         HttpEntity entity = response.getEntity();
391                         String responseOutput=EntityUtils.toString(entity);
392                         doSuccess(rc,responseCode,responseOutput);
393                 } catch (Exception ex) {
394                         doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
395                 }
396         }
397         
398         public void commonPut(Map<String, String> params, SvcLogicContext ctx) {
399                 logger.info("Run put method");
400                 String haveHeader="false";
401                 String tUrl=params.get("org.openecomp.appc.instance.URI");
402                 String body=params.get("org.openecomp.appc.instance.requestBody");
403                 haveHeader=params.get("org.openecomp.appc.instance.haveHeader");
404                 String headers=params.get("org.openecomp.appc.instance.headers");
405                 RequestContext rc = new RequestContext(ctx);
406                 rc.isAlive();
407                 
408         try {
409                         HttpPut httpPut = new HttpPut(tUrl);
410                         if(haveHeader.equals("true"))
411                         {
412                                 JSONObject JsonHeaders= new JSONObject(headers);
413                                 Iterator keys = JsonHeaders.keys();
414                                 while(keys.hasNext()) {
415                                 String String1 = (String)keys.next();
416                                 String String2 = JsonHeaders.getString(String1);
417                                 httpPut.addHeader(String1,String2);
418                             }
419
420                         }
421                         StringEntity bodyParams =new StringEntity (body,"UTF-8");
422                         httpPut.setEntity(bodyParams);
423                         HttpClient httpClient = HttpClients.createDefault();
424                         HttpResponse response = null;
425                         response = httpClient.execute(httpPut);
426                         int responseCode=response.getStatusLine().getStatusCode();
427                         HttpEntity entity = response.getEntity();
428                         String responseOutput=EntityUtils.toString(entity);
429                         if(responseCode == 200){
430                         doSuccess(rc,responseCode,responseOutput);
431                         } else {
432                                 doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase());
433                         }
434                         } 
435                         catch (Exception ex) {
436                                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
437                         }
438 /*              } catch (Exception ex) {
439                         doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.getMessage());
440                 }*/
441         }
442         
443         @SuppressWarnings("static-method")
444         private void doFailure(RequestContext rc, HttpStatus code, String message) {
445                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
446                 String msg = (message == null) ? code.getReasonPhrase() : message;
447                 if (msg.contains("\n")) {
448                         msg = msg.substring(msg.indexOf("\n"));
449                 }
450
451                 String status;
452                 try {
453                         status = Integer.toString(code.getStatusCode());
454                 } catch (Exception e) {
455                         status = "500";
456                 }
457                 svcLogic.setStatus(OUTCOME_FAILURE);
458                 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status);
459         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
460                 svcLogic.setAttribute("org.openecomp.rest.result.code", status);
461                 svcLogic.setAttribute("org.openecomp.rest.result.message", msg);
462         }
463         
464
465         /**
466          * @param rc
467          *            The request context that manages the state and recovery of the
468          *            request for the life of its processing.
469          */
470         @SuppressWarnings("static-method")
471         private void doSuccess(RequestContext rc, int code, String message) {
472                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
473                 svcLogic.setStatus(OUTCOME_SUCCESS);
474                 svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode()));
475         svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, message);
476                 svcLogic.setAttribute("org.openecomp.rest.agent.result.code",Integer.toString(code));
477                 svcLogic.setAttribute("org.openecomp.rest.agent.result.message",message);
478                 svcLogic.setAttribute("org.openecomp.rest.result.code",Integer.toString(HttpStatus.OK_200.getStatusCode()));
479         }
480         
481
482         /**
483          * initialize the provider adapter by building the context cache
484          */
485         private void initialize() {
486                 configuration = ConfigurationFactory.getConfiguration();
487         
488                 logger.info("init rest adapter!!!!!");
489         }
490
491 }