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