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