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