Merge "Logging improvements"
[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.vid.client.HttpBasicClient;
7 import org.onap.vid.exceptions.GenericUncheckedException;
8 import org.onap.vid.policy.rest.RequestDetails;
9 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
10 import org.onap.portalsdk.core.util.SystemProperties;
11
12 import javax.ws.rs.client.Client;
13 import javax.ws.rs.client.Entity;
14 import javax.ws.rs.core.MediaType;
15 import javax.ws.rs.core.MultivaluedHashMap;
16 import javax.ws.rs.core.Response;
17 import java.text.DateFormat;
18 import java.text.SimpleDateFormat;
19 import java.util.Collections;
20 import java.util.Date;
21
22 public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInterfaceIfc {
23
24         /** The logger. */
25         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class);
26         
27         public static final String APPLICATION_JSON = "application/json";
28
29         /** The client. */
30         private static Client client = null;
31
32         /** The common headers. */
33         private MultivaluedHashMap<String, Object> commonHeaders;
34         public PolicyRestInterface() {
35                 super();
36         }
37
38         /** The Constant dateFormat. */
39         static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
40
41         public void initRestClient()
42         {
43                 final String methodname = "initRestClient()";
44                 
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<> ();
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 ) {
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 GenericUncheckedException(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
136                         int status = cres.getStatus();
137                 restObject.setStatusCode (status);
138                 
139                         if (status == 404) { // resource not found
140                                 String msg = "Resource does not exist...: " + cres.getStatus();
141                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
142                         } else if (status == 200  || status == 204){
143                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted");
144                         } else if (status == 202) {
145                                 String msg = "Delete in progress: " + status;
146                                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
147                         }
148                         else {
149                                 String msg = "Deleting Resource failed: " + status;
150                                         logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg);
151                         }
152                         
153                         try {
154                                 t = (T) cres.readEntity(t.getClass());
155                                 restObject.set(t);
156             }
157             catch ( Exception e ) {
158                 logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e="
159                                 + e.getMessage());
160             }
161    
162         } 
163                 catch (Exception e)
164         {
165                  logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
166                  throw e;
167         
168         }
169         }
170         
171         @SuppressWarnings("unchecked")
172         public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject) {
173                 
174         String methodName = "Post";
175         String url="";
176
177         System.out.println( "POST policy rest interface");
178        
179         try {
180             
181             initRestClient();    
182     
183             url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path;
184             System.out.println( "<== " +  methodName + " sending request to url= " + url);
185             // Change the content length
186             final Response cres = client.target(url)
187                  .request()
188                  .accept(APPLICATION_JSON)
189                          .headers(commonHeaders)
190                  //.header("content-length", 201)
191                  //.header("X-FromAppId",  sourceID)
192                  .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
193             
194             try {
195                                 t = (T) cres.readEntity(t.getClass());
196                                 restObject.set(t);
197             }
198             catch ( Exception e ) {
199                 
200                 System.out.println("<== " + methodName + " No response entity, this is probably ok, e=" + e.getMessage());
201             }
202
203             int status = cres.getStatus();
204                 restObject.setStatusCode (status);
205                 
206                 if ( status >= 200 && status <= 299 ) {
207                         System.out.println( "<== " + methodName + " REST api POST was successful!");
208                 
209              } else {
210                  System.out.println( "<== " + methodName + " with status="+status+", url="+url);
211              }    
212    
213         } catch (Exception e)
214         {
215                 System.out.println( "<== " + methodName + " with url="+url+ ", Exception: " + e.toString());
216                  throw e;
217         
218         }
219     }
220         
221         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
222         {
223                 return clazz.newInstance();
224         }
225
226         @Override
227         public void logRequest(RequestDetails r) {
228                 // TODO Auto-generated method stub
229         }       
230 }