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.kuali.kra.irb.personnel.ProtocolPersonnelServiceImpl.java

/**
 * @see org.kuali.kra.irb.personnel.ProtocolPersonnelService#isValidStudentFacultyMatch(java.util.List)
 */// w ww .  ja  v  a  2  s .  c  o m
public boolean isValidStudentFacultyMatch(List<ProtocolPerson> protocolPersons) {
    boolean validInvestigator = true;
    System.out.println("\n\n");
    HashMap<Integer, Integer> investigatorAffiliation = new HashMap<Integer, Integer>();
    for (ProtocolPerson protocolPerson : protocolPersons) {
        if (isAffiliationStudentInvestigatorOrFacultySupervisor(protocolPerson)) {
            updateAffiliationCount(protocolPerson, investigatorAffiliation);
        }
        System.out.println("protocolPerson, name = " + protocolPerson.getUserName() + ", is student inv = "
                + isAffiliationStudentInvestigatorOrFacultySupervisor(protocolPerson) + ", count = "
                + investigatorAffiliation.size());
    }
    Integer studentAffiliationCount = investigatorAffiliation.get(getStudentAffiliationType()) == null ? 0
            : investigatorAffiliation.get(getStudentAffiliationType());
    Integer facultySupervisorAffiliationCount = investigatorAffiliation
            .get(getFacultySupervisorAffiliationType()) == null ? 0
                    : investigatorAffiliation.get(getFacultySupervisorAffiliationType());
    if (studentAffiliationCount > 0
            && studentAffiliationCount.compareTo(facultySupervisorAffiliationCount) != 0) {
        validInvestigator = false;
    }
    System.out.println("\n\n");
    return validInvestigator;
}

From source file:org.kuali.kpme.tklm.time.timesheet.service.TimesheetServiceImpl.java

private Map<String, BigDecimal> getAssignmentHoursToFlsaWeekMap(TkTimeBlockAggregate tkTimeBlockAggregate,
        String principalId, String assignmentKey, LocalDate jobStartDate, DateTimeZone userTimeZone) {

    Map<String, BigDecimal> hoursToFlsaWeekMap = new LinkedHashMap<String, BigDecimal>();
    List<List<FlsaWeek>> flsaWeeks = tkTimeBlockAggregate.getFlsaWeeks(userTimeZone, principalId);

    int weekCount = 1;
    for (List<FlsaWeek> flsaWeekParts : flsaWeeks) {
        boolean printWeek = true;
        BigDecimal weekTotal = new BigDecimal(0.00);
        FlsaWeek lastWeekPart = CollectionUtils.isNotEmpty(flsaWeekParts)
                ? flsaWeekParts.get(flsaWeekParts.size() - 1)
                : null;//from  w  ww  .ja v  a  2 s . c o m
        for (FlsaWeek flsaWeekPart : flsaWeekParts) {

            //if flsa week doesn't end during this pay period do not validate.
            if (flsaWeekPart == lastWeekPart) {
                Integer lastFlsaDayOfWeek = flsaWeekPart.getFlsaDays()
                        .get(flsaWeekPart.getFlsaDays().size() - 1).getFlsaDate().getDayOfWeek();

                Integer flsaWeekEndDayOfWeek = TkConstants.FLSA_WEEK_END_DAY
                        .get(tkTimeBlockAggregate.getPayCalendar().getFlsaBeginDay());

                if (lastFlsaDayOfWeek.compareTo(flsaWeekEndDayOfWeek) != 0) {
                    printWeek = false;
                    weekCount++;
                    continue;
                }
            }

            //if flsa week starts before effective date of the job on the assignment do not validate.
            if (flsaWeekPart.getFlsaDays().get(0).getFlsaDate().toLocalDate().isBefore(jobStartDate)) {
                printWeek = false;
                weekCount++;
                continue;
            }

            for (FlsaDay flsaDay : flsaWeekPart.getFlsaDays()) {

                for (TimeBlock timeBlock : flsaDay.getAppliedTimeBlocks()) {
                    if (assignmentKey != null) {
                        if (timeBlock.getAssignmentKey().compareTo(assignmentKey) == 0) {
                            weekTotal = weekTotal.add(timeBlock.getHours(), HrConstants.MATH_CONTEXT);
                        } else {
                            weekTotal = weekTotal.add(new BigDecimal("0"), HrConstants.MATH_CONTEXT);
                        }
                    } else {
                        weekTotal = weekTotal.add(timeBlock.getHours(), HrConstants.MATH_CONTEXT);
                    }
                }
            }
        }

        if (printWeek) {
            hoursToFlsaWeekMap.put("Week " + weekCount++, weekTotal);
        }
    }

    return hoursToFlsaWeekMap;
}

From source file:com.espertech.esper.dataflow.core.DataFlowServiceImpl.java

private Set<Integer> analyzeBuildOrder(Map<Integer, OperatorDependencyEntry> operators)
        throws ExprValidationException {

    DependencyGraph graph = new DependencyGraph(operators.size(), true);
    for (Map.Entry<Integer, OperatorDependencyEntry> entry : operators.entrySet()) {
        int myOpNum = entry.getKey();
        Set<Integer> incomings = entry.getValue().getIncoming();
        for (int incoming : incomings) {
            graph.addDependency(myOpNum, incoming);
        }//from w  w  w .  j av  a 2 s .  c om
    }

    Set<Integer> topDownSet = new HashSet<Integer>();
    while (topDownSet.size() < operators.size()) {

        // seconardy sort according to the order of listing
        Set<Integer> rootNodes = new TreeSet<Integer>(new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return -1 * o1.compareTo(o2);
            }
        });
        rootNodes.addAll(graph.getRootNodes(topDownSet));

        if (rootNodes.isEmpty()) { // circular dependency could cause this
            for (int i = 0; i < operators.size(); i++) {
                if (!topDownSet.contains(i)) {
                    rootNodes.add(i);
                    break;
                }
            }
        }

        topDownSet.addAll(rootNodes);
    }

    return topDownSet;
}

From source file:com.puresoltechnologies.versioning.Version.java

private int comparePreReleaseInformation(Version o) {
    // We split the strings into identifiers
    String[] myIdentifiers = preReleaseInformation.split("\\.");
    String[] otherIdentifiers = o.preReleaseInformation.split("\\.");
    // Now we check each identifier position one after another...
    for (int i = 0; i < Math.min(myIdentifiers.length, otherIdentifiers.length); i++) {
        String my = myIdentifiers[i];
        String other = otherIdentifiers[i];
        Integer myDigits = convertToDigits(my);
        Integer otherDigits = convertToDigits(other);
        if (myDigits == null) {
            if (otherDigits != null) {
                return 1;
            } else {
                int result = my.compareTo(other);
                if (result != 0) {
                    return result;
                }/*  w w  w.  j a  va2  s .c  o m*/
            }
        } else {
            if (otherDigits == null) {
                return -1;
            } else {
                int result = myDigits.compareTo(otherDigits);
                if (result != 0) {
                    return result;
                }
            }
        }
    }
    // Everything is equal, now only the length of the identifiers can
    // decide...
    if (myIdentifiers.length == otherIdentifiers.length) {
        return 0;
    } else if (myIdentifiers.length > otherIdentifiers.length) {
        return 1;
    } else {
        return -1;
    }
}

From source file:edu.wustl.geneconnect.metadata.MetadataCalculator.java

/**
 * Writes "source, destination, linktype" information fo file
 *//*w ww.  j  ava2s . c  om*/
private void writeLinkTypes(String fileName) {
    // Link types between data source 
    try {
        FileWriter opFile = new FileWriter(new File(fileName));
        opFile.write("LOAD DATA INFILE * APPEND INTO TABLE DATASOURCE_LINKS FIELDS TERMINATED BY '"
                + FIELD_DELIMITER + "' " + " (SOURCE_DATASOURCE_ID, TARGET_DATASOURCE_ID, LINK_TYPE_ID)\n"
                + "BEGINDATA\n");

        for (int srcNodeID = 0; srcNodeID < m_numSources; ++srcNodeID) {
            Map destMap = (Map) m_linkTypeMap.get(new Integer(srcNodeID));
            Iterator mapIter = destMap.entrySet().iterator();
            for (Iterator iter = destMap.entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                String destID = new Integer(((Integer) (entry.getKey())).intValue()).toString();
                List linkTypeList = (List) entry.getValue();
                int size = linkTypeList.size();
                for (int k = 0; k < size; ++k) {
                    Integer link = (Integer) linkTypeList.get(k);
                    // write to file only if some kind of link exists between the 2 data sources
                    if ((link.compareTo(new Integer(0))) != 0) {
                        String linkType = link.toString();
                        String temp = (new Integer(srcNodeID).toString()) + FIELD_DELIMITER + destID
                                + FIELD_DELIMITER + linkType + "\n";
                        opFile.write(temp);
                        opFile.flush();
                    }
                }
            }
        }
        opFile.close();
    } catch (IOException e) {
        System.out.println("Failed to create an output file in current directory" + e.getMessage());
    }
}

From source file:org.opendatakit.common.persistence.engine.mysql.DatastoreImpl.java

/**
 * Relation manipulation APIs/*from ww  w .  ja va  2  s.co  m*/
 */
@Override
public void assertRelation(CommonFieldsBase relation, User user) throws ODKDatastoreException {
    try {
        LogFactory.getLog(DatastoreImpl.class).info("before updateRelation: " + relation.getTableName());
        // see if relation already is defined and update it with dimensions...
        if (updateRelation(relation, null)) {
            // it exists -- we're done!
            return;
        } else {
            // need to create the table...
            StringBuilder b = new StringBuilder();
            b.append(K_CREATE_TABLE);
            b.append(K_BQ);
            b.append(relation.getSchemaName());
            b.append(K_BQ);
            b.append(".");
            b.append(K_BQ);
            b.append(relation.getTableName());
            b.append(K_BQ);
            b.append(K_OPEN_PAREN);
            boolean firstTime = true;
            for (DataField f : relation.getFieldList()) {
                if (!firstTime) {
                    b.append(K_CS);
                }
                firstTime = false;
                b.append(K_BQ);
                b.append(f.getName());
                b.append(K_BQ);
                DataField.DataType type = f.getDataType();
                switch (type) {
                case BINARY:
                    b.append(" LONGBLOB");
                    break;
                case LONG_STRING:
                    b.append(" LONGTEXT CHARACTER SET utf8");
                    break;
                case STRING:
                    b.append(" VARCHAR(");
                    Long len = f.getMaxCharLen();
                    if (len == null) {
                        len = PersistConsts.DEFAULT_MAX_STRING_LENGTH;
                    }
                    b.append(len.toString());
                    b.append(K_CLOSE_PAREN);
                    b.append(" CHARACTER SET utf8");
                    break;
                case BOOLEAN:
                    b.append(" CHAR(1) CHARACTER SET utf8");
                    break;
                case INTEGER:
                    Integer int_digits = f.getNumericPrecision();
                    if (int_digits == null) {
                        int_digits = DEFAULT_INT_NUMERIC_PRECISION;
                    }

                    if (int_digits.compareTo(10) > 0) {
                        b.append(" BIGINT(");
                        b.append(int_digits.toString());
                        b.append(K_CLOSE_PAREN);
                    } else {
                        b.append(" INTEGER(");
                        b.append(int_digits.toString());
                        b.append(K_CLOSE_PAREN);
                    }
                    break;
                case DECIMAL:
                    Integer dbl_digits = f.getNumericPrecision();
                    Integer dbl_fract = f.getNumericScale();
                    if (dbl_digits == null) {
                        dbl_digits = DEFAULT_DBL_NUMERIC_PRECISION;
                    }
                    if (dbl_fract == null) {
                        dbl_fract = DEFAULT_DBL_NUMERIC_SCALE;
                    }
                    b.append(" DECIMAL(");
                    b.append(dbl_digits.toString());
                    b.append(K_CS);
                    b.append(dbl_fract.toString());
                    b.append(K_CLOSE_PAREN);
                    break;
                case DATETIME:
                    b.append(" DATETIME");
                    break;
                case URI:
                    b.append(" VARCHAR(");
                    len = f.getMaxCharLen();
                    if (len == null) {
                        len = PersistConsts.URI_STRING_LEN;
                    }
                    b.append(len.toString());
                    b.append(") CHARACTER SET utf8");
                    break;
                }

                if (f.getNullable()) {
                    b.append(" NULL ");
                } else {
                    b.append(" NOT NULL ");
                }
            }
            /*
             * Setting the primary key as the _URI and making it use
             * HASH.
             */

            // For MySQL, it is important to NOT declare a PRIMARY KEY
            // when that key is a UUID. It should only be declared as 
            // a non-unique index...
            //
            // http://kccoder.com/mysql/uuid-vs-int-insert-performance/
            //
            b.append(", INDEX(");
            b.append(K_BQ);
            b.append(relation.primaryKey.getName());
            b.append(K_BQ);
            b.append(K_CLOSE_PAREN);
            b.append(K_USING_HASH);
            // create other indicies
            for (DataField f : relation.getFieldList()) {
                if ((f.getIndexable() != IndexType.NONE) && (f != relation.primaryKey)) {
                    b.append(", INDEX(");
                    b.append(K_BQ);
                    b.append(f.getName());
                    b.append(K_BQ);
                    b.append(K_CLOSE_PAREN);
                    if (f.getIndexable() == IndexType.HASH) {
                        b.append(K_USING_HASH);
                    }
                }
            }
            b.append(K_CLOSE_PAREN);

            String createTableStmt = b.toString();
            LogFactory.getLog(DatastoreImpl.class).info("Attempting: " + createTableStmt);
            getJdbcConnection().execute(createTableStmt);
            LogFactory.getLog(DatastoreImpl.class)
                    .info("create table success (before updateRelation): " + relation.getTableName());

            // and update the relation with actual dimensions...
            updateRelation(relation, createTableStmt);
        }
    } catch (Exception e) {
        LogFactory.getLog(DatastoreImpl.class)
                .warn("Failure: " + relation.getTableName() + " exception: " + e.toString());
        throw new ODKDatastoreException(e);
    }
}

From source file:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java

/**
 * Method to check if value coordinates passed are valid with respect to column coordinates.
 * // ww w  . j a  v a2 s.c  o  m
 * @param valueX0 {@link Integer}
 * @param valueX1 {@link Integer}
 * @param columnX0 {@link Integer}
 * @param columnX1 {@link Integer}
 * @return boolean
 */
public static boolean isColumnValidWithColCoord(final Integer valueX0, final Integer valueX1,
        final Integer columnX0, final Integer columnX1) {
    LOGGER.info("Entering method isColumnValidWithColCoord.....");
    boolean isValid = false;
    LOGGER.debug("Column Coordinates: X0=", valueX0, " ,X1=", valueX1);
    LOGGER.debug("Value Coordinates: X0=", columnX0, " ,X1=", columnX1);
    if (valueX0 != null && valueX1 != null && columnX0 != null && columnX0 != null
            && (columnX0 != 0 || columnX1 != 0)) {
        if ((valueX0.compareTo(columnX0) == 1 && valueX0.compareTo(columnX1) == -1)
                || (valueX1.compareTo(columnX0) == 1 && valueX1.compareTo(columnX1) == -1)
                || (valueX0.compareTo(columnX0) == -1 && valueX1.compareTo(columnX1) == 1)
                || valueX0.compareTo(columnX0) == 0 || valueX1.compareTo(columnX1) == 0) {
            isValid = true;
        }
    }
    LOGGER.info("Is value coordinates valid with column coordinates : ", isValid);
    LOGGER.info("Exiting method isColumnValidWithColCoord.....");
    return isValid;
}

From source file:org.deidentifier.arx.aggregates.StatisticsBuilder.java

/**
 * Orders the given array by the given sort order.
 *
 * @param array/* w w  w .  j  a  v a  2s .  c  o m*/
 * @param order
 */
private void sort(final String[] array, final Map<String, Integer> order) {
    GenericSorting.mergeSort(0, array.length, new IntComparator() {
        @Override
        public int compare(int arg0, int arg1) {
            checkInterrupt();
            Integer order1 = order.get(array[arg0]);
            Integer order2 = order.get(array[arg1]);
            if (order1 == null || order2 == null) {
                throw new RuntimeException("The hierarchy seems to not cover all data values");
            } else {
                return order1.compareTo(order2);
            }
        }
    }, new Swapper() {
        @Override
        public void swap(int arg0, int arg1) {
            String temp = array[arg0];
            array[arg0] = array[arg1];
            array[arg1] = temp;
        }
    });
}

From source file:com.googlecode.jsfFlex.component.ext.AbstractFlexUIDataGrid.java

public Map<String, ? super Object> removeDataEntry() {

    final Comparator<? super String> DELETE_INDICES_COMPARATOR = new Comparator<String>() {

        public int compare(String firstInstance, String secondInstance) {
            Integer firstCompare = Integer.valueOf(firstInstance);
            Integer secondCompare = Integer.valueOf(secondInstance);
            return firstCompare.compareTo(secondCompare);
        }//  w  ww  .  j a  v  a  2 s.co m
    };

    Map<String, ? super Object> removeDataResult = new HashMap<String, Object>();
    boolean success = true;

    FacesContext context = FacesContext.getCurrentInstance();
    Map<String, String[]> requestParameterValuesMap = context.getExternalContext()
            .getRequestParameterValuesMap();
    String[] deleteIndices = requestParameterValuesMap.get(DELETE_INDICES_KEY);
    List<String> deleteIndicesList = Arrays.asList(deleteIndices);
    Collections.sort(deleteIndicesList, DELETE_INDICES_COMPARATOR);
    Collections.reverse(deleteIndicesList);
    StringBuilder deleteIndicesLog = new StringBuilder("[");
    for (String deleteIndex : deleteIndicesList) {
        deleteIndicesLog.append(deleteIndex);
        deleteIndicesLog.append(", ");
    }
    deleteIndicesLog.append("]");
    _log.info("Requested deleteIndices are : " + deleteIndices + " for component : " + getId());

    synchronized (this) {

        for (String currDeleteIndex : deleteIndicesList) {
            int parsedDeleteIndex = -1;

            try {
                parsedDeleteIndex = Integer.parseInt(currDeleteIndex);
            } catch (NumberFormatException parsingException) {
                _log.error("Error parsing of " + currDeleteIndex + " to an int", parsingException);
                success = false;
                break;
            }

            Object removeEntry = null;
            if (isFiltered()) {
                /*
                 * Need to remove from _filteredList, _wrappedList, and getBindingBeanList()
                 */
                WrappedBeanEntry filterEntry = _filteredList.remove(parsedDeleteIndex);

                /*
                 * Below two are costly operations, try to improve
                 */
                _wrappedList.remove(filterEntry);
                removeEntry = filterEntry.getBeanEntry();
            } else {

                removeEntry = _wrappedList.remove(parsedDeleteIndex).getBeanEntry();
            }

            getBindingBeanList().remove(removeEntry);
            _log.debug("Have removed element at : " + currDeleteIndex + " for component : " + getId());
        }

    }

    Integer batchColumnDataRetrievalSize = computeBatchColumnDataRetrievalSize();
    Integer maxDataPartitionIndex = computeMaxDataPartitionIndex();

    deselectAll();

    removeDataResult.put(BATCH_COLUMN_DATA_RETRIEVAL_SIZE_KEY, batchColumnDataRetrievalSize);
    removeDataResult.put(MAX_DATA_PARTITION_INDEX_KEY, maxDataPartitionIndex);
    removeDataResult.put(AbstractEvent.ASYNCHRONOUS_VARIABLES.RESULT_CODE.toString(), Boolean.valueOf(success));
    return removeDataResult;
}

From source file:org.sakaiproject.tool.assessment.ui.bean.author.ItemAuthorBean.java

/**
 * delete specified Item//from ww  w.j a va 2s  .co  m
 */
public String deleteItem() {
    ItemService delegate = new ItemService();
    Long deleteId = this.getItemToDelete().getItemId();
    ItemFacade itemf = delegate.getItem(deleteId, AgentFacade.getAgentString());
    // save the currSection before itemf.setSection(null), used to reorder question sequences
    SectionFacade currSection = (SectionFacade) itemf.getSection();
    Integer currSeq = itemf.getSequence();

    QuestionPoolService qpdelegate = new QuestionPoolService();
    if (qpdelegate.getPoolIdsByItem(deleteId.toString()) == null
            || qpdelegate.getPoolIdsByItem(deleteId.toString()).isEmpty()) {
        // if no reference to this item at all, ie, this item is created in assessment but not assigned to any pool

        AuthorizationBean authzBean = (AuthorizationBean) ContextUtil.lookupBean("authorization");
        AssessmentService assessdelegate = new AssessmentService();
        AssessmentFacade af = assessdelegate
                .getBasicInfoOfAnAssessmentFromSectionId(currSection.getSectionId());
        if (!authzBean.isUserAllowedToEditAssessment(af.getAssessmentBaseId().toString(), af.getCreatedBy(),
                false)) {
            throw new IllegalArgumentException(
                    "User does not have permission to delete item in assessment: " + af.getAssessmentBaseId());
        }

        delegate.deleteItem(deleteId, AgentFacade.getAgentString());
    } else {
        if (currSection == null) {
            // if this item is created from question pool
            QuestionPoolBean qpoolbean = (QuestionPoolBean) ContextUtil.lookupBean("questionpool");
            ItemFacade itemfacade = delegate.getItem(deleteId, AgentFacade.getAgentString());
            ArrayList items = new ArrayList();
            items.add(itemfacade);
            qpoolbean.setItemsToDelete(items);
            qpoolbean.removeQuestionsFromPool();
            return "editPool";
        } else {
            // 
            // if some pools still reference to this item, ie, this item is 
            // created in assessment but also assigned a a pool
            // then just set section = null
            itemf.setSection(null);
            delegate.saveItem(itemf);
        }
    }
    //An item has been deleted
    EventTrackingService.post(EventTrackingService.newEvent("sam.assessment.item.delete",
            "/sam/" + AgentFacade.getCurrentSiteId() + "/removed itemId=" + deleteId, true));

    AssessmentService assessdelegate = new AssessmentService();
    // reorder item numbers

    SectionFacade sectfacade = assessdelegate.getSection(currSection.getSectionId().toString());
    Set itemset = sectfacade.getItemFacadeSet();
    // should be size-1 now.
    Iterator iter = itemset.iterator();
    while (iter.hasNext()) {
        ItemFacade itemfacade = (ItemFacade) iter.next();
        Integer itemfacadeseq = itemfacade.getSequence();
        if (itemfacadeseq.compareTo(currSeq) > 0) {
            itemfacade.setSequence(Integer.valueOf(itemfacadeseq.intValue() - 1));
            delegate.saveItem(itemfacade);
        }
    }

    //  go to editAssessment.jsp, need to first reset assessmentBean
    AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean");
    AssessmentFacade assessment = assessdelegate.getAssessment(assessmentBean.getAssessmentId());
    assessmentBean.setAssessment(assessment);
    assessdelegate.updateAssessmentLastModifiedInfo(assessment);
    //Assessment has been revised
    EventTrackingService.post(EventTrackingService.newEvent("sam.asessment.revise",
            "/sam/" + AgentFacade.getCurrentSiteId() + "/removed itemId=" + deleteId + "from assessmentId="
                    + assessmentBean.getAssessmentId(),
            true));
    return "editAssessment";
}