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