Merge from ECOMP's repository
[vid.git] / vid-app-common / src / main / java / org / onap / vid / scheduler / SchedulerRestInterface.java
index 2077e7a..c986f22 100644 (file)
 package org.onap.vid.scheduler;
 
-import java.util.Collections;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.Response;
-
-import org.apache.commons.codec.binary.Base64;
+import com.att.eelf.configuration.EELFLogger;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+import io.joshworks.restclient.http.HttpResponse;
+import org.apache.http.HttpException;
 import org.eclipse.jetty.util.security.Password;
-import org.json.simple.JSONObject;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.onap.vid.client.HttpBasicClient;
-import org.onap.vid.client.HttpsBasicClient;
-import org.onap.vid.scheduler.SchedulerProperties;
-import org.onap.vid.scheduler.RestObjects.RestObject;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
+import org.onap.vid.client.SyncRestClient;
+import org.onap.vid.client.SyncRestClientInterface;
+import org.onap.vid.exceptions.GenericUncheckedException;
+import org.onap.vid.mso.RestObject;
+import org.onap.vid.mso.RestObjectWithRequestInfo;
+import org.onap.vid.utils.Logging;
+import org.springframework.http.HttpMethod;
 import org.springframework.stereotype.Service;
 
-import static org.onap.vid.utils.Logging.getHttpServletRequest;
-import static org.onap.vid.utils.Logging.requestIdHeaderKey;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.Map;
+import java.util.function.Function;
+
+import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
 
 @Service
 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
 
-       private static Client client = null;
-               
-       private MultivaluedHashMap<String, Object> commonHeaders;
-       
-       /** The logger. */
-       static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
-       
-       public SchedulerRestInterface() {
-               super();
-       }
-       
-       public void initRestClient()
-       {       
-               System.out.println( "\t <== Starting to initialize rest client ");
-               
-               final String username;
-               final String password;
-               
-               /*Setting user name based on properties*/
-               String retrievedUsername = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
-               if(retrievedUsername.isEmpty()) {
-                       username = "";
-               } else {
-                       username = retrievedUsername;
-               }
-               
-               /*Setting password based on properties*/
-               String retrievedPassword = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
-               if(retrievedPassword.isEmpty()) {
-                       password = "";
-               } else {
-                       if (retrievedPassword.contains("OBF:")) {
-                               password = Password.deobfuscate(retrievedPassword);
-                       } else {
-                               password = retrievedPassword;
-                       }
-               }
-               
-               String authString = username + ":" + password;
-                               
-               byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
-               String authStringEnc = new String(authEncBytes);
-
-               commonHeaders = new MultivaluedHashMap<String, Object> ();
-               commonHeaders.put("Authorization",  Collections.singletonList((Object) ("Basic " + authStringEnc)));            
-                                       
-               try {
-                       if ( !username.isEmpty() ) { 
-                               
-                               client = HttpsBasicClient.getClient();
-                       }
-                       else {
-                               
-                               client = HttpBasicClient.getClient();
-                       }
-               } catch (Exception e) {
-                       System.out.println( " <== Unable to initialize rest client ");
-               }
-               
-               System.out.println( "\t<== Client Initialized \n");
-       }
-               
-       @SuppressWarnings("unchecked")
-       public <T> void Get (T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject ) throws Exception {
-               
-               String methodName = "Get";
-               String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
-               
-               
-               System.out.println( "<== URL FOR GET : " + url + "\n");
+    private static final  EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("scheduler");
+    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
+    private static final String SUCCESSFUL_API_MESSAGE=" REST api GET was successful!";
+    private SyncRestClientInterface syncRestClient;
+    private Function<String, String> propertyGetter;
+    private Map<String, String> commonHeaders;
 
-        initRestClient();
-               
-               final Response cres = client.target(url)
-                        .request()
-                .accept("application/json")
-                .headers(commonHeaders)
-                        .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
-                        .get();
-                               
-               int status = cres.getStatus();
-               restObject.setStatusCode (status);
-               
-               if (status == 200) {
-                        t = (T) cres.readEntity(t.getClass());
-                        restObject.set(t);
-                       
-                } else {
-                    throw new Exception(methodName + " with status="+ status + ", url= " + url );
-                }
-
-               return;
-       }
-               
-       @SuppressWarnings("unchecked")
-       public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception {
-               
-        String methodName = "Post";
-        String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
-                       
-        System.out.println( "<== URL FOR POST : " + url + "\n");
-     
-        try {
-            
-            initRestClient();    
-    
-            // Change the content length
-            final Response cres = client.target(url)
-                .request()
-                 .accept("application/json")
-                        .headers(commonHeaders)
-                                .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
-                                .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
-            
-            try {
-                               t = (T) cres.readEntity(t.getClass());
-                               restObject.set(t);
-            }
-            catch ( Exception e ) {
-               
-               System.out.println("<== " + methodName + " : No response entity, this is probably ok, e=" + e.getMessage());
-            }
+    public SchedulerRestInterface() {
+        this.propertyGetter = SystemProperties::getProperty;
+    }
 
-            int status = cres.getStatus();
-               restObject.setStatusCode (status);              
-                               
-               if ( status >= 200 && status <= 299 ) {
-                                               
-                       System.out.println( "<== " + methodName + " : REST api POST was successful!" + "\n");
-               
-             } else {
-                System.out.println( "<== " + methodName + " : FAILED with http status : "+status+", url = " + url + "\n");
-             }    
-   
-        } catch (Exception e)
-        {
-               System.out.println( "<== " + methodName + " : with url="+url+ ", Exception: " + e.toString() + "\n");
-               throw e;        
-        }
+    public SchedulerRestInterface(Function<String, String> propertyGetter) {
+        this.propertyGetter = propertyGetter;
     }
 
-       @Override
-       public void logRequest(JSONObject requestDetails) {}
-
-       @SuppressWarnings("unchecked")
-       public <T> void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject<T> restObject) {
-        
-               String url="";
-               Response cres = null;
-               
-               try {
-                       initRestClient();
-                       
-                       url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
-               
-                       cres = client.target(url)
-                                        .request()
-                                .accept("application/json")
-                                .headers(commonHeaders)
-                                        .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey))
-                                //.entity(r)
-                                .delete();
-                              //  .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
-                                //.delete(Entity.entity(r, MediaType.APPLICATION_JSON));
-                       
-                       int status = cres.getStatus();
-               restObject.setStatusCode (status);
-                               
-                       try {
-                               t = (T) cres.readEntity(t.getClass());
-                               restObject.set(t);
-            }
-            catch ( Exception e ) {
+    public void initRestClient() {
+        logger.info("Starting to initialize rest client ");
+        String authStringEnc = calcEncodedAuthString();
+
+        commonHeaders = Maps.newHashMap();
+        commonHeaders.put("Authorization", "Basic " + authStringEnc);
+
+        syncRestClient = new SyncRestClient();
+
+        logger.info("\t<== Client Initialized \n");
+    }
+
+    public <T> RestObjectWithRequestInfo<T> Get(T t, String path, RestObject<T> restObject) {
+
+        String url = null;
+        String rawData = null;
+        Integer status = null;
+
+        try {
+            String methodName = "Get";
+            url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path);
+            initRestClient();
+            Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
+            Map<String, String> requestHeaders = ImmutableMap.<String, String>builder()
+                    .putAll(commonHeaders)
+                    .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId())
+                    .build();
+            final HttpResponse<T> response = ((HttpResponse<T>) syncRestClient.get(url, requestHeaders,
+                    Collections.emptyMap(), t.getClass()));
+            Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response);
+            status = response.getStatus();
+            restObject.setStatusCode(status);
+
+            if (status == 200) {
+                t = response.getBody();
+                restObject.set(t);
+                logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE);
+                logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE);
+            } else {
+                throw new GenericUncheckedException(new HttpException(String.format("%s with status=%d, url=%s", methodName, status, url)));
             }
-   
-        } 
-               catch (Exception e)
-        {      
-                throw e;        
+            return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData);
+        }
+        catch (RuntimeException e) {
+            throw new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e);
         }
-       }
-       
-       public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
-       {
-               return clazz.newInstance();
-       }
+    }
 
+    public <T> void Delete(T t, String sourceID, String path, RestObject<T> restObject) {
+        initRestClient();
+        String url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path);
+        Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
+        Map<String, String> requestHeaders = ImmutableMap.<String, String>builder()
+                .putAll(commonHeaders)
+                .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()).build();
+        final HttpResponse<T> response = (HttpResponse<T>) syncRestClient.delete(url, requestHeaders, t.getClass());
+
+        Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, response);
+
+        int status = response.getStatus();
+        restObject.setStatusCode(status);
+
+        t = response.getBody();
+        restObject.set(t);
+    }
+
+    public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
+        return clazz.newInstance();
+    }
+
+    private String calcEncodedAuthString() {
+        String retrievedUsername = propertyGetter.apply(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
+        final String username = retrievedUsername.isEmpty() ? "" : retrievedUsername;
+
+        String retrievedPassword = propertyGetter.apply(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
+        final String password = retrievedPassword.isEmpty() ? "" : getDeobfuscatedPassword(retrievedPassword);
+
+        return Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
+    }
+
+    private static String getDeobfuscatedPassword(String password) {
+        return password.contains("OBF:") ? Password.deobfuscate(password) : password;
+    }
 }