org.onap migration
[vid.git] / vid-app-common / src / main / java / org / onap / vid / policy / PolicyRestInterface.java
1 package org.onap.vid.policy;
2
3 import org.apache.commons.codec.binary.Base64;
4 import org.eclipse.jetty.util.security.Password;
5 import org.json.simple.JSONObject;
6 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
7 import org.onap.portalsdk.core.util.SystemProperties;
8 import org.onap.vid.client.HttpBasicClient;
9 import org.onap.vid.policy.rest.RequestDetails;
10
11 import javax.ws.rs.client.Client;
12 import javax.ws.rs.client.Entity;
13 import javax.ws.rs.core.MediaType;
14 import javax.ws.rs.core.MultivaluedHashMap;
15 import javax.ws.rs.core.Response;
16 import java.text.DateFormat;
17 import java.text.SimpleDateFormat;
18 import java.util.Collections;
19 import java.util.Date;
20
21 public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInterfaceIfc {
22
23         /** The logger. */
24         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class);
25         
26         /** The Constant dateFormat. */
27         final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
28         
29         /** The client. */
30         private static Client client = null;
31         
32         /** The common headers. */
33         private MultivaluedHashMap<String, Object> commonHeaders;
34         
35         public PolicyRestInterface() {
36                 super();
37         }
38         
39         public void initRestClient()
40         {
41                 final String methodname = "initRestClient()";
42                 
43                 //final String clientAuth = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENTAUTH_VAL);
44                 //final String authorization = SystemProperties.getProperty(PolicyProperties.POLICY_AUTHORIZATION_VAL);
45                 final String mechId = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_MECHID_VAL);
46                 final String clientPassword = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_PASSWORD_VAL);
47                 final String username = SystemProperties.getProperty(PolicyProperties.POLICY_USERNAME_VAL);
48                 final String password = SystemProperties.getProperty(PolicyProperties.POLICY_PASSWORD_VAL);
49                 final String environment = SystemProperties.getProperty(PolicyProperties.POLICY_ENVIRONMENT_VAL);
50                                 
51                 final String decrypted_client_password = Password.deobfuscate(clientPassword);          
52                 String mechAuthString = mechId + ":" + decrypted_client_password;               
53                 byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes());
54                 String clientAuth = new String(mechAuthEncBytes);
55                 
56                 final String decrypted_password = Password.deobfuscate(password);               
57                 String authString = username + ":" + decrypted_password;                
58                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
59                 String authorization = new String(authEncBytes);
60                 
61                 commonHeaders = new MultivaluedHashMap<String, Object> ();
62                 commonHeaders.put("ClientAuth",  Collections.singletonList((Object) ("Basic " + clientAuth)));
63                 commonHeaders.put("Authorization",  Collections.singletonList((Object) ("Basic " + authorization)));
64                 commonHeaders.put("Environment",  Collections.singletonList((Object) (environment)));
65                 
66                 if (client == null) {
67                         
68                         try {
69                                 client = HttpBasicClient.getClient();
70                         } catch (Exception e) {
71                                 System.out.println(  methodname + " Unable to get the SSL client");
72                         }
73                 }
74         }
75         
76         @SuppressWarnings("unchecked")
77         public <T> void  Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception {
78                 String methodName = "Get";
79                 
80                 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
81                 
82                 String url="";
83                 restObject.set(t);
84                 
85                 url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path;
86         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " +  methodName + " sending request to url= " + url);
87                 
88         initRestClient();
89                 
90                 final Response cres = client.target(url)
91                          .request()
92                  .accept("application/json")
93                  .headers(commonHeaders)
94                  .get();
95                 
96                 int status = cres.getStatus();
97                 restObject.setStatusCode (status);
98                 
99                 if (status == 200) {
100                          t = (T) cres.readEntity(t.getClass());
101                          restObject.set(t);
102                          logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!");
103                     
104                  } else {
105                      throw new Exception(methodName + " with status="+ status + ", url= " + url );
106                  }
107
108                 logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status );
109                 
110                 return;
111         }
112    
113    @SuppressWarnings("unchecked")
114         public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
115          
116                 String methodName = "Delete";
117                 String url="";
118                 Response cres = null;
119                 
120                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " +  methodName + " start");
121                 logRequest (r);
122
123                 try {
124                         initRestClient();
125                         
126                         url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path;
127                         logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + " methodName sending request to: " + url);
128         
129                         cres = client.target(url)
130                                          .request()
131                                  .accept("application/json")
132                                  .headers(commonHeaders)
133                                  //.entity(r)
134                                  .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke();
135                                //  .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
136                                  //.delete(Entity.entity(r, MediaType.APPLICATION_JSON));
137                         
138                         int status = cres.getStatus();
139                 restObject.setStatusCode (status);
140                 
141                         if (status == 404) { // resource not found
142                                 String msg = "Resource does not exist...: " + cres.getStatus();
143                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
144                         } else if (status == 200  || status == 204){
145                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted");
146                         } else if (status == 202) {
147                                 String msg = "Delete in progress: " + status;
148                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
149                         }
150                         else {
151                                 String msg = "Deleting Resource failed: " + status;
152                                         logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
153                         }
154                         
155                         try {
156                                 t = (T) cres.readEntity(t.getClass());
157                                 restObject.set(t);
158             }
159             catch ( Exception e ) {
160                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e="
161                                 + e.getMessage());
162             }
163    
164         } 
165                 catch (Exception e)
166         {
167                  logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
168                  throw e;
169         
170         }
171         }
172         
173         @SuppressWarnings("unchecked")
174         public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject) throws Exception {
175                 
176         String methodName = "Post";
177         String url="";
178
179         System.out.println( "POST policy rest interface");
180        
181      //   logRequest (requestDetails);
182         try {
183             
184             initRestClient();    
185     
186             url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path;
187             System.out.println( "<== " +  methodName + " sending request to url= " + url);
188             // Change the content length
189             final Response cres = client.target(url)
190                  .request()
191                  .accept("application/json")
192                          .headers(commonHeaders)
193                  //.header("content-length", 201)
194                  //.header("X-FromAppId",  sourceID)
195                  .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
196             
197             try {
198                                 t = (T) cres.readEntity(t.getClass());
199                                 restObject.set(t);
200             }
201             catch ( Exception e ) {
202                 
203                 System.out.println("<== " + methodName + " No response entity, this is probably ok, e=" + e.getMessage());
204             }
205
206             int status = cres.getStatus();
207                 restObject.setStatusCode (status);
208                 
209                 if ( status >= 200 && status <= 299 ) {
210                         System.out.println( "<== " + methodName + " REST api POST was successful!");
211                 
212              } else {
213                  System.out.println( "<== " + methodName + " with status="+status+", url="+url);
214              }    
215    
216         } catch (Exception e)
217         {
218                 System.out.println( "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
219                  throw e;
220         
221         }
222     }
223         
224         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
225         {
226                 return clazz.newInstance();
227         }
228
229         @Override
230         public void logRequest(RequestDetails r) {
231                 // TODO Auto-generated method stub
232         }       
233 }