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:dk.sdu.mmmi.featureous.views.featurecharacterization.FeatureViewChart.java

private void doItForClass(boolean uniformSize) {
    // Sort according to category rank
    Set<ClassModel> cmsSet = new HashSet<ClassModel>();
    List<ClassModel> cms = new ArrayList<ClassModel>();
    for (TraceModel tm : ftms) {
        cmsSet.addAll(tm.getClasses().values());
    }//  ww  w. jav a 2  s.  c  o m
    cms.addAll(cmsSet);
    Collections.sort(cms, new Comparator<ClassModel>() {

        public int compare(ClassModel o1, ClassModel o2) {
            Integer o1r = Controller.getInstance().getAffinity().getClassAffinity(o1.getName()).weigth;
            Integer o2r = Controller.getInstance().getAffinity().getClassAffinity(o2.getName()).weigth;
            return o1r.compareTo(o2r);
        }
    });
    // Insert data
    for (ClassModel cm : cms) {
        for (Result r : scattering) {
            int specific = 0;
            TraceModel tm = null;
            for (TraceModel t : ftms) {
                if (t.getName().equals(r.name)) {
                    tm = t;
                    break;
                }
            }
            if (!tm.hasClass(cm.getName())) {
                continue;
            }
            Controller c = Controller.getInstance();
            double val = 0d;
            if (uniformSize) {
                val = 1f / tm.getClassSet().size();
            } else {
                val = r.value / tm.getClassSet().size();
            }
            data.addValue(val, cm.getName(), r.name);
        }
    }
    Controller c = Controller.getInstance();
    for (int i = 0; i < data.getRowCount(); i++) {
        for (ClassModel cm : c.getTraceSet().getAllClassIDs()) {
            if (cm.getName().equals(data.getRowKey(i).toString())) {
                Color col = Controller.getInstance().getAffinity().getClassAffinity(cm.getName()).color;
                plot.getRenderer().setSeriesPaint(i, col);
                plot.getRenderer().setSeriesOutlinePaint(i, col);
                break;
            }
        }
    }
}

From source file:com.swordlord.jalapeno.datatable.DataTableBase.java

/**
 * Compare Fields with "." like 1.2.4/*from w w  w. ja  v  a2s .  c  om*/
 * 
 * @param bAscending
 *            Ascending compare
 * @param value1
 *            value to compare
 * @param value2
 *            value to compare
 * @return
 */
protected int compareDotNumber(boolean bAscending, Object value1, Object value2) {
    String strVal1 = "";
    String strVal2 = "";

    if (value1 instanceof List) {
        strVal1 = ((List<?>) value1).get(0).toString().trim();
    } else {
        strVal1 = value1.toString();
    }

    if (value2 instanceof List) {
        strVal2 = ((List<?>) value2).get(0).toString().trim();
    } else {
        strVal2 = value2.toString();
    }

    String[] strArr1 = strVal1.split("\\.");
    String[] strArr2 = strVal2.split("\\.");

    // this is a neat little hack to make sure that both arrays are of the
    // same size
    if (strArr1.length > strArr2.length) {
        for (int i = strArr2.length; i < strArr1.length; i++) {
            strVal2 += ".0";
        }

        strArr2 = strVal2.split("\\.");
    } else {
        for (int i = strArr1.length; i < strArr2.length; i++) {
            strVal1 += ".0";
        }

        strArr1 = strVal1.split("\\.");
    }

    for (int i = 0; i < strArr1.length; i++) {
        try {
            Integer int1 = Integer.parseInt(strArr1[i].trim());
            Integer int2 = Integer.parseInt(strArr2[i].trim());

            int compareResult = int1.compareTo(int2);
            if (compareResult != 0) {
                return (bAscending) ? compareResult : -compareResult;
            }
        } catch (NumberFormatException e) {
            int compareResult = ConversionUtil.toComparable(strArr1[i])
                    .compareTo(ConversionUtil.toComparable(strArr2[i]));
            if (compareResult != 0) {
                return (bAscending) ? compareResult : -compareResult;
            }
        }
    }

    return 0;
}

From source file:nl.nn.adapterframework.pipes.CompareIntegerPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {

    String sessionKey1StringValue = (String) session.get(sessionKey1);
    String sessionKey2StringValue = (String) session.get(sessionKey2);

    if (log.isDebugEnabled()) {
        log.debug("sessionKey1StringValue [" + sessionKey1StringValue + "]");
        log.debug("sessionKey2StringValue [" + sessionKey2StringValue + "]");
    }//from  www.java2s .co  m

    Integer sessionKey1IntegerValue;
    Integer sessionKey2IntegerValue;
    try {
        sessionKey1IntegerValue = new Integer(sessionKey1StringValue);
        sessionKey2IntegerValue = new Integer(sessionKey2StringValue);
    } catch (Exception e) {
        PipeRunException prei = new PipeRunException(this, "Exception while comparing integers", e);
        throw prei;
    }

    int comparison = sessionKey1IntegerValue.compareTo(sessionKey2IntegerValue);
    if (comparison == 0)
        return new PipeRunResult(findForward(EQUALSFORWARD), input);
    else if (comparison < 0)
        return new PipeRunResult(findForward(LESSTHANFORWARD), input);
    else
        return new PipeRunResult(findForward(GREATERTHANFORWARD), input);

}

From source file:org.eclipse.virgo.ide.runtime.internal.core.DefaultServerDeployer.java

/**
 * {@inheritDoc}/*w  w w .j a  v a  2s  .c  o m*/
 */
public void deploy(IModule... modules) {
    List<IModule> orderedModules = Arrays.asList(modules);

    // make sure we honor the user configured order
    final List<String> orderedArtefacts = getArtefactOrder();

    // sort the modules according the order defined in the server configuration
    Collections.sort(orderedModules, new Comparator<IModule>() {

        public int compare(IModule o1, IModule o2) {
            Integer m1 = (orderedArtefacts.contains(o1.getId()) ? orderedArtefacts.indexOf(o1.getId())
                    : Integer.MAX_VALUE);
            Integer m2 = (orderedArtefacts.contains(o2.getId()) ? orderedArtefacts.indexOf(o2.getId())
                    : Integer.MAX_VALUE);
            return m1.compareTo(m2);
        }
    });

    for (IModule module : orderedModules) {
        DeploymentIdentity identity = executeDeployerCommand(getServerDeployCommand(module));
        if (behaviour instanceof ServerBehaviour) {
            ((ServerBehaviour) behaviour).tail(identity);
        }
        behaviour.onModulePublishStateChange(new IModule[] { module }, IServer.PUBLISH_STATE_NONE);
        // if (identity != null) {
        // behaviour.onModuleStateChange(new IModule[] { module }, IServer.STATE_STARTED);
        // }
        // else {
        // behaviour.onModuleStateChange(new IModule[] { module }, IServer.STATE_STOPPED);
        // }
    }
}

From source file:com.aurel.track.fieldType.runtime.base.WBSComparable.java

@Override
public int compareTo(Object o) {
    WBSComparable wbsComparable = (WBSComparable) o;
    List<Integer> paramWbsOnLevelsList = wbsComparable.getWbsOnLevelsList();
    if ((wbsOnLevelsList == null || wbsOnLevelsList.isEmpty())
            && (paramWbsOnLevelsList == null || paramWbsOnLevelsList.isEmpty())) {
        return 0;
    }/*  w  w  w.  j  ava 2s.com*/
    if (wbsOnLevelsList == null || wbsOnLevelsList.isEmpty()) {
        return -1;
    }
    if (paramWbsOnLevelsList == null || paramWbsOnLevelsList.isEmpty()) {
        return 1;
    }
    int length = wbsOnLevelsList.size();
    int paramLength = paramWbsOnLevelsList.size();
    int minLength = length;
    if (minLength > paramLength) {
        minLength = paramLength;
    }
    for (int i = 0; i < minLength; i++) {
        Integer wbsOnLevel = wbsOnLevelsList.get(i);
        Integer paramWbsOnLevel = paramWbsOnLevelsList.get(i);
        if (wbsOnLevel == null && paramWbsOnLevel == null) {
            return 0;
        }
        if (wbsOnLevel == null) {
            return -1;
        }
        if (paramWbsOnLevel == null) {
            return 1;
        }
        try {
            int compareResult = wbsOnLevel.compareTo(paramWbsOnLevel);
            if (compareResult != 0) {
                //return only if the part if different
                return compareResult;
            }
        } catch (Exception e) {
            LOGGER.warn("Sorting the values " + wbsOnLevel + " of class " + wbsOnLevel.getClass().getName()
                    + " and " + paramWbsOnLevel + " of class " + paramWbsOnLevel.getClass().getName()
                    + " failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    //ancestor-descendant relation: the longer the path the later in wbs
    return Integer.valueOf(length).compareTo(Integer.valueOf(paramLength));
}

From source file:com.richtodd.android.quiltdesign.block.PaperPiecedBlock.java

public void sort(HashMap<UUID, Integer> pieceIndexes) {
    final HashMap<UUID, Integer> pieceIndexesCaptured = pieceIndexes;
    Collections.sort(m_pieces, new Comparator<PaperPiecedBlockPiece>() {

        @Override/*  w  w  w .  j  a  va  2s  .c  om*/
        public int compare(PaperPiecedBlockPiece lhs, PaperPiecedBlockPiece rhs) {
            Integer lhsValue = pieceIndexesCaptured.get(lhs.getId());
            Integer rhsValue = pieceIndexesCaptured.get(rhs.getId());

            if (lhsValue == null)
                lhsValue = 0;
            if (rhsValue == null)
                rhsValue = 0;

            return lhsValue.compareTo(rhsValue);
        }
    });
}

From source file:org.kuali.coeus.common.committee.impl.rules.CommitteeScheduleDayRule.java

private boolean validateDay(Integer day, String month, String key) {
    boolean rulePassed = true;
    int maxDay;/*from www  .  j av  a2 s. com*/

    if (StringUtils.equalsIgnoreCase(month, "FEBRUARY")) {
        maxDay = 29;
    } else if (StringUtils.equalsIgnoreCase(month, "APRIL") || StringUtils.equalsIgnoreCase(month, "JUNE")
            || StringUtils.equalsIgnoreCase(month, "SEPTEMBER")
            || StringUtils.equalsIgnoreCase(month, "NOVEMBER")) {
        maxDay = 30;
    } else {
        maxDay = 31;
    }

    if ((day != null) && (day.compareTo(maxDay) > 0)) {
        rulePassed = false;
        reportError(key, KeyConstants.ERROR_COMMITTEESCHEDULE_DAY, "31");
    }

    return rulePassed;
}

From source file:azkaban.viewer.reportal.ReportalMailCreator.java

private boolean createMessage(Project project, ExecutableFlow flow, EmailMessage message, String urlPrefix,
        boolean printData) throws Exception {
    message.println("<html>");
    message.println("<head></head>");
    message.println(//from  ww w.ja  v  a  2  s  .c om
            "<body style='font-family: verdana; color: #000000; background-color: #cccccc; padding: 20px;'>");
    message.println(
            "<div style='background-color: #ffffff; border: 1px solid #aaaaaa; padding: 20px;-webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px;'>");
    // Title
    message.println("<b>" + project.getMetadata().get("title") + "</b>");
    message.println("<div style='font-size: .8em; margin-top: .5em; margin-bottom: .5em;'>");
    // Status
    message.println(flow.getStatus().name());
    // Link to logs
    message.println("(<a href='" + urlPrefix + "?view&logs&id=" + flow.getProjectId() + "&execid="
            + flow.getExecutionId() + "'>Logs</a>)");
    // Link to Data
    message.println("(<a href='" + urlPrefix + "?view&id=" + flow.getProjectId() + "&execid="
            + flow.getExecutionId() + "'>Result data</a>)");
    // Link to Edit
    message.println("(<a href='" + urlPrefix + "?edit&id=" + flow.getProjectId() + "'>Edit</a>)");
    message.println("</div>");
    message.println("<div style='margin-top: .5em; margin-bottom: .5em;'>");
    // Description
    message.println(project.getDescription());
    message.println("</div>");

    // Print variable values, if any
    Map<String, String> flowParameters = flow.getExecutionOptions().getFlowParameters();
    int i = 0;
    while (flowParameters.containsKey("reportal.variable." + i + ".from")) {
        if (i == 0) {
            message.println(
                    "<div style='margin-top: 10px; margin-bottom: 10px; border-bottom: 1px solid #ccc; padding-bottom: 5px; font-weight: bold;'>");
            message.println("Variables");
            message.println("</div>");
            message.println("<table border='1' cellspacing='0' cellpadding='2' style='font-size: 14px;'>");
            message.println("<thead><tr><th><b>Name</b></th><th><b>Value</b></th></tr></thead>");
            message.println("<tbody>");
        }

        message.println("<tr>");
        message.println("<td>" + flowParameters.get("reportal.variable." + i + ".from") + "</td>");
        message.println("<td>" + flowParameters.get("reportal.variable." + i + ".to") + "</td>");
        message.println("</tr>");

        i++;
    }

    if (i > 0) { // at least one variable
        message.println("</tbody>");
        message.println("</table>");
    }

    if (printData) {
        String locationFull = (outputLocation + "/" + flow.getExecutionId()).replace("//", "/");

        IStreamProvider streamProvider = ReportalUtil.getStreamProvider(outputFileSystem);

        if (streamProvider instanceof StreamProviderHDFS) {
            StreamProviderHDFS hdfsStreamProvider = (StreamProviderHDFS) streamProvider;
            hdfsStreamProvider.setHadoopSecurityManager(hadoopSecurityManager);
            hdfsStreamProvider.setUser(reportalStorageUser);
        }

        // Get file list
        String[] fileList = ReportalHelper.filterCSVFile(streamProvider.getFileList(locationFull));

        // Sort files in execution order.
        // File names are in the format {EXECUTION_ORDER}-{QUERY_TITLE}.csv
        // E.g.: 1-queryTitle.csv
        Arrays.sort(fileList, new Comparator<String>() {
            public int compare(String a, String b) {
                Integer aExecutionOrder = Integer.parseInt(a.substring(0, a.indexOf('-')));
                Integer bExecutionOrder = Integer.parseInt(b.substring(0, b.indexOf('-')));
                return aExecutionOrder.compareTo(bExecutionOrder);
            }

            public boolean equals(Object obj) {
                return this.equals(obj);
            }
        });

        // Get jobs in execution order
        List<ExecutableNode> jobs = ReportalUtil.sortExecutableNodes(flow);

        File tempFolder = new File(reportalMailTempDirectory + "/" + flow.getExecutionId());
        tempFolder.mkdirs();

        // Copy output files from HDFS to local disk, so you can send them as email attachments
        for (String file : fileList) {
            String filePath = locationFull + "/" + file;
            InputStream csvInputStream = null;
            OutputStream tempOutputStream = null;
            File tempOutputFile = new File(tempFolder, file);
            tempOutputFile.createNewFile();
            try {
                csvInputStream = streamProvider.getFileInputStream(filePath);
                tempOutputStream = new BufferedOutputStream(new FileOutputStream(tempOutputFile));

                IOUtils.copy(csvInputStream, tempOutputStream);
            } finally {
                IOUtils.closeQuietly(tempOutputStream);
                IOUtils.closeQuietly(csvInputStream);
            }
        }

        try {
            streamProvider.cleanUp();
        } catch (IOException e) {
            e.printStackTrace();
        }

        boolean emptyResults = true;

        for (i = 0; i < fileList.length; i++) {
            String file = fileList[i];
            ExecutableNode job = jobs.get(i);
            job.getAttempt();

            message.println(
                    "<div style='margin-top: 10px; margin-bottom: 10px; border-bottom: 1px solid #ccc; padding-bottom: 5px; font-weight: bold;'>");
            message.println(file);
            message.println("</div>");
            message.println("<div>");
            message.println("<table border='1' cellspacing='0' cellpadding='2' style='font-size: 14px;'>");
            File tempOutputFile = new File(tempFolder, file);
            InputStream csvInputStream = null;
            try {
                csvInputStream = new BufferedInputStream(new FileInputStream(tempOutputFile));
                Scanner rowScanner = new Scanner(csvInputStream);
                int lineNumber = 0;
                while (rowScanner.hasNextLine() && lineNumber <= NUM_PREVIEW_ROWS) {
                    // For Hive jobs, the first line is the column names, so we ignore it
                    // when deciding whether the output is empty or not
                    if (!job.getType().equals(ReportalType.HiveJob.getJobTypeName()) || lineNumber > 0) {
                        emptyResults = false;
                    }

                    String csvLine = rowScanner.nextLine();
                    String[] data = csvLine.split("\",\"");
                    message.println("<tr>");
                    for (String item : data) {
                        String column = StringEscapeUtils.escapeHtml(item.replace("\"", ""));
                        message.println("<td>" + column + "</td>");
                    }
                    message.println("</tr>");
                    if (lineNumber == NUM_PREVIEW_ROWS && rowScanner.hasNextLine()) {
                        message.println("<tr>");
                        message.println("<td colspan=\"" + data.length + "\">...</td>");
                        message.println("</tr>");
                    }
                    lineNumber++;
                }
                rowScanner.close();
                message.println("</table>");
                message.println("</div>");
            } finally {
                IOUtils.closeQuietly(csvInputStream);
            }
            message.addAttachment(file, tempOutputFile);
        }

        // Don't send an email if there are no results, unless this is an unscheduled run.
        String unscheduledRun = flowParameters.get("reportal.unscheduled.run");
        boolean isUnscheduledRun = unscheduledRun != null && unscheduledRun.trim().equalsIgnoreCase("true");
        if (emptyResults && !isUnscheduledRun) {
            return false;
        }
    }

    message.println("</div>").println("</body>").println("</html>");

    return true;
}

From source file:com.cloud.test.regression.ApiCommand.java

public static boolean verifyEvents(String fileName, String level, String host, String account) {
    boolean result = false;
    HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    String key = "";

    File file = new File(fileName);
    if (file.exists()) {
        Properties pro = new Properties();
        try {/*  w  ww.j  av a2  s .co  m*/
            // get expected events
            FileInputStream in = new FileInputStream(file);
            pro.load(in);
            Enumeration<?> en = pro.propertyNames();
            while (en.hasMoreElements()) {
                key = (String) en.nextElement();
                expectedEvents.put(key, Integer.parseInt(pro.getProperty(key)));
            }

            // get actual events
            String url = host + "/?command=listEvents&account=" + account + "&level=" + level
                    + "&domainid=1&pagesize=100";
            s_logger.info("Getting events with the following url " + url);
            HttpClient client = new HttpClient();
            HttpMethod method = new GetMethod(url);
            int responseCode = client.executeMethod(method);
            if (responseCode == 200) {
                InputStream is = method.getResponseBodyAsStream();
                ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is,
                        new String[] { "event" });

                for (int i = 0; i < eventValues.size(); i++) {
                    HashMap<String, String> element = eventValues.get(i);
                    if (element.get("level").equals(level)) {
                        if (actualEvents.containsKey(element.get("type")) == true) {
                            actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
                        } else {
                            actualEvents.put(element.get("type"), 1);
                        }
                    }
                }
            }
            method.releaseConnection();

            // compare actual events with expected events

            // compare expected result and actual result
            Iterator<?> iterator = expectedEvents.keySet().iterator();
            Integer expected;
            Integer actual;
            int fail = 0;
            while (iterator.hasNext()) {
                expected = null;
                actual = null;
                String type = iterator.next().toString();
                expected = expectedEvents.get(type);
                actual = actualEvents.get(type);
                if (actual == null) {
                    s_logger.error("Event of type " + type + " and level " + level
                            + " is missing in the listEvents response. Expected number of these events is "
                            + expected);
                    fail++;
                } else if (expected.compareTo(actual) != 0) {
                    fail++;
                    s_logger.info("Amount of events of  " + type + " type and level " + level
                            + " is incorrect. Expected number of these events is " + expected
                            + ", actual number is " + actual);
                }
            }
            if (fail == 0) {
                result = true;
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    } else {
        s_logger.info("File " + fileName + " not found");
    }
    return result;
}

From source file:org.protempa.LowLevelAbstractionDefinition.java

public final void setMinimumDuration(Integer minDuration) {
    if (minDuration == null || minDuration.compareTo(0) < 0) {
        this.minimumDuration = 0;
    } else {//w  w  w  .  j  av a 2  s .  co m
        this.minimumDuration = minDuration;
    }
}