Example usage for java.lang Integer compareTo

List of usage examples for java.lang Integer compareTo

Introduction

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

Prototype

public int compareTo(Integer anotherInteger) 

Source Link

Document

Compares two Integer objects numerically.

Usage

From source file:org.finra.dm.core.ArgumentParser.java

/**
 * Retrieves the argument as an Integer object, if any, of an option and validates it against minimum and maximum allowed values.
 *
 * @param option the option that we want argument value to be returned for
 * @param defaultValue is the default value to be returned if the option is not specified
 * @param minValue the minimum allowed Integer value for the option
 * @param maxValue the maximum allowed Integer value for the option
 *
 * @return Value of the argument if option is set, and has an argument, otherwise defaultValue.
 * @throws IllegalArgumentException if there are problems with the option value
 */// ww w.  j  av  a 2 s .  c  o m
public Integer getIntegerValue(Option option, Integer defaultValue, Integer minValue, Integer maxValue)
        throws IllegalArgumentException {
    Integer answer = getIntegerValue(option, defaultValue);

    if (answer != null) {
        Assert.isTrue(answer.compareTo(minValue) >= 0,
                String.format("The %s option value %d is less than the minimum allowed value of %d.",
                        option.getLongOpt(), answer, minValue));
        Assert.isTrue(answer.compareTo(maxValue) <= 0,
                String.format("The %s option value %d is bigger than maximum allowed value of %d.",
                        option.getLongOpt(), answer, maxValue));
    }

    return answer;
}

From source file:org.pdfgal.pdfgalweb.validators.utils.impl.ValidatorUtilsImpl.java

/**
 * This method represents the loop for the validateConcretePages method.
 * //  www  .  j a  va 2s  .  c o  m
 * @param totalPages
 * @param pages
 * @param delim1
 * @param delim2
 * @param moreThanOne
 * @return
 */
private boolean validateConcretePagesLoop(final Integer totalPages, final String pages, final String delim1,
        final String delim2, final boolean testMoreThanOne) {

    boolean result = false;

    if (totalPages != null && StringUtils.isNotEmpty(pages) && StringUtils.isNotEmpty(delim1)) {

        result = true;

        final StringTokenizer st = new StringTokenizer(pages, delim1);
        Integer previous = null;
        String token = null;
        if ("-".equals(delim1) && st.countTokens() != 2) {
            result = false;
        } else {
            while (st.hasMoreElements()) {
                try {
                    token = st.nextToken();
                    final Integer current = Integer.valueOf(token);
                    boolean isMoreThan = true;
                    if (testMoreThanOne) {
                        isMoreThan = (current.compareTo(new Integer(2)) < 0);
                    } else {
                        isMoreThan = (current.compareTo(new Integer(1)) < 0);
                    }
                    if ((current.compareTo(totalPages) > 0) || isMoreThan
                            || (previous != null && current.compareTo(previous) <= 0)) {
                        result = false;
                        break;
                    }
                    previous = current;

                } catch (final Exception e) {
                    if (StringUtils.isNotEmpty(delim2)) {
                        result = this.validateConcretePagesLoop(totalPages, token, delim2, null,
                                testMoreThanOne);

                    } else {
                        result = false;
                    }

                    if (!result) {
                        break;
                    }
                }
            }
        }
    }

    return result;
}

From source file:org.intermine.bio.dataconversion.BioFileConverter.java

/**
 * Make a Location between a Feature and a Chromosome.
 * @param chromosomeId Chromosome Item identifier
 * @param sequenceFeatureId the Item identifier of the feature
 * @param startString the start position
 * @param endString the end position//from  w  w w .  j a  v  a2  s.c  o  m
 * @param strand the strand
 * @param store if true the location item will be saved in the database
 * @return the new Location object
 */
protected Item makeLocation(String chromosomeId, String sequenceFeatureId, String startString, String endString,
        String strand, boolean store) {
    Item location = createItem("Location");
    Integer start = new Integer(Integer.parseInt(startString));
    Integer end = new Integer(Integer.parseInt(endString));

    if (start.compareTo(end) <= 0) {
        location.setAttribute("start", startString);
        location.setAttribute("end", endString);
    } else {
        location.setAttribute("start", endString);
        location.setAttribute("end", startString);
    }
    if (StringUtils.isNotEmpty(strand)) {
        location.setAttribute("strand", strand);
    }
    location.setReference("locatedOn", chromosomeId);
    location.setReference("feature", sequenceFeatureId);

    if (store) {
        try {
            store(location);
        } catch (ObjectStoreException e) {
            throw new RuntimeException("failed to store location", e);
        }
    }
    return location;
}

From source file:com.inmobi.databus.purge.DataPurgerService.java

private void addMergedStreams() {
    Map<String, DestinationStream> destinationStreamMapStreamMap = cluster.getDestinationStreams();
    Set<Map.Entry<String, DestinationStream>> entrySet = destinationStreamMapStreamMap.entrySet();
    Iterator it = entrySet.iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        String streamName = (String) entry.getKey();
        DestinationStream consumeStream = (DestinationStream) entry.getValue();
        Integer mergedStreamRetentionInHours = consumeStream.getRetentionInHours();
        LOG.debug("Merged Stream :: streamName [" + streamName + "] mergedStreamRetentionInHours ["
                + mergedStreamRetentionInHours + "]");
        if (streamRetention.get(streamName) == null) {
            streamRetention.put(streamName, mergedStreamRetentionInHours);
            LOG.debug("Adding Merged Stream [" + streamName + "] retentionInHours ["
                    + mergedStreamRetentionInHours + "]");
        } else {/*from   w  w  w. j  a  v a2 s  . c o m*/
            // Partial & Merged stream are produced at this cluster
            // choose max retention period
            Integer partialStreamRetentionInHours = streamRetention.get(streamName);
            if (partialStreamRetentionInHours.compareTo(mergedStreamRetentionInHours) > 0) {
                streamRetention.put(streamName, partialStreamRetentionInHours);
                LOG.debug("Overriding Stream [" + streamName + "] retentionInHours ["
                        + partialStreamRetentionInHours + "]");

            } else {
                streamRetention.put(streamName, mergedStreamRetentionInHours);
                LOG.debug("Overriding Stream [" + streamName + "] retentionInHours ["
                        + mergedStreamRetentionInHours + "]");

            }

        }
    }
}

From source file:com.feilong.commons.core.util.StringUtilTest.java

/**
 * Compare to.//from  w ww  .  j  av  a2s.  c  o m
 */
@Test
public void compareTo() {
    log.info("" + "8".compareTo("13"));

    final Integer parseInt = Integer.parseInt("8");

    log.info("" + parseInt.compareTo(Integer.parseInt("13")));
    log.info("" + "12".compareTo("13"));
}

From source file:op.care.med.structure.DlgTradeForm.java

private void txtExpiresInFocusLost(FocusEvent e) {
    if (initPhase)
        return;/*from ww  w . j  a  v a  2 s.c o m*/
    Integer i = SYSTools.checkInteger(txtExpiresIn.getText());
    if (i == null || i.compareTo(0) <= 0) {
        i = 7;
        txtExpiresIn.setText("7");
    }
    if (cmbDaysWeeks.getSelectedIndex() == 1) {
        tradeForm.setDaysToExpireAfterOpened(i * 7);
    } else {
        tradeForm.setDaysToExpireAfterOpened(i);
    }

}

From source file:op.care.med.structure.DlgTradeForm.java

private void cmbDaysWeeksItemStateChanged(ItemEvent e) {
    if (initPhase)
        return;//from  w w  w.j a  va 2 s.  c om
    if (e.getStateChange() == ItemEvent.SELECTED) {
        Integer i = SYSTools.checkInteger(txtExpiresIn.getText());
        if (i == null || i.compareTo(0) <= 0) {
            i = 7;
            txtExpiresIn.setText("7");
        }
        if (cmbDaysWeeks.getSelectedIndex() == 1) {
            tradeForm.setDaysToExpireAfterOpened(i * 7);
        } else {
            tradeForm.setDaysToExpireAfterOpened(i);
        }
    }
}

From source file:org.openmrs.module.reporting.web.datasets.PatientDataSetEditor.java

@RequestMapping(value = "/module/reporting/datasets/patientDataSetEditor-sortColumns", method = RequestMethod.POST)
public String sortColumns(WebRequest request, HttpSession session) {
    final List<String> columnOrder = new ArrayList<String>();
    int i = 0;//ww w .  j  a v a  2s. co  m
    while (true) {
        String colName = request.getParameter("column" + i);
        if (colName == null)
            break;
        columnOrder.add(colName);
        ++i;
    }

    PatientDataSetDefinition dsd = getFromSession(session);
    Collections.sort(dsd.getColumnDefinitions(), new Comparator<RowPerObjectColumnDefinition>() {
        public int compare(RowPerObjectColumnDefinition left, RowPerObjectColumnDefinition right) {
            Integer leftIndex = columnOrder.indexOf(left.getName());
            Integer rightIndex = columnOrder.indexOf(right.getName());
            return leftIndex.compareTo(rightIndex);
        }
    });
    putInSession(session, dsd, true);
    return "redirect:patientDataSetEditor.form";
}

From source file:org.drools.workbench.jcr2vfsmigration.jcrExport.ModuleAssetExporter.java

private XmlAssets exportAssetHistory(ExportContext historyContext) throws SerializationException {
    XmlAssets xmlAssets = new XmlAssets();

    //loadItemHistory wont return the current version
    String currentVersionAssetName = "";
    try {/*w w w.  j  ava2s .com*/
        TableDataResult history = jcrRepositoryAssetService.loadItemHistory(historyContext.getAssetUUID());
        TableDataRow[] rows = history.data;
        Arrays.sort(rows, new Comparator<TableDataRow>() {
            public int compare(TableDataRow r1, TableDataRow r2) {
                Integer v2 = Integer.valueOf(r2.values[0]);
                Integer v1 = Integer.valueOf(r1.values[0]);

                return v1.compareTo(v2);
            }
        });

        String historicalAssetExportFileName = "h_" + historyContext.getAssetExportFileName();
        for (TableDataRow row : rows) {
            AssetItem historicalAssetJCR = rulesRepository.loadAssetByUUID(row.id);
            currentVersionAssetName = historicalAssetJCR.getName();

            ExportContext historicalAssetExportContext = ExportContext.create(historyContext.getJcrModule(),
                    historicalAssetJCR, historicalAssetExportFileName);
            xmlAssets.addAsset(export(historicalAssetExportContext));

            logger.info("    Asset [{}.{}] migrated: version [{}], comment [{}], lastModified [{}]",
                    historicalAssetJCR.getName(), historicalAssetJCR.getFormat(),
                    historicalAssetJCR.getVersionNumber(), historicalAssetJCR.getCheckinComment(),
                    historicalAssetJCR.getLastModified().getTime());
        }
    } catch (RuntimeException e) {
        logger.error("Exception migrating assetHistory at version {} from module {}!", currentVersionAssetName,
                historyContext.getJcrModule().getName());
    }
    return xmlAssets;
}

From source file:ubic.gemma.core.loader.protein.string.StringProteinProteinInteractionFileParser.java

/**
 * Typical line of string file is of the following format:
 * <pre>//  w  w  w.j  av  a2s .c o m
 * 882.DVU0001 882.DVU0002 707 0 0 0 0 0 172 742
 * </pre>
 * 882.DVU0001 and 882.DVU0002 refer to protein 1 and protein2 Note the 882 is the ncbi taxon id, the other part is
 * an external id (ensembl). Method takes the array representing a line of string file and creates a
 * StringProteinProteinInteraction object.
 *
 * @param fields Line split on delimiter
 * @return StringProteinProteinInteraction value object.
 */
public StringProteinProteinInteraction createStringProteinProteinInteraction(String[] fields) {
    // validate
    if (fields == null) {
        return null;
    }
    if (fields[0] == null || fields[1] == null || fields[0].isEmpty() || fields[1].isEmpty()) {
        return null;
    }

    String[] protein1AndTaxa = StringUtils.split(fields[0], ".");
    int taxonIdProtein1 = Integer.parseInt(protein1AndTaxa[0]);

    String[] protein2AndTaxa = StringUtils.split(fields[1], ".");
    int taxonIdProtein2 = Integer.parseInt(protein2AndTaxa[0]);

    // Check that the two proteins taxa match that is the taxon appended to protein name match
    if (taxonIdProtein1 != taxonIdProtein2) {
        throw new FileFormatException(
                "Protein 1 " + fields[0] + " protein 2  " + fields[1] + " do not contain matching taxons");
    }
    // taxon not supported skip it
    if (!(this.getNcbiValidTaxon()).contains(taxonIdProtein1)) {
        return null;
    }

    // always ensure that protein 1 and protein 2 are set same alphabetical order makes matching much easier later
    // hashcode equality method relies on them being in consistent order.
    // use hashcode as mixed alphanumeric code
    Integer protein1Infile = fields[0].hashCode();
    Integer protein2InFile = fields[1].hashCode();
    StringProteinProteinInteraction stringProteinProteinInteraction;

    if (protein1Infile.compareTo(protein2InFile) < 0) {
        stringProteinProteinInteraction = new StringProteinProteinInteraction(fields[0], fields[1]);
    } else {
        stringProteinProteinInteraction = new StringProteinProteinInteraction(fields[1], fields[0]);
    }

    stringProteinProteinInteraction.setNcbiTaxonId(taxonIdProtein1);

    // validate the line make sure these fields are numeric
    for (int i = 2; i < fields.length; i++) {
        if (!StringUtils.isNumeric(fields[i])) {
            throw new FileFormatException("This line does not contain valid number ");
        }
    }

    stringProteinProteinInteraction.addEvidenceCodeScoreToMap(
            StringProteinInteractionEvidenceCodeEnum.NEIGHBORHOOD, Integer.valueOf(fields[2]));
    stringProteinProteinInteraction.addEvidenceCodeScoreToMap(
            StringProteinInteractionEvidenceCodeEnum.GENEFUSION, Integer.valueOf(fields[3]));
    stringProteinProteinInteraction.addEvidenceCodeScoreToMap(
            StringProteinInteractionEvidenceCodeEnum.COOCCURENCE, Integer.valueOf(fields[4]));
    stringProteinProteinInteraction.addEvidenceCodeScoreToMap(
            StringProteinInteractionEvidenceCodeEnum.COEXPRESSION, Integer.valueOf(fields[5]));
    stringProteinProteinInteraction.addEvidenceCodeScoreToMap(
            StringProteinInteractionEvidenceCodeEnum.EXPERIMENTAL, Integer.valueOf(fields[6]));
    stringProteinProteinInteraction.addEvidenceCodeScoreToMap(StringProteinInteractionEvidenceCodeEnum.DATABASE,
            Integer.valueOf(fields[7]));
    stringProteinProteinInteraction.addEvidenceCodeScoreToMap(
            StringProteinInteractionEvidenceCodeEnum.TEXTMINING, Integer.valueOf(fields[8]));

    stringProteinProteinInteraction.setCombined_score(Double.valueOf(fields[9]));
    return stringProteinProteinInteraction;
}