Null check for ClientResponse in PolicyUril.java
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / scheduler / SchedulerRestInterface.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the “License”);
10  * you may not use this software 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  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.openecomp.portalapp.portal.scheduler;
39
40 import java.util.Collections;
41
42 import javax.ws.rs.client.Client;
43 import javax.ws.rs.client.Entity;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.MultivaluedHashMap;
46 import javax.ws.rs.core.Response;
47
48 import org.apache.commons.codec.binary.Base64;
49 import org.json.simple.JSONObject;
50 import org.openecomp.portalapp.portal.scheduler.client.HttpBasicClient;
51 import org.openecomp.portalapp.portal.scheduler.client.HttpsBasicClient;
52 import org.openecomp.portalsdk.core.util.SystemProperties;
53 import org.springframework.stereotype.Service;
54 import org.openecomp.portalapp.portal.scheduler.restobjects.RestObject;
55
56
57 @Service
58 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
59
60         private static Client client = null;
61                 
62         private MultivaluedHashMap<String, Object> commonHeaders;
63         
64         public SchedulerRestInterface() {
65                 super();
66         }
67         
68         public void initRestClient()
69         {
70                 final String methodname = "initRestClient()";
71                 
72                 final String username = "";//SystemProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
73                 //final String password = "";//SystemProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
74                 final String scheduler_url = "";//SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL);
75                 final String decrypted_password = "";//Password.deobfuscate(password);
76                 
77                 String authString = username + ":" + decrypted_password;
78                 
79                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
80                 String authStringEnc = new String(authEncBytes);
81
82                 commonHeaders = new MultivaluedHashMap<String, Object> ();
83                 commonHeaders.put("Authorization",  Collections.singletonList((Object) ("Basic " + authStringEnc)));
84                 
85                 boolean use_ssl = true;
86                 if ( (scheduler_url != null) && ( !(scheduler_url.isEmpty()) ) ) {
87                         if ( scheduler_url.startsWith("https")) {
88                                 use_ssl = true;
89                         }
90                         else {
91                                 use_ssl = false;
92                         }
93                 }
94                 if (client == null) {
95                         
96                         try {
97                                 if ( use_ssl ) { 
98                                         
99                                         client = HttpsBasicClient.getClient();
100                                 }
101                                 else {
102                                         
103                                         client = HttpBasicClient.getClient();
104                                 }
105                         } catch (Exception e) {
106                                 System.out.println(  methodname + " Unable to get the SSL client");
107                         }
108                 }
109         }
110                 
111         @SuppressWarnings("unchecked")
112         public <T> void Get (T t, String sourceId, String path, org.openecomp.portalapp.portal.scheduler.restobjects.RestObject<T> restObject ) throws Exception {
113                 
114                 String methodName = "Get";
115                 String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
116                 
117                 
118                 System.out.println( "<== URL FOR GET : " + url + "\n");
119
120         initRestClient();
121                 
122                 final Response cres = client.target(url)
123                          .request()
124                  .accept("application/json")
125                  .headers(commonHeaders)
126                  .get();
127                                 
128                 int status = cres.getStatus();
129                 restObject.setStatusCode (status);
130                 
131                 if (status == 200) {
132                          t = (T) cres.readEntity(t.getClass());
133                          restObject.set(t);
134                         
135                  } else {
136                      throw new Exception(methodName + " with status="+ status + ", url= " + url );
137                  }
138
139                 return;
140         }
141                 
142         @SuppressWarnings("unchecked")
143         public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception {
144                 
145         String methodName = "Post";
146         String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
147                         
148         System.out.println( "<== URL FOR POST : " + url + "\n");
149      
150         try {
151             
152             initRestClient();    
153     
154             // Change the content length
155             final Response cres = client.target(url)
156                  .request()
157                  .accept("application/json")
158                          .headers(commonHeaders)
159                  //.header("content-length", 201)
160                  //.header("X-FromAppId",  sourceID)
161                  .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
162             
163             try {
164                                 t = (T) cres.readEntity(t.getClass());
165                                 restObject.set(t);
166             }
167             catch ( Exception e ) {
168                 
169                 System.out.println("<== " + methodName + " : No response entity, this is probably ok, e=" + e.getMessage());
170             }
171
172             int status = cres.getStatus();
173                 restObject.setStatusCode (status);              
174                                 
175                 if ( status >= 200 && status <= 299 ) {
176                                                 
177                         System.out.println( "<== " + methodName + " : REST api POST was successful!" + "\n");
178                 
179              } else {
180                  System.out.println( "<== " + methodName + " : FAILED with http status : "+status+", url = " + url + "\n");
181              }    
182    
183         } catch (Exception e)
184         {
185                 System.out.println( "<== " + methodName + " : with url="+url+ ", Exception: " + e.toString() + "\n");
186                 throw e;        
187         }
188     }
189         
190         @SuppressWarnings("unchecked")
191         public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) {
192          
193                 String url="";
194                 Response cres = null;
195                 
196                 try {
197                         initRestClient();
198                         
199                         url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
200                 
201                         cres = client.target(url)
202                                          .request()
203                                  .accept("application/json")
204                                  .headers(commonHeaders)
205                                  //.entity(r)
206                                  .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke();
207                                //  .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
208                                  //.delete(Entity.entity(r, MediaType.APPLICATION_JSON));
209                         
210                         int status = cres.getStatus();
211                 restObject.setStatusCode (status);
212                                 
213                         try {
214                                 t = (T) cres.readEntity(t.getClass());
215                                 restObject.set(t);
216             }
217             catch ( Exception e ) {
218             }
219    
220         } 
221                 catch (Exception e)
222         {       
223                  throw e;        
224         }
225         }
226         
227         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
228         {
229                 return clazz.newInstance();
230         }
231
232         @Override
233         public void logRequest(JSONObject requestDetails) {
234                 // TODO Auto-generated method stub
235                 
236         }       
237 }