Example usage for java.lang String compareTo

List of usage examples for java.lang String compareTo

Introduction

In this page you can find the example usage for java.lang String compareTo.

Prototype

public int compareTo(String anotherString) 

Source Link

Document

Compares two strings lexicographically.

Usage

From source file:com.iitb.cse.ConnectionInfo.java

static void handleConnection(Socket sock, Session session, int tid) {

    System.out.println("\n\n\n---------------->>>>>>>>>[" + tid + "]");

    try {/*from  ww w  .  j a  va2  s  . c  om*/
        int count = 0;
        boolean newConnection = true;
        String ip_add = sock.getInetAddress().toString();
        String[] _ip_add = ip_add.split("/");

        String macAddress = "";
        DeviceInfo myDevice = null;
        InputStream in = sock.getInputStream();
        OutputStream out = sock.getOutputStream();
        DataInputStream dis = new DataInputStream(in);
        DataOutputStream dos = new DataOutputStream(out);

        while (true) {

            System.out.println("\n[" + tid + "] My Socket : " + sock);

            String receivedData = ClientConnection.readFromStream(sock, dis, dos).trim();
            if (receivedData.equals("") || receivedData == null) {
                System.out.println("\n[Empty/Null Data][" + tid + "]");

            } else {

                System.out.println("\nReceived : " + receivedData);

                Map<String, String> jsonMap = null;
                JSONParser parser = new JSONParser();

                ContainerFactory containerFactory = new ContainerFactory() {

                    @SuppressWarnings("rawtypes")
                    @Override
                    public List creatArrayContainer() {
                        return new LinkedList();
                    }

                    @SuppressWarnings("rawtypes")
                    @Override
                    public Map createObjectContainer() {
                        return new LinkedHashMap();
                    }
                };

                try {
                    jsonMap = (Map<String, String>) parser.parse(receivedData, containerFactory);

                    if (jsonMap != null) {

                        String action = jsonMap.get(Constants.action);

                        if (action.compareTo(Constants.heartBeat) == 0
                                || action.compareTo(Constants.heartBeat1) == 0
                                || action.compareTo(Constants.heartBeat2) == 0) {

                            macAddress = jsonMap.get(Constants.macAddress);
                            // heartbeat    
                            System.out.println("\n [" + tid + "] HeartBeat Received : " + (++count));

                            DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress));
                            if (device == null) { // first time from this device. ie new connection

                                System.out.println("<<<== 1 ==>>>");
                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                newDevice.setBssid(jsonMap.get(Constants.bssid));
                                newDevice.setSsid(jsonMap.get(Constants.ssid));
                                // newDevice.setSsid(jsonMap.get(Constants.bssidList));

                                /* String apInfo = jsonMap.get(Constants.bssidList);
                                        
                                if (apInfo != null || !apInfo.equals("")) {
                                  System.out.println("\nInside Bssid List1");
                                String[] bssidInfo = apInfo.split(";");
                                NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length];
                                        
                                for (int i = 0; i < bssidInfo.length; i++) {
                                    String[] info = bssidInfo[i].split(",");
                                    obj[i].setBssid(info[0]);
                                    obj[i].setRssi(info[1]);
                                    obj[i].setRssi(info[2]);
                                }
                                newDevice.setBssidList(obj);
                                }*/
                                Date date = Utils.getCurrentTimeStamp();
                                newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setConnectionStatus(true);
                                newDevice.setThread(Thread.currentThread());
                                newDevice.setSocket(sock);
                                newDevice.setGetlogrequestsend(false);

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                            } else // subsequent heartbeats /  reconnection from same client
                            if (newConnection) { // reconnection from same client

                                System.out.println("<<<== 2 ==>>>");
                                if (device.thread != null) {
                                    device.thread.interrupt();
                                    System.out.println("\n@#1[" + tid + "] Interrupting old thread");
                                }

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));

                                newDevice.setBssid(jsonMap.get(Constants.bssid));
                                newDevice.setSsid(jsonMap.get(Constants.ssid));

                                /* String apInfo = jsonMap.get(Constants.bssidList);
                                if (apInfo != null || !apInfo.equals("")) {
                                    System.out.println("\nInside Bssid List");
                                                    
                                    String[] bssidInfo = apInfo.split(";");
                                    NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length];
                                    for (int i = 0; i < bssidInfo.length; i++) {
                                        String[] info = bssidInfo[i].split(",");
                                        obj[i].setBssid(info[0]);
                                        obj[i].setRssi(info[1]);
                                        obj[i].setRssi(info[2]);
                                    }
                                    newDevice.setBssidList(obj);
                                }*/
                                Date date = Utils.getCurrentTimeStamp();
                                newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);

                                newDevice.setThread(Thread.currentThread());
                                newDevice.setConnectionStatus(true);
                                newDevice.setGetlogrequestsend(false);
                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.remove(device.macAddress);
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                                if (session.filteredClients.contains(device)) {
                                    session.filteredClients.remove(device);
                                    session.filteredClients.add(newDevice);
                                }

                            } else { // heartbeat

                                System.out.println("<<<== 3 ==>>>");

                                Date date = Utils.getCurrentTimeStamp();
                                device.setLastHeartBeatTime(date);
                                device.setSocket(sock);
                                device.setConnectionStatus(true);
                            }

                        } else if (action.compareTo(Constants.experimentOver) == 0) {

                            macAddress = jsonMap.get(Constants.macAddress);

                            System.out.println("\n[" + tid + "] Experiment Over Mesage received");
                            // experiment over
                            // i need mac address from here
                            // ip and port also preferred
                            DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress));

                            if (device == null) { // new connection

                                System.out.println("<<<== 4 ==>>>");

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                //Date date = Utils.getCurrentTimeStamp();
                                //newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);
                                newDevice.setThread(Thread.currentThread());
                                newDevice.setGetlogrequestsend(false);
                                newDevice.setConnectionStatus(true);

                                newDevice.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        newDevice.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                            } else if (newConnection) { // reconnction from the same client

                                System.out.println("<<<== 5 ==>>>");

                                if (device.thread != null) {
                                    device.thread.interrupt();
                                    System.out.println("\n@#2[" + tid + "] Interrupting old thread");
                                }

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                //Date date = Utils.getCurrentTimeStamp();
                                //newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);

                                newDevice.setThread(Thread.currentThread());
                                newDevice.setGetlogrequestsend(false);
                                newDevice.setConnectionStatus(true);

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                newDevice.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        newDevice.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                                session.connectedClients.remove(device.macAddress);
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                                if (session.filteredClients.contains(device)) {
                                    session.filteredClients.remove(device);
                                    session.filteredClients.add(newDevice);
                                }

                            } else {

                                System.out.println("<<<== 6 ==>>>");

                                // alread connected client
                                // device.setExpOver(jsonMap.get(Constants.macAddress))
                                device.setConnectionStatus(true);
                                device.setSocket(sock);
                                device.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        device.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                            }

                        } else if (action.compareTo(Constants.acknowledgement) == 0) {

                            System.out.println("\nAcknowledgement Received -->");
                            int expNumber = Integer.parseInt(jsonMap.get(Constants.experimentNumber));
                            System.out.println("\nExperiment number : " + expNumber);
                            //int sessionId = Utils.getCurrentSessionID();
                            int expId = 1;
                            ///important                                int expId =1;// Utils.getCurrentExperimentID(Integer.toString(1));
                            System.out.println("\nExperiment number : " + expNumber + "== " + expId);

                            //            if (expNumber == expId) {
                            if (macAddress != null && !macAddress.equals("")) {
                                DeviceInfo device = session.connectedClients.get(macAddress);
                                session.actualFilteredDevices.add(device);
                                System.out.println("\n Ack : " + expNumber + " Acknowledgement Received!!!");

                                if (DBManager.updateControlFileSendStatus(expNumber, macAddress, 1,
                                        "Successfully sent Control File")) {
                                    System.out.println("\n Ack : " + expNumber + " DB updated Successfully");
                                } else {
                                    System.out.println("\n Ack : " + expNumber + " DB updation Failed");
                                }
                                ///important                                        Utils.addExperimentDetails(expId, device, false);
                            }
                            //              }
                            // update the db.
                        } else {
                            System.out.println("\n[" + tid + "] Some Other Operation...");
                        }
                        newConnection = false;
                    }
                } catch (Exception ex) {
                    System.out.println("Json Ex : " + ex.toString());
                }
            }

            try {
                Thread.sleep(5000); // wait for interrupt
            } catch (InterruptedException ex) {
                System.out.println("\n[" + tid + "] InterruptedException 1 : " + ex.toString() + "\n");

                try {
                    sock.close();
                } catch (IOException ex1) {
                    System.out.println("\n[" + tid + "] IOException5 : " + ex1.toString() + "\n");
                }
                break; //
            }
        }

    } catch (IOException ex) {
        System.out.println("\n [" + tid + "] IOException1 : " + ex.toString() + "\n");
        try {
            sock.close();
            //    session.connectedClients.remove(conn);
        } catch (IOException ex1) {
            System.out.println("\n[" + tid + "] IOException2 : " + ex1.toString() + "\n");
        }
    } catch (Exception ex) {
        System.out.println("\n[" + tid + "] IOException3 : " + ex.toString() + "\n");
        try {
            sock.close();
            //    session.connectedClients.remove(conn);
        } catch (IOException ex1) {
            System.out.println("\n[" + tid + "] IOException4 : " + ex1.toString() + "\n");
        }
    }

}

From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java

/**
 * Used to limit the files if any starting or ending date exist
 * So only few files to be searched.//from   w  w w  . java 2 s . c o m
 *
 * @param filelist Iterator
 * @param startDate Date
 * @param endDate Date
 * @param reverseOrder reverse order of files
 * @return Vector
 */
static Vector<String> filterFilesByDate(Iterator<String> filelist, Date startDate, Date endDate,
        final boolean reverseOrder) {
    if (startDate == null && endDate == null) {
        // no filtering needed then just return the same list
        Vector<String> result = new Vector<String>();
        while (filelist.hasNext()) {
            result.add(filelist.next());
        }

        Collections.sort(result, new Comparator<String>() {

            public int compare(String o1, String o2) {
                if (reverseOrder)
                    return o2.compareTo(o1);
                else
                    return o1.compareTo(o2);
            }
        });

        return result;
    }
    // first convert all files to long
    TreeSet<Long> files = new TreeSet<Long>();
    while (filelist.hasNext()) {
        String filename = filelist.next();

        files.add(Long.parseLong(filename.substring(0, filename.length() - 4)));
    }

    TreeSet<Long> resultAsLong = new TreeSet<Long>();

    // Temporary fix of a NoSuchElementException
    if (files.size() == 0) {
        return new Vector<String>();
    }

    Long startLong;
    Long endLong;

    if (startDate == null)
        startLong = Long.MIN_VALUE;
    else
        startLong = startDate.getTime();

    if (endDate == null)
        endLong = Long.MAX_VALUE;
    else
        endLong = endDate.getTime();

    // get all records inclusive the one before the startdate
    for (Long f : files) {
        if (startLong <= f && f <= endLong) {
            resultAsLong.add(f);
        }
    }

    // get the subset before the start date, to get its last element
    // if exists
    if (!files.isEmpty() && files.first() <= startLong) {
        SortedSet<Long> setBeforeTheInterval = files.subSet(files.first(), true, startLong, true);
        if (!setBeforeTheInterval.isEmpty())
            resultAsLong.add(setBeforeTheInterval.last());
    }

    Vector<String> result = new Vector<String>();

    Iterator<Long> iter = resultAsLong.iterator();
    while (iter.hasNext()) {
        Long item = iter.next();
        result.add(item.toString() + ".xml");
    }

    Collections.sort(result, new Comparator<String>() {

        public int compare(String o1, String o2) {
            if (reverseOrder)
                return o2.compareTo(o1);
            else
                return o1.compareTo(o2);
        }
    });

    return result;
}

From source file:com.albert.util.StringUtilCommon.java

/**
 * Convert current academic year. ex. 0910 => 2009-2010
 * /*from   w  w  w . j ava2 s.c  o m*/
 * @param academicYr
 * @return
 */
public static String formatAcademicYear(String academicYr) {
    String rtnValue = null;
    String century1 = null;
    String century2 = null;

    if (!StringUtilCommon.isEmpty(academicYr) && academicYr.trim().length() == 4) {
        if (academicYr.compareTo("9091") >= 0) {
            century1 = "19";
            if ("9900".equals(academicYr)) {
                century2 = "19";
            } else {
                century2 = "19";
            }
        } else {
            century1 = "20";
            century2 = "20";
        }

        rtnValue = century1 + academicYr.substring(0, 2) + "-" + century2 + academicYr.substring(2);
    }

    return rtnValue;
}

From source file:marytts.util.string.StringUtils.java

public static boolean isOneOf(String item, String[] list) {
    boolean isFound = false;
    for (int i = 0; i < list.length; i++) {
        if (item.compareTo(list[i]) == 0) {
            isFound = true;// w w w  .j  a  v  a  2  s  .  c om
            break;
        }
    }

    return isFound;
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static boolean checkIgnoreFile(Folder root, File file) {
    String fileNameLower = file.getName().toLowerCase();

    /* This case is a special one. It will check if the file
       has the structure .nw_111_aaa meaning it is a new wp. */
    if (isSpecialFileToProcess(root, file)) {
        return false;
    }/*www.  j a  va 2 s .c  o  m*/

    if (isStackSyncTemporalFile(root, file)) {
        return true;
    }

    //.ds_store
    if (fileNameLower.compareTo(Constants.FILE_IGNORE_MAC_PREFIX) == 0) {
        return true;
    }

    //.thumbs.db
    if (fileNameLower.compareTo("thumbs.db") == 0) {
        return true;
    }

    // gedit temporal file
    if (fileNameLower.endsWith("~")) {
        return true;
    }

    // .file linux hidden file
    if (fileNameLower.startsWith(".")) {
        return true;
    }

    File parent = file.getParentFile();
    if (parent != null && parent.getAbsolutePath().compareTo(root.getLocalFile().getAbsolutePath()) != 0
            && parent.getAbsolutePath().length() > root.getLocalFile().getAbsolutePath().length()) {
        return checkIgnoreFile(root, parent);
    }

    return false;
}

From source file:MyComp.java

public int compare(String a, String b) {
    return b.compareTo(a);
}

From source file:com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck.java

/**
 * Checks compare two import paths./*from   ww w.j a v a 2  s  .  c o m*/
 * @param import1
 *        current import.
 * @param import2
 *        previous import.
 * @return a negative integer, zero, or a positive integer as the
 *        specified String is greater than, equal to, or less
 *        than this String, ignoring case considerations.
 */
private static int compareImports(String import1, String import2) {
    int result = 0;
    final String separator = "\\.";
    final String[] import1Tokens = import1.split(separator);
    final String[] import2Tokens = import2.split(separator);
    for (int i = 0; i < import1Tokens.length && i != import2Tokens.length; i++) {
        final String import1Token = import1Tokens[i];
        final String import2Token = import2Tokens[i];
        result = import1Token.compareTo(import2Token);
        if (result != 0) {
            break;
        }
    }
    return result;
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.BootDependenciesPanel.java

private static boolean allowable(String verRange, String bootVersion) {
    boolean ret = true;
    if (verRange != null && !verRange.isEmpty()) {
        if (verRange.indexOf('[') >= 0 || verRange.indexOf('(') >= 0 || verRange.indexOf(']') >= 0
                || verRange.indexOf(')') >= 0) {
            // bounded range
            String[] bounds = verRange.substring(1, verRange.length() - 1).split(",");
            // check there are two bounds
            if (bounds.length != 2) {
                return false;
            }/* w w w .j  a v  a  2 s . c  o m*/
            // test various cases
            if (bootVersion.compareTo(bounds[0]) > 0 && bootVersion.compareTo(bounds[1]) < 0) {
                return true;
            } else if (bootVersion.compareTo(bounds[0]) == 0 && verRange.startsWith("[")) {
                return true;
            } else if (bootVersion.compareTo(bounds[0]) == 0 && verRange.startsWith("(")) {
                return false;
            } else if (bootVersion.compareTo(bounds[1]) == 0 && verRange.endsWith("]")) {
                return true;
            } else if (bootVersion.compareTo(bounds[1]) == 0 && verRange.endsWith(")")) {
                return false;
            } else {
                return false;
            }
        } else {
            // unbounded range
            return bootVersion.compareTo(verRange) >= 0;
        }
    }
    return ret;
}

From source file:Main.java

public static int compareVersion(String s1, String s2) {
    if (s1 == null && s2 == null) {
        return 0;
    } else if (s1 != null && s2 == null) {
        return 1;
    } else if (s1 == null && s2 != null) {
        return -1;
    } else {/*w  ww. j a v a 2s  .  c o m*/
        String[] var2 = s1.split("\\.");
        String[] var3 = s2.split("\\.");

        try {
            int var4;
            for (var4 = 0; var4 < var2.length && var4 < var3.length; ++var4) {
                int var5 = Integer.parseInt(var2[var4]);
                int var6 = Integer.parseInt(var3[var4]);
                if (var5 < var6) {
                    return -1;
                }

                if (var5 > var6) {
                    return 1;
                }
            }

            return var2.length > var4 ? 1 : (var3.length > var4 ? -1 : 0);
        } catch (NumberFormatException var7) {
            return s1.compareTo(s2);
        }
    }
}

From source file:MyComparator.java

public int compare(String strA, String strB) {
    return strB.compareTo(strA);
}