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.mellanox.jxio.jxioConnection.impl.ServerWorker.java

/**
 * This function is called just before the server listener forwards a new connection to the worker
 * Reset all variables/*from   w  w  w  . ja va 2 s  .  co  m*/
 * 
 * @param ss
 *            - the new session that was constructod for this connection
 * @param sk
 *            - session key to get the uri
 */
public void prepareSession(ServerSession ss, URI uri) {
    session = ss;
    this.uri = uri;
    firstMsg = true;
    String type = getStreamType();
    if (type.compareTo("input") == 0) {
        streamWorker = new OSWorker(this, appCallbacks);
    } else if (type.compareTo("output") == 0) {
        streamWorker = new ISWorker(this, appCallbacks);
    } else {
        throw new UnsupportedOperationException("Stream type is not recognized");
    }
}

From source file:WebCrawler.java

  public void run() {
  String strURL = "http://www.google.com";
  String strTargetType = "text/html";
  int numberSearched = 0;
  int numberFound = 0;

  if (strURL.length() == 0) {
    System.out.println("ERROR: must enter a starting URL");
    return;//from ww w . j  a va  2 s  .  co  m
  }

  vectorToSearch = new Vector();
  vectorSearched = new Vector();
  vectorMatches = new Vector();

  vectorToSearch.addElement(strURL);

  while ((vectorToSearch.size() > 0)
      && (Thread.currentThread() == searchThread)) {
    strURL = (String) vectorToSearch.elementAt(0);

    System.out.println("searching " + strURL);

    URL url = null;
    try {
      url = new URL(strURL);
    } catch (MalformedURLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    vectorToSearch.removeElementAt(0);
    vectorSearched.addElement(strURL);

    try {
      URLConnection urlConnection = url.openConnection();

      urlConnection.setAllowUserInteraction(false);

      InputStream urlStream = url.openStream();
      String type = urlConnection.guessContentTypeFromStream(urlStream);
      if (type == null)
        break;
      if (type.compareTo("text/html") != 0)
        break;

      byte b[] = new byte[5000];
      int numRead = urlStream.read(b);
      String content = new String(b, 0, numRead);
      while (numRead != -1) {
        if (Thread.currentThread() != searchThread)
          break;
        numRead = urlStream.read(b);
        if (numRead != -1) {
          String newContent = new String(b, 0, numRead);
          content += newContent;
        }
      }
      urlStream.close();

      if (Thread.currentThread() != searchThread)
        break;

      String lowerCaseContent = content.toLowerCase();

      int index = 0;
      while ((index = lowerCaseContent.indexOf("<a", index)) != -1) {
        if ((index = lowerCaseContent.indexOf("href", index)) == -1)
          break;
        if ((index = lowerCaseContent.indexOf("=", index)) == -1)
          break;

        if (Thread.currentThread() != searchThread)
          break;

        index++;
        String remaining = content.substring(index);

        StringTokenizer st = new StringTokenizer(remaining, "\t\n\r\">#");
        String strLink = st.nextToken();

        URL urlLink;
        try {
          urlLink = new URL(url, strLink);
          strLink = urlLink.toString();
        } catch (MalformedURLException e) {
          System.out.println("ERROR: bad URL " + strLink);
          continue;
        }

        if (urlLink.getProtocol().compareTo("http") != 0)
          break;

        if (Thread.currentThread() != searchThread)
          break;

        try {
          URLConnection urlLinkConnection = urlLink.openConnection();
          urlLinkConnection.setAllowUserInteraction(false);
          InputStream linkStream = urlLink.openStream();
          String strType = urlLinkConnection
              .guessContentTypeFromStream(linkStream);
          linkStream.close();

          if (strType == null)
            break;
          if (strType.compareTo("text/html") == 0) {
            if ((!vectorSearched.contains(strLink))
                && (!vectorToSearch.contains(strLink))) {

              vectorToSearch.addElement(strLink);
            }
          }

          if (strType.compareTo(strTargetType) == 0) {
            if (vectorMatches.contains(strLink) == false) {
              System.out.println(strLink);
              vectorMatches.addElement(strLink);
              numberFound++;
              if (numberFound >= SEARCH_LIMIT)
                break;
            }
          }
        } catch (IOException e) {
          System.out.println("ERROR: couldn't open URL " + strLink);
          continue;
        }
      }
    } catch (IOException e) {
      System.out.println("ERROR: couldn't open URL " + strURL);
      break;
    }

    numberSearched++;
    if (numberSearched >= SEARCH_LIMIT)
      break;
  }

  if (numberSearched >= SEARCH_LIMIT || numberFound >= SEARCH_LIMIT)
    System.out.println("reached search limit of " + SEARCH_LIMIT);
  else
    System.out.println("done");
  searchThread = null;
}

From source file:au.org.ala.layers.dao.TabulationDAOImpl.java

@Override
public List<Tabulation> getTabulation(String fid1, String fid2, String wkt) {
    List<Tabulation> tabulations = null;

    String min, max;//w  w w  .  j a  va  2 s  . c o  m
    if (fid1.compareTo(fid2) < 0) {
        min = fid1;
        max = fid2;
    } else {
        min = fid2;
        max = fid1;
    }

    if (wkt == null || wkt.length() == 0) {
        /*  after "tabulation" table is updated with column "occurrences" and column "species"
         * String sql = "SELECT i.pid1, i.pid2, i.fid1, i.fid2, i.area, i.occurrences, i.species, o1.name as name1, o2.name as name2 FROM "
            + "(SELECT * FROM tabulation WHERE fid1= ? AND fid2 = ? ) i, "
            + "(SELECT * FROM objects WHERE fid= ? ) o1, "
            + "(SELECT * FROM objects WHERE fid= ? ) o2 "
            + "WHERE i.pid1=o1.pid AND i.pid2=o2.pid ;";
            * 
            */
        /* before "tabulation" table is updated with column "occurrences", to just make sure column "area" is all good */
        String sql = "SELECT i.pid1, i.pid2, i.fid1, i.fid2, i.area, o1.name as name1, o2.name as name2, i.occurrences, i.species FROM "
                + "(SELECT pid1, pid2, fid1, fid2, area, occurrences, species FROM tabulation WHERE fid1= ? AND fid2 = ? ) i, "
                + "(select t1.pid1 as pid, name from tabulation t1 left join objects o3 on t1.fid1=o3.fid and t1.pid1=o3.pid where t1.fid1= ? group by t1.pid1, name) o1, "
                //+ "(SELECT pid, name FROM objects WHERE fid= ? ) o1, "
                + "(select t2.pid2 as pid, name from tabulation t2 left join objects o4 on t2.fid2=o4.fid and t2.pid2=o4.pid where t2.fid2= ? group by t2.pid2, name) o2 "
                //+ "(SELECT pid, name FROM objects WHERE fid= ? ) o2 "
                + "WHERE i.pid1=o1.pid AND i.pid2=o2.pid ;";

        tabulations = jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(Tabulation.class),
                min, max, min, max);

    } else {
        String sql = "SELECT fid1, pid1, fid2, pid2, ST_AsText(newgeom) as geometry, name1, name2, occurrences, species FROM "
                + "(SELECT fid1, pid1, fid2, pid2, (ST_INTERSECTION(ST_GEOMFROMTEXT( ? ,4326), i.the_geom)) as newgeom, o1.name as name1, o2.name as name2, i.occurrences, i.species FROM "
                + "(SELECT * FROM tabulation WHERE fid1= ? AND fid2 = ? ) i, "
                + "(select t1.pid1 as pid, name from tabulation t1 left join objects o3 on t1.fid1=o3.fid and t1.pid1=o3.pid where t1.fid1= ? group by t1.pid1, name) o1, "
                //+ "(SELECT pid, name FROM objects WHERE fid= ? ) o1, "
                + "(select t2.pid2 as pid, name from tabulation t2 left join objects o4 on t2.fid2=o4.fid and t2.pid2=o4.pid where t2.fid2= ? group by t2.pid2, name) o2 "
                //+ "(SELECT pid, name FROM objects WHERE fid= ? ) o2 "
                + "WHERE i.pid1=o1.pid AND i.pid2=o2.pid) a "
                + "WHERE a.newgeom is not null AND ST_Area(a.newgeom) > 0;";

        tabulations = jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(Tabulation.class),
                wkt, min, max, min, max);

        for (Tabulation t : tabulations) {
            try {
                t.setArea(SpatialUtil.calculateArea(t.getGeometry()));
                t.setOccurrences(TabulationUtil.calculateOccurrences(
                        layerIntersectDao.getConfig().getOccurrenceSpeciesRecordsFilename(), t.getGeometry()));
                t.setSpecies(TabulationUtil.calculateSpecies(
                        layerIntersectDao.getConfig().getOccurrenceSpeciesRecordsFilename(), t.getGeometry()));
            } catch (Exception e) {
                logger.error("fid1:" + fid1 + " fid2:" + fid2 + " wkt:" + wkt, e);
            }
        }
    }

    //fill in 'name' for 'grids as classes'/fields.type='a'/pids with ':'
    IntersectionFile f = layerIntersectDao.getConfig().getIntersectionFile(min);
    if (f.getType().equals("a")) {
        for (Tabulation t : tabulations) {
            t.setName1(f.getClasses().get(Integer.parseInt(t.getPid1().split(":")[1])).getName());
        }
    }
    f = layerIntersectDao.getConfig().getIntersectionFile(max);
    if (f.getType().equals("a")) {
        for (Tabulation t : tabulations) {
            t.setName2(f.getClasses().get(Integer.parseInt(t.getPid2().split(":")[1])).getName());
        }
    }

    return tabulations;
}

From source file:ch.systemsx.cisd.openbis.generic.shared.dto.FilterPE.java

public int compareTo(FilterPE that) {
    final String thatName = that.getName();
    final String thisName = getName();
    if (thisName == null) {
        return thatName == null ? 0 : -1;
    }/*from   w ww  .  ja v a  2s . c  o  m*/
    if (thatName == null) {
        return 1;
    }
    return thisName.compareTo(thatName);
}

From source file:edu.cwru.apo.Home.java

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.phone) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    SharedPreferences.Editor editor = getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)
                            .edit();/*from  ww  w  .  j  a  va 2 s  .  c o m*/
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");
                    JSONArray caseID = result.getJSONArray("caseID");
                    JSONArray first = result.getJSONArray("first");
                    JSONArray last = result.getJSONArray("last");
                    JSONArray phone = result.getJSONArray("phone");
                    JSONArray family = result.getJSONArray("family");
                    ContentValues values;
                    for (int i = 0; i < numbros; i++) {
                        values = new ContentValues();
                        values.put("_id", caseID.getString(i));
                        values.put("first", first.getString(i));
                        values.put("last", last.getString(i));
                        values.put("phone", phone.getString(i));
                        values.put("family", family.getString(i));
                        database.replace("phoneDB", null, values);
                    }
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(this, "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Auth.loggedIn = false;
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                    finish();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else if (method == Methods.checkAppVersion) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    String appVersion = result.getString("version");
                    String appDate = result.getString("date");
                    final String appUrl = result.getString("url");
                    PackageInfo pinfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
                    ;
                    if (appVersion.compareTo(pinfo.versionName) != 0) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Upgrade");
                        builder.setMessage("Update available, ready to upgrade?");
                        builder.setIcon(R.drawable.icon);
                        builder.setCancelable(false);
                        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent promptInstall = new Intent("android.intent.action.VIEW",
                                        Uri.parse("https://apo.case.edu:8090/app/" + appUrl));
                                startActivity(promptInstall);
                            }
                        });
                        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    } else {
                        Toast msg = Toast.makeText(this, "No updates found", Toast.LENGTH_LONG);
                        msg.show();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NameNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:eu.trentorise.smartcampus.communicatorservice.storage.CommunicatorStorage.java

public Notification getObjectByIdAndApp(String id, String capp, Class<Notification> class1)
        throws NotFoundException {

    Criteria criteria = new Criteria();
    criteria = criteria.and("id").is(id);
    if (capp != null && capp.compareTo("") != 0) {
        criteria.and("content.type").is(capp);
    }//w  w  w.  j a  va2  s  .  c om
    criteria = criteria.and("deleted").is(false);
    List<Notification> x = find(Query.query(criteria), Notification.class);
    if (x.isEmpty())
        throw new NotFoundException();
    return x.get(FIRST);
}

From source file:io.microprofile.showcase.speaker.domain.VenueJavaOne2016.java

private Set<Speaker> getSpeakersOnline() {

    final Set<Speaker> speakers = new TreeSet<>((left, that) -> {

        final String nameFirst = left.getNameFirst().toLowerCase();
        final String thatNameFirst = that.getNameFirst().toLowerCase();

        if (nameFirst.compareTo(thatNameFirst) < 0) {
            return -1;
        } else if (nameFirst.compareTo(thatNameFirst) > 0) {
            return 1;
        }//  w  ww . j a v  a  2s. co  m

        final String nameLast = left.getNameLast().toLowerCase();
        final String thatNameLast = that.getNameLast().toLowerCase();

        if (nameLast.compareTo(thatNameLast) < 0) {
            return -1;
        } else if (nameLast.compareTo(thatNameLast) > 0) {
            return 1;
        }

        if (null != left.getOrganization()) {
            if (left.getOrganization().compareTo(that.getOrganization()) < 0) {
                return -1;
            } else if (left.getOrganization().compareTo(that.getOrganization()) > 0) {
                return 1;
            }
        }

        if (null != left.getTwitterHandle()) {
            if (left.getTwitterHandle().compareTo(that.getTwitterHandle()) < 0) {
                return -1;
            } else if (left.getTwitterHandle().compareTo(that.getTwitterHandle()) > 0) {
                return 1;
            }
        }

        if (left.getId().compareTo(that.getId()) < 0) {
            return -1;
        } else if (left.getId().compareTo(that.getId()) > 0) {
            return 1;
        }
        return 0;
    });

    if (null == System.getProperty("microprofile.speaker.scrape")) {
        return speakers;
    }

    InputStream is = null;

    try {
        is = this.url.openStream();
        is = new IncludeFilterInputStream(is, "<body", "</body>");
        final StreamLexer lexer = new StreamLexer(is);

        //Read all speaker <div> blocks
        String token;
        while (null != (token = lexer.readToken("<div class=\"cw16 cw16v1 cwidth\" ", "!-- CN"))) {
            speakers.add(this.processSpeakerToken(token));
        }

        //<div class="cw16 cw16v1 cwidth"

        //System.out.println(new String(readBytes(is)));

    } catch (final Exception e) {
        this.log.log(Level.SEVERE, "Failed to parse: " + this.url, e);
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (final Exception e) {
                //no-op
            }
        }
    }
    return speakers;
}

From source file:com.sldeditor.test.unit.tool.mapbox.MapBoxToolTest.java

/**
 * Test method for/*from  ww w. j a  v a2s.c  o  m*/
 * {@link com.sldeditor.tool.mapbox.MapBoxTool#setSelectedItems(java.util.List, java.util.List)}.
 */
@Test
public void testSetSelectedItems() {
    MapBoxTool tool = new MapBoxTool();

    JPanel panel = tool.getPanel();

    ToolButton toSLD = null;

    for (Component c : panel.getComponents()) {
        if (c instanceof ToolButton) {
            ToolButton button = (ToolButton) c;
            String toolTipText = button.getToolTipText();
            if (toolTipText
                    .compareTo(Localisation.getString(MapBoxTool.class, "MapBoxTool.exportToSLD")) == 0) {
                toSLD = button;
            }
        }
    }

    File testFile1 = null;
    File testFile3 = null;
    try {
        testFile1 = File.createTempFile("invalid", ".tst");
        testFile3 = File.createTempFile("valid", ".json");
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Should both be disabled
    assertFalse(toSLD.isEnabled());

    tool.setSelectedItems(null, null);

    // Invalid file
    List<SLDDataInterface> sldDataList = new ArrayList<SLDDataInterface>();
    SLDData sldData1 = new SLDData(null, null);
    sldData1.setSLDFile(testFile1);
    sldDataList.add(sldData1);
    tool.setSelectedItems(null, sldDataList);

    // Should both be disabled
    assertFalse(toSLD.isEnabled());

    /*
     * // Try with valid mapbox file sldDataList = new ArrayList<SLDDataInterface>(); SLDData
     * sldData3 = getSLDDataFile("/point/mapbox/circleStyleTest.json");
     * sldDataList.add(sldData3); tool.setSelectedItems(null, sldDataList);
     * 
     * // SLD should be enabled assertTrue(toSLD.isEnabled()); toSLD.doClick();
     * 
     * // Try with valid sld files sldDataList = new ArrayList<SLDDataInterface>();
     * sldDataList.add(sldData3); tool.setSelectedItems(null, sldDataList);
     * 
     * // SLD should be enabled assertTrue(toSLD.isEnabled());
     */

    testFile1.delete();
    testFile3.delete();

    // tidyUpTempFiles(sldData3.getSLDFile());
}

From source file:com.sfs.dao.FieldMapDAOImpl.java

/**
 * Load a map of FieldMapBeans based on the supplied map class and type
 * variables./* w  w  w  .  j a  v  a  2  s. c  o m*/
 *
 * @param mapClass the map class
 * @param mapType the map type
 *
 * @return the map< string, field map bean>
 *
 * @throws SFSDaoException the SFS dao exception
 */
@SuppressWarnings("unchecked")
public final Map<String, FieldMapBean> load(final String mapClass, final String mapType)
        throws SFSDaoException {
    if (mapClass == null) {
        throw new SFSDaoException("Error: field map class cannot be null");
    }
    if (mapClass.compareTo("") == 0) {
        throw new SFSDaoException("Error: field map class cannot be an " + "empty string");
    }
    if (mapType == null) {
        throw new NullPointerException("Error: field map type cannot " + "be null");
    }
    dataLogger.info("Field maps for: " + mapClass + " - " + mapType + " requested");

    Map<String, FieldMapBean> fieldHash = new HashMap<String, FieldMapBean>();

    Collection<FieldMapBean> fieldMaps = new ArrayList<FieldMapBean>();
    try {
        fieldMaps = this.getJdbcTemplateReader().query(this.getSQL().getValue("fieldMap/loadName"),
                new Object[] { mapClass, mapType }, new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        return loadFieldMap(rs);
                    }
                });

    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for this search: " + ie.getMessage());
    }

    for (FieldMapBean fieldMap : fieldMaps) {
        fieldHash.put(fieldMap.getName(), fieldMap);
    }
    return fieldHash;
}

From source file:eu.trentorise.smartcampus.communicatorservice.storage.CommunicatorStorage.java

public Notification getObjectByIdAndUser(String id, String userId, Class<Notification> class1)
        throws NotFoundException {
    Criteria criteria = new Criteria();
    criteria = criteria.and("id").is(id);
    if (userId != null && userId.compareTo("") != 0) {
        criteria.and("content.user").is(userId);
    }//from w w  w .  j  a va  2 s  .co m
    criteria = criteria.and("deleted").is(false);
    List<Notification> x = find(Query.query(criteria), Notification.class);
    if (x.isEmpty())
        throw new NotFoundException();
    return x.get(FIRST);
}