Merge "Remove the literal false boolean value"
[music.git] / src / main / java / org / onap / music / main / MusicUtil.java
index c0b968b..cfad845 100755 (executable)
@@ -23,18 +23,29 @@ package org.onap.music.main;
 
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
 import java.math.BigInteger;
+import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Properties;
 import java.util.Scanner;
+import java.util.StringTokenizer;
 import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+
 import org.onap.music.datastore.PreparedQueryObject;
 import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.exceptions.MusicServiceException;
 
 import com.datastax.driver.core.DataType;
+import com.sun.jersey.core.util.Base64;
 
 /**
  * @author nelson24
@@ -51,35 +62,65 @@ public class MusicUtil {
     public static final String EVENTUAL = "eventual";
     public static final String CRITICAL = "critical";
     public static final String ATOMICDELETELOCK = "atomic_delete_lock";
-    
     public static final String DEFAULTKEYSPACENAME = "TBD";
-
+    private static final String XLATESTVERSION = "X-latestVersion";
+    private static final String XMINORVERSION = "X-minorVersion";
+    private static final String XPATCHVERSION = "X-patchVersion";
+    public static final String SELECT = "select";
+    public static final String INSERT = "insert";
+    public static final String UPDATE = "update";
+    public static final String UPSERT = "upsert";
+    public static final String USERID = "userId";
+    public static final String PASSWORD = "password";
+
+       public static final String AUTHORIZATION = "Authorization";
+
+    private static final String LOCALHOST = "localhost";
+    private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
     
     private static int myId = 0;
     private static ArrayList<String> allIds = new ArrayList<>();
     private static String publicIp = "";
     private static ArrayList<String> allPublicIps = new ArrayList<>();
-    private static String myZkHost = "localhost";
-    private static String myCassaHost = "localhost";
-    private static String defaultMusicIp = "localhost";
+    private static String myZkHost = LOCALHOST;
+    private static String myCassaHost = LOCALHOST;
+    private static String defaultMusicIp = LOCALHOST;
+    private static int cassandraPort = 9042;
+    private static int notifytimeout = 30000;
+    private static int notifyinterval = 5000;
+    
     private static boolean debug = true;
     private static String version = "2.3.0";
-    private static String musicRestIp = "localhost";
-    private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties";
+    private static String musicRestIp = LOCALHOST;
+    private static String musicPropertiesFilePath = PROPERTIES_FILE;
     private static long defaultLockLeasePeriod = 6000;
     private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
             "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
-            "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url" };
+            "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url","cassandra.port", "notify.timeout", "notify.interval" };
 
     private static String cassName = "cassandra";
     private static String cassPwd;
     private static String aafEndpointUrl = null;
+    public static final ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>();
 
     private MusicUtil() {
         throw new IllegalStateException("Utility Class");
     }
-    
-    
+    /**
+     * 
+     * @return cassandra port
+     */
+    public static int getCassandraPort() {
+               return cassandraPort;
+       }
+
+    /**
+     * set cassandra port
+     * @param cassandraPort
+     */
+       public static void setCassandraPort(int cassandraPort) {
+               MusicUtil.cassandraPort = cassandraPort;
+       }
     /**
      * @return the cassName
      */
@@ -340,7 +381,8 @@ public class MusicUtil {
         try {
             Scanner fileScanner = new Scanner(new File(""));
             testType = fileScanner.next();// ignore the my id line
-            String batchSize = fileScanner.next();// ignore the my public ip
+            @SuppressWarnings("unused")
+                       String batchSize = fileScanner.next();// ignore the my public ip
                                                     // line
             fileScanner.close();
         } catch (FileNotFoundException e) {
@@ -394,7 +436,8 @@ public class MusicUtil {
         MusicUtil.cassPwd = cassPwd;
     }
 
-    public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
+    @SuppressWarnings("unchecked")
+       public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
 
         String value = "";
         switch (type.getName()) {
@@ -424,32 +467,41 @@ public class MusicUtil {
      * @param colType
      * @param valueObj
      * @return
+     * @throws MusicTypeConversionException 
      * @throws Exception
      */
-    public static Object convertToActualDataType(DataType colType, Object valueObj)  throws Exception{
+    @SuppressWarnings("unchecked")
+       public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
         String valueObjString = valueObj + "";
         switch (colType.getName()) {
-        case UUID:
-            return UUID.fromString(valueObjString);
-        case VARINT:
-            return BigInteger.valueOf(Long.parseLong(valueObjString));
-        case BIGINT:
-            return Long.parseLong(valueObjString);
-        case INT:
-            return Integer.parseInt(valueObjString);
-        case FLOAT:
-            return Float.parseFloat(valueObjString);
-        case DOUBLE:
-            return Double.parseDouble(valueObjString);
-        case BOOLEAN:
-            return Boolean.parseBoolean(valueObjString);
-        case MAP:
-            return (Map<String, Object>) valueObj;
-        default:
-            return valueObjString;
+            case UUID:
+                return UUID.fromString(valueObjString);
+            case VARINT:
+                return BigInteger.valueOf(Long.parseLong(valueObjString));
+            case BIGINT:
+                return Long.parseLong(valueObjString);
+            case INT:
+                return Integer.parseInt(valueObjString);
+            case FLOAT:
+                return Float.parseFloat(valueObjString);
+            case DOUBLE:
+                return Double.parseDouble(valueObjString);
+            case BOOLEAN:
+                return Boolean.parseBoolean(valueObjString);
+            case MAP:
+                return (Map<String, Object>) valueObj;
+            case BLOB:
+               
+            default:
+                return valueObjString;
         }
     }
 
+    public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
+         ByteBuffer buffer = ByteBuffer.wrap(valueObj);
+         return buffer;
+    }
     /**
      *
      * Utility function to parse json map into sql like string
@@ -475,4 +527,107 @@ public class MusicUtil {
         }
         return sqlString.toString();
     }
+
+    @SuppressWarnings("unused")
+    public static String buildVersion(String major, String minor, String patch) {
+        if (minor != null) {
+            major += "." + minor;
+            if (patch != null) {
+                major += "." + patch;
+            }
+        }
+        return major;
+    }
+    
+    /**
+     * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
+     * X-latestVerstion will be equal to the latest full version.
+     * X-minorVersion - will be equal to the latest minor version.
+     * X-pathVersion - will be equal to the latest patch version.
+     * Future plans will change this. 
+     * @param response
+     * @param major
+     * @param minor
+     * @param patch
+     * @return
+     */
+    public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
+        ResponseBuilder response = Response.noContent();
+        String versionIn = buildVersion(major,minor,patch);
+        String version = MusicUtil.getVersion();
+        String[] verArray = version.split("\\.",3);
+        if ( minor != null ) { 
+            response.header(XMINORVERSION,minor);
+        } else {
+            response.header(XMINORVERSION,verArray[1]);
+        } 
+        if ( patch != null ) {
+            response.header(XPATCHVERSION,patch);
+        } else {
+            response.header(XPATCHVERSION,verArray[2]);
+        } 
+        response.header(XLATESTVERSION,version);
+        logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
+        return response;
+    }
+    
+    
+    public static Map<String,String> extractBasicAuthentication(String authorization){
+               
+       Map<String,String> authValues = new HashMap<>();
+       authorization = authorization.replaceFirst("Basic", "");
+       String decoded = Base64.base64Decode(authorization);
+       StringTokenizer token = new StringTokenizer(decoded, ":");
+       authValues.put(MusicUtil.USERID, token.nextToken().toString());
+       authValues.put(MusicUtil.PASSWORD,token.nextToken());
+       return authValues;
+       
+    }
+    
+    public static void loadProperties() throws Exception {
+               Properties prop = new Properties();
+           InputStream input = null;
+           try {
+               // load the properties file
+               input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
+               prop.load(input);
+           } catch (Exception ex) {
+               logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
+               throw new Exception();
+           } finally {
+               if (input != null) {
+                   try {
+                       input.close();
+                   } catch (IOException e) {
+                       logger.error(EELFLoggerDelegate.applicationLogger,"Load properties failed "+e.getMessage(),e);
+                   }
+               }
+           }
+           // get the property value and return it
+               MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
+               String zkHosts = prop.getProperty("zookeeper.host");
+               MusicUtil.setMyZkHost(zkHosts);
+               MusicUtil.setCassName(prop.getProperty("cassandra.user"));
+               MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
+               MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port")));
+               MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout")));
+               MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval")));
+               
+       }
+    
+       public static void setNotifyInterval(int notifyinterval) {
+               MusicUtil.notifyinterval = notifyinterval;
+       }
+       public static void setNotifyTimeOut(int notifytimeout) {
+               MusicUtil.notifytimeout = notifytimeout;
+       }
+
+       public static int getNotifyInterval() {
+               return MusicUtil.notifyinterval;
+       }
+       
+       public static int getNotifyTimeout() {
+               return MusicUtil.notifytimeout;
+               
+       }
 }