org.onap migration
[vid.git] / vid-app-common / src / main / java / org / onap / vid / scheduler / SchedulerRestInterface.java
1 package org.onap.vid.scheduler;
2
3 import java.util.Collections;
4 import javax.ws.rs.client.Client;
5 import javax.ws.rs.client.Entity;
6 import javax.ws.rs.core.MediaType;
7 import javax.ws.rs.core.MultivaluedHashMap;
8 import javax.ws.rs.core.Response;
9
10 import org.apache.commons.codec.binary.Base64;
11 import org.eclipse.jetty.util.security.Password;
12 import org.json.simple.JSONObject;
13 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
14 import org.openecomp.portalsdk.core.util.SystemProperties;
15 import org.onap.vid.client.HttpBasicClient;
16 import org.onap.vid.client.HttpsBasicClient;
17 import org.onap.vid.scheduler.SchedulerProperties;
18 import org.onap.vid.scheduler.RestObjects.RestObject;
19 import org.springframework.stereotype.Service;
20
21 import static org.onap.vid.utils.Logging.getHttpServletRequest;
22 import static org.onap.vid.utils.Logging.requestIdHeaderKey;
23
24 @Service
25 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
26
27         private static Client client = null;
28                 
29         private MultivaluedHashMap<String, Object> commonHeaders;
30         
31         /** The logger. */
32         static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
33         
34         public SchedulerRestInterface() {
35                 super();
36         }
37         
38         public void initRestClient()
39         {       
40                 System.out.println( "\t <== Starting to initialize rest client ");
41                 
42                 final String username;
43                 final String password;
44                 
45                 /*Setting user name based on properties*/
46                 String retrievedUsername = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
47                 if(retrievedUsername.isEmpty()) {
48                         username = "";
49                 } else {
50                         username = retrievedUsername;
51                 }
52                 
53                 /*Setting password based on properties*/
54                 String retrievedPassword = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
55                 if(retrievedPassword.isEmpty()) {
56                         password = "";
57                 } else {
58                         if (retrievedPassword.contains("OBF:")) {
59                                 password = Password.deobfuscate(retrievedPassword);
60                         } else {
61                                 password = retrievedPassword;
62                         }
63                 }
64                 
65                 String authString = username + ":" + password;
66                                 
67                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
68                 String authStringEnc = new String(authEncBytes);
69
70                 commonHeaders = new MultivaluedHashMap<String, Object> ();
71                 commonHeaders.put("Authorization",  Collections.singletonList((Object) ("Basic " + authStringEnc)));            
72                                         
73                 try {
74                         if ( !username.isEmpty() ) { 
75                                 
76                                 client = HttpsBasicClient.getClient();
77                         }
78                         else {
79                                 
80                                 client = HttpBasicClient.getClient();
81                         }
82                 } catch (Exception e) {
83                         System.out.println( " <== Unable to initialize rest client ");
84                 }
85                 
86                 System.out.println( "\t<== Client Initialized \n");
87         }
88                 
89         @SuppressWarnings("unchecked")
90         public <T> void Get (T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject ) throws Exception {
91                 
92                 String methodName = "Get";
93                 String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
94                 
95                 
96                 System.out.println( "<== URL FOR GET : " + url + "\n");
97
98         initRestClient();
99                 
100                 final Response cres = client.target(url)
101                          .request()
102                  .accept("application/json")
103                  .headers(commonHeaders)
104                          .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
105                          .get();
106                                 
107                 int status = cres.getStatus();
108                 restObject.setStatusCode (status);
109                 
110                 if (status == 200) {
111                          t = (T) cres.readEntity(t.getClass());
112                          restObject.set(t);
113                         
114                  } else {
115                      throw new Exception(methodName + " with status="+ status + ", url= " + url );
116                  }
117
118                 return;
119         }
120                 
121         @SuppressWarnings("unchecked")
122         public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception {
123                 
124         String methodName = "Post";
125         String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
126                         
127         System.out.println( "<== URL FOR POST : " + url + "\n");
128      
129         try {
130             
131             initRestClient();    
132     
133             // Change the content length
134             final Response cres = client.target(url)
135                  .request()
136                  .accept("application/json")
137                          .headers(commonHeaders)
138                                  .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
139                                  .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
140             
141             try {
142                                 t = (T) cres.readEntity(t.getClass());
143                                 restObject.set(t);
144             }
145             catch ( Exception e ) {
146                 
147                 System.out.println("<== " + methodName + " : No response entity, this is probably ok, e=" + e.getMessage());
148             }
149
150             int status = cres.getStatus();
151                 restObject.setStatusCode (status);              
152                                 
153                 if ( status >= 200 && status <= 299 ) {
154                                                 
155                         System.out.println( "<== " + methodName + " : REST api POST was successful!" + "\n");
156                 
157              } else {
158                  System.out.println( "<== " + methodName + " : FAILED with http status : "+status+", url = " + url + "\n");
159              }    
160    
161         } catch (Exception e)
162         {
163                 System.out.println( "<== " + methodName + " : with url="+url+ ", Exception: " + e.toString() + "\n");
164                 throw e;        
165         }
166     }
167
168         @Override
169         public void logRequest(JSONObject requestDetails) {}
170
171         @SuppressWarnings("unchecked")
172         public <T> void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject<T> restObject) {
173          
174                 String url="";
175                 Response cres = null;
176                 
177                 try {
178                         initRestClient();
179                         
180                         url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
181                 
182                         cres = client.target(url)
183                                          .request()
184                                  .accept("application/json")
185                                  .headers(commonHeaders)
186                                          .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
187                                  //.entity(r)
188                                  .delete();
189                                //  .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
190                                  //.delete(Entity.entity(r, MediaType.APPLICATION_JSON));
191                         
192                         int status = cres.getStatus();
193                 restObject.setStatusCode (status);
194                                 
195                         try {
196                                 t = (T) cres.readEntity(t.getClass());
197                                 restObject.set(t);
198             }
199             catch ( Exception e ) {
200             }
201    
202         } 
203                 catch (Exception e)
204         {       
205                  throw e;        
206         }
207         }
208         
209         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
210         {
211                 return clazz.newInstance();
212         }
213
214 }