Example usage for java.lang Long compareTo

List of usage examples for java.lang Long compareTo

Introduction

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

Prototype

public int compareTo(Long anotherLong) 

Source Link

Document

Compares two Long objects numerically.

Usage

From source file:org.apache.hadoop.hbase.regionserver.HRegionServer.java

/**
 * @return A new Map of online regions sorted by region size with the first entry being the
 * biggest.  If two regions are the same size, then the last one found wins; i.e. this method
 * may NOT return all regions./*from  w w  w .j  ava  2s. com*/
 */
SortedMap<Long, HRegion> getCopyOfOnlineRegionsSortedBySize() {
    // we'll sort the regions in reverse
    SortedMap<Long, HRegion> sortedRegions = new TreeMap<Long, HRegion>(new Comparator<Long>() {
        @Override
        public int compare(Long a, Long b) {
            return -1 * a.compareTo(b);
        }
    });
    // Copy over all regions. Regions are sorted by size with biggest first.
    for (HRegion region : this.onlineRegions.values()) {
        sortedRegions.put(region.memstoreSize.get(), region);
    }
    return sortedRegions;
}

From source file:com.cloud.user.AccountManagerImpl.java

@Override
public Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId) {
    // We just care for resource domain admin for now. He should be permitted to see only his zone.
    if (isResourceDomainAdmin(caller.getType())) {
        if (zoneId == null)
            return getZoneIdForAccount(caller);
        else if (zoneId.compareTo(getZoneIdForAccount(caller)) != 0)
            throw new PermissionDeniedException(
                    "Caller " + caller + "is not allowed to access the zone " + zoneId);
        else//from   w w w. j av  a2s  .  c  o  m
            return zoneId;
    }

    else
        return zoneId;
}

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

private Comparator<MetricValue> getTimestampComparator() {
    return new Comparator<MetricValue>() {
        public int compare(MetricValue arg0, MetricValue arg1) {
            Long point0 = arg0.getTimestamp();
            Long point1 = arg1.getTimestamp();
            return point0.compareTo(point1);
        }/*from w ww  .j  a  v  a2s .c  o m*/
    };
}

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

protected String[] getUpdateLockSQL(Node n1, Node n2) {
    Node[] nodes = null;/* w  w w.ja  v  a 2 s.c  o m*/
    Long id1 = getNodeID(n1);
    Long id2 = null;
    if (n2 != null)
        id2 = getNodeID(n2);

    if (n2 == null || id1.compareTo(id2) == 0) // same node
        nodes = new Node[] { n1 };
    else if (id1.compareTo(id2) < 0)
        nodes = new Node[] { n1, n2 };
    else
        nodes = new Node[] { n2, n1 };

    String[] ret = new String[nodes.length];
    for (int i = 0; i < nodes.length; i++) {
        ret[i] = getUpdateLockSQL(nodes[i]);
    }
    return ret;
}

From source file:edu.northwestern.jcr.adapter.xtf.query.SearchIndex.java

/**
 * Sorts the query results based on the value of the properties.
 * The ORDER BY clause is actually handled here.
 *
 * @param lines array of comma-separated full paths to the query results
 * @param valueMap maps pid to comma-separated values
 * @param orderSpecs true for ascending, false for descending
 * @return array of sorted results/*from   ww  w .j  av  a2s. c  o m*/
 */
private String[] sort(String[] lines, final Map<String, String> valueMap, final boolean[] orderSpecs) {

    Comparator<String> result_order = new Comparator<String>() {
        public int compare(String line1, String line2) {
            String pid1, pid2;
            String valueList1, valueList2;
            String[] parts;
            String[] valueString1, valueString2;
            String value1, value2;
            Double double1, double2;
            Long long1, long2;
            Calendar calendar1, calendar2;
            Boolean boolean1, boolean2;
            int i;
            int compare = 0;

            // get pid of the last object in the list
            parts = line1.split(",");
            pid1 = parts[parts.length - 1];
            parts = line2.split(",");
            pid2 = parts[parts.length - 1];

            // get comma-separated the value list
            valueList1 = valueMap.get(pid1);
            valueList2 = valueMap.get(pid2);

            valueString1 = valueList1.split(",");
            valueString2 = valueList2.split(",");

            for (i = 0; i < valueString1.length; ++i) {
                // loop over the values
                value1 = valueString1[i];
                parts = value1.split("%57");
                value1 = parts[parts.length - 1];

                value2 = valueString2[i];
                parts = value2.split("%57");
                value2 = parts[parts.length - 1];

                switch (Integer.parseInt(parts[0])) {
                case PropertyType.STRING:
                    if (orderSpecs[i]) {
                        compare = value1.compareTo(value2);
                    } else {
                        compare = value2.compareTo(value1);
                    }
                    break;
                case PropertyType.DOUBLE:
                    double1 = Double.parseDouble(value1);
                    double2 = Double.parseDouble(value2);
                    if (orderSpecs[i]) {
                        compare = double1.compareTo(double2);
                    } else {
                        compare = double2.compareTo(double1);
                    }
                    break;
                case PropertyType.LONG:
                    long1 = Long.parseLong(value1);
                    long2 = Long.parseLong(value2);
                    if (orderSpecs[i]) {
                        compare = long1.compareTo(long2);
                    } else {
                        compare = long2.compareTo(long1);
                    }
                    break;
                case PropertyType.DATE:
                    calendar1 = ISO8601.parse(value1);
                    calendar2 = ISO8601.parse(value2);
                    if (orderSpecs[i]) {
                        compare = calendar1.compareTo(calendar2);
                    } else {
                        compare = calendar2.compareTo(calendar1);
                    }
                    break;
                case PropertyType.BOOLEAN:
                    boolean1 = Boolean.valueOf(value1);
                    boolean2 = Boolean.valueOf(value2);
                    if (orderSpecs[i]) {
                        compare = boolean1.compareTo(boolean2);
                    } else {
                        compare = boolean2.compareTo(boolean1);
                    }
                    break;
                // not supported
                case PropertyType.BINARY:
                case PropertyType.REFERENCE:
                case PropertyType.NAME:
                case PropertyType.PATH:
                    compare = 0;
                }

                if (compare != 0) {
                    return compare;
                }

                // more comparison
            }

            return compare;
        }
    };

    List<String> resultList = Arrays.asList(lines);
    Collections.sort(resultList, result_order);
    return resultList.toArray(new String[0]);
}

From source file:org.apache.cocoon.acting.AbstractValidatorAction.java

/**
 * Validates nullability and default value for given parameter. If given
 * constraints are not null they are validated as well.
 *//*from w  w  w .  j a  va 2s  .  c  o m*/
private ValidatorActionHelper validateLong(String name, Configuration constraints, Configuration conf,
        Map params, boolean is_string, Object param) {

    boolean nullable = getNullable(conf, constraints);
    Long value = null;
    Long dflt = getLongValue(getDefault(conf, constraints), true);

    if (getLogger().isDebugEnabled())
        getLogger().debug("Validating long parameter " + name + " (encoded in a string: " + is_string + ")");
    try {
        value = getLongValue(param, is_string);
    } catch (Exception e) {
        // Unable to parse long
        return new ValidatorActionHelper(value, ValidatorActionResult.ERROR);
    }
    if (value == null) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Long parameter " + name + " is null");
        if (!nullable) {
            return new ValidatorActionHelper(value, ValidatorActionResult.ISNULL);
        } else {
            return new ValidatorActionHelper(dflt);
        }
    }
    if (constraints != null) {
        Long eq = getAttributeAsLong(constraints, "equals-to", null);
        String eqp = constraints.getAttribute("equals-to-param", "");

        Long min = getAttributeAsLong(conf, "min", null);
        min = getAttributeAsLong(constraints, "min", min);

        Long max = getAttributeAsLong(conf, "max", null);
        max = getAttributeAsLong(constraints, "max", max);

        // Validate whether param is equal to constant
        if (eq != null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Long parameter " + name + " should be equal to " + eq);

            if (!value.equals(eq)) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("and it is not");
                return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH);
            }
        }

        // Validate whether param is equal to another param
        // FIXME: take default value of param being compared with into
        // account?
        if (!"".equals(eqp)) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Long parameter " + name + " should be equal to " + params.get(eqp));
            // Request parameter is stored as string.
            // Need to convert it beforehand.
            try {
                Long _eqp = new Long(Long.parseLong((String) params.get(eqp)));
                if (!value.equals(_eqp)) {
                    if (getLogger().isDebugEnabled())
                        getLogger().debug("and it is not");
                    return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH);
                }
            } catch (NumberFormatException nfe) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("Long parameter " + name + ": " + eqp + " is no long", nfe);
                return new ValidatorActionHelper(value, ValidatorActionResult.NOMATCH);
            }
        }

        // Validate wheter param is at least min
        if (min != null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Long parameter " + name + " should be at least " + min);

            if (min.compareTo(value) > 0) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("and it is not");
                return new ValidatorActionHelper(value, ValidatorActionResult.TOOSMALL);
            }
        }

        // Validate wheter param is at most max
        if (max != null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Long parameter " + name + " should be at most " + max);
            if (max.compareTo(value) < 0) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("and it is not");
                return new ValidatorActionHelper(value, ValidatorActionResult.TOOLARGE);
            }
        }
    }
    return new ValidatorActionHelper(value);
}

From source file:org.kuali.kpme.tklm.time.detail.validation.TimeDetailValidationUtil.java

public static List<String> validateTimeEntryDetails(BigDecimal hours, BigDecimal amount, String startTimeS,
        String endTimeS, String startDateS, String endDateS, TimesheetDocument timesheetDocument,
        String selectedEarnCode, String selectedAssignment, boolean acrossDays, String timeblockId,
        String overtimePref) {//from  w w w . j  a va 2s.  c om
    List<String> errors = new ArrayList<String>();
    LocalDate savedStartDate = TKUtils.formatDateString(startDateS);
    LocalDate savedEndDate = TKUtils.formatDateString(endDateS);

    if (timesheetDocument == null) {
        errors.add("No timesheet document found.");
    }
    if (errors.size() > 0)
        return errors;

    CalendarEntry payCalEntry = timesheetDocument.getCalendarEntry();
    EarnCode earnCode = null;
    if (StringUtils.isNotBlank(selectedEarnCode)) {
        earnCode = HrServiceLocator.getEarnCodeService().getEarnCode(selectedEarnCode,
                TKUtils.formatDateTimeStringNoTimezone(endDateS).toLocalDate());
    }
    boolean isTimeRecordMethod = earnCode != null
            && StringUtils.equalsIgnoreCase(earnCode.getRecordMethod(), HrConstants.EARN_CODE_TIME);

    errors.addAll(CalendarValidationUtil.validateDates(startDateS, endDateS));

    if (isTimeRecordMethod) {
        errors.addAll(CalendarValidationUtil.validateTimes(startTimeS, endTimeS));
    }
    if (errors.size() > 0)
        return errors;

    Long startTime;
    Long endTime;

    if (!isTimeRecordMethod) {
        startTimeS = "0:0";
        endTimeS = "0:0";
    }

    if (acrossDays && !endTimeS.equals("0:00")) {
        endDateS = startDateS;
    }

    startTime = TKUtils.convertDateStringToDateTimeWithoutZone(startDateS, startTimeS).getMillis();
    endTime = TKUtils.convertDateStringToDateTimeWithoutZone(endDateS, endTimeS).getMillis();

    errors.addAll(CalendarValidationUtil.validateInterval(payCalEntry, startTime, endTime));
    if (errors.size() > 0)
        return errors;

    if (isTimeRecordMethod) {
        if (startTimeS == null)
            errors.add("The start time is blank.");
        if (endTimeS == null)
            errors.add("The end time is blank.");
        if (startTime - endTime == 0)
            errors.add("Start time and end time cannot be equivalent");
    }
    if (errors.size() > 0)
        return errors;

    DateTime startTemp = new DateTime(startTime);
    DateTime endTemp = new DateTime(endTime);
    /*
     * KPME-2687:
     *
     * Removed 24 hour limitation. System creates continuous sequence of time blocks when !accrossDays,
     * hours between startTemp and endTemp may be over 24 hours.
     *
            if (errors.size() == 0 && !acrossDays && !StringUtils.equals(TkConstants.EARN_CODE_CPE, overtimePref)) {
    Hours hrs = Hours.hoursBetween(startTemp, endTemp);
    if (hrs.getHours() > 24) errors.add("One timeblock cannot exceed 24 hours");
            }
            if (errors.size() > 0) return errors;
            
     */

    //Check that assignment is valid within the timeblock span. 
    AssignmentDescriptionKey assignKey = HrServiceLocator.getAssignmentService()
            .getAssignmentDescriptionKey(selectedAssignment);
    Assignment assign = HrServiceLocator.getAssignmentService().getAssignmentForTargetPrincipal(assignKey,
            startTemp.toLocalDate());
    if (assign == null)
        errors.add("Assignment is not valid for start date " + TKUtils.formatDate(new LocalDate(startTime)));
    assign = HrServiceLocator.getAssignmentService().getAssignmentForTargetPrincipal(assignKey,
            endTemp.toLocalDate());
    if (assign == null)
        errors.add("Assignment is not valid for end date " + TKUtils.formatDate(new LocalDate(endTime)));
    if (errors.size() > 0)
        return errors;

    //------------------------
    // some of the simple validations are in the js side in order to reduce the server calls
    // 1. check if the begin / end time is empty - tk.calenadr.js
    // 2. check the time format - timeparse.js
    // 3. only allows decimals to be entered in the hour field
    //------------------------

    //------------------------
    // check if the overnight shift is across days
    //------------------------
    if (acrossDays && hours == null && amount == null) {
        if (savedEndDate.isAfter(savedStartDate) && startTemp.getHourOfDay() > endTemp.getHourOfDay()
                && !(endTemp.getDayOfYear() - startTemp.getDayOfYear() <= 1 && endTemp.getHourOfDay() == 0)) {
            errors.add("The \"apply to each day\" box should not be checked.");
        }
    }
    if (errors.size() > 0)
        return errors;

    //------------------------
    // check if the begin / end time are valid
    //------------------------
    if ((startTime.compareTo(endTime) > 0 || endTime.compareTo(startTime) < 0)) {
        errors.add("The time or date is not valid.");
    }
    if (errors.size() > 0)
        return errors;

    // KPME-1446 
    // -------------------------------
    // check if there is a weekend day when the include weekends flag is checked
    //--------------------------------

    //------------------------
    // Amount cannot be zero
    //------------------------
    if (amount != null && earnCode != null
            && StringUtils.equals(earnCode.getEarnCodeType(), HrConstants.EARN_CODE_AMOUNT)) {
        if (amount.equals(BigDecimal.ZERO)) {
            errors.add("Amount cannot be zero.");
        }
        if (amount.scale() > 2) {
            errors.add("Amount cannot have more than two digits after decimal point.");
        }
    }
    if (errors.size() > 0)
        return errors;

    //------------------------
    // check if the hours entered for hourly earn code is greater than 24 hours per day
    // Hours cannot be zero
    //------------------------
    if (hours != null && earnCode != null
            && StringUtils.equals(earnCode.getEarnCodeType(), HrConstants.EARN_CODE_HOUR)) {
        if (hours.equals(BigDecimal.ZERO)) {
            errors.add("Hours cannot be zero.");
        }
        if (hours.scale() > 2) {
            errors.add("Hours cannot have more than two digits after decimal point.");
        }
        /*
         * KPME-2671:
         * 
         * Replacing this conditional with the one below. Shouldn't matter if the date range spans more than one day,
         * hours shouldn't exceed 24.
         * 
         *          int dayDiff = endTemp.getDayOfYear() - startTemp.getDayOfYear() + 1;
                    if (hours.compareTo(new BigDecimal(dayDiff * 24)) == 1) {
        errors.add("Cannot enter more than 24 hours per day.");
                    }
         */
    }
    if (errors.size() > 0)
        return errors;

    /**
     * KPME-2671:
     * 
     * Generalize 24 limit to hour field on time entry form.
     * 
     */
    if (hours != null && hours.compareTo(new BigDecimal(24.0)) > 0) {
        errors.add("Hours cannot exceed 24.");
    }
    //------------------------
    // check if time blocks overlap with each other. Note that the tkTimeBlockId is used to
    // determine is it's updating an existing time block or adding a new one
    //------------------------

    boolean isRegularEarnCode = StringUtils.equals(assign.getJob().getPayTypeObj().getRegEarnCode(),
            selectedEarnCode);
    startTime = TKUtils.convertDateStringToDateTime(startDateS, startTimeS).getMillis();
    endTime = TKUtils.convertDateStringToDateTime(endDateS, endTimeS).getMillis();

    errors.addAll(validateOverlap(startTime, endTime, acrossDays, startDateS, endTimeS, startTemp, endTemp,
            timesheetDocument, timeblockId, isRegularEarnCode, selectedEarnCode));
    if (errors.size() > 0)
        return errors;

    // Accrual Hour Limits Validation
    //errors.addAll(TkServiceLocator.getTimeOffAccrualService().validateAccrualHoursLimitByEarnCode(timesheetDocument, selectedEarnCode));

    return errors;
}

From source file:edu.harvard.iq.dvn.core.index.IndexServiceBean.java

public void updateStudiesInCollections() {
    long ioProblemCount = 0;
    boolean ioProblem = false;
    Indexer indexer = Indexer.getInstance();

    String dvnIndexLocation = System.getProperty("dvn.index.location");

    String lockFileName = dvnIndexLocation + "/IndexAll.lock";
    File indexAllLockFile = new File(lockFileName);

    // Before we do anything else, check if the index directory is
    // locked for IndexAll: 

    if (indexAllLockFile.exists()) {
        logger.info("Detected IndexAll in progress; skipping reindexing ofn collection-linked studies.");
        return;//w  ww .  j ava 2  s . c  o m
    }

    logger.info("Starting batch reindex of collection-linked studies.");

    lockFileName = dvnIndexLocation + "/collReindex.lock";
    File collReindexLockFile = new File(lockFileName);

    try {
        // Check for an existing lock file: 

        if (collReindexLockFile.exists()) {
            String errorMessage = "Cannot reindex: collection reindexing already in progress;";
            errorMessage += ("lock file " + lockFileName + ", created on "
                    + (new Date(collReindexLockFile.lastModified())).toString() + ".");
            throw new IOException(errorMessage);
        }

        // Create a lock file: 
        try {
            collReindexLockFile.createNewFile();
        } catch (IOException ex) {
            String errorMessage = "Error: could not create lock file (";
            errorMessage += (lockFileName + ")");
            throw new IOException(errorMessage);
        }

        List<Long> vdcIdList = vdcService.findAllIds();
        logger.fine("Found " + vdcIdList.size() + " dataverses.");

        Long maxStudyId = studyService.getMaxStudyTableId();

        if (maxStudyId == null) {
            logger.fine("The database appears to be empty. Exiting.");
            return;
        }

        if (maxStudyId.intValue() != maxStudyId.longValue()) {
            logger.severe(
                    "There appears to be more than 2^^31 objects in the study table; the subnetwork cross-indexing hack isn't going to work.");
            throw new IOException(
                    "There appears to be more than 2^^31 objects in the study table; the subnetwork cross-indexing hack isn't going to work.");
            /* This is quite unlikely to happen, but still... */
        }

        ArrayList<VDCNetwork> subNetworks = getSubNetworksAsArray(); //vdcNetworkService.getVDCSubNetworks();
        // This is an array of [sub]networks organized by *network id*; 
        // i.e., if there are subnetworks with the ids 0, 2 and 5 the array 
        // will contain {0, NULL, network_2, NULL, NULL, network_5}

        if (subNetworks == null || (subNetworks.size() < 1)) {
            // No subnetworks in this DV Network; nothing to do. 
            logger.fine("There's only one network in the DVN; nothing to do. Exiting");
            return;
        }

        int maxSubnetworkId = subNetworks.size() - 1;

        if (maxSubnetworkId > 63) {
            logger.severe(
                    "There are more than 63 VDC (sub)networks. The subnetwork cross-indexing hack isn't going to work."
                            + "(we are using longs as bitstrings to store network cross-linked status of a study)");
            throw new IOException(
                    "There are more than 63 VDC (sub)networks. The subnetwork cross-indexing hack isn't going to work."
                            + "(we are using longs as bitstrings to store network cross-linked status of a study)");
            /* Not very likely to happen either... */
        }

        long linkedVdcNetworkMap[] = new long[maxStudyId.intValue() + 1];
        Long vdcId = null;
        VDC vdc = null;
        List<Long> linkedStudyIds = null;
        Long vdcNetworkId = null;
        Long studyNetworkId = null;
        Study linkedStudy = null;

        for (Iterator it = vdcIdList.iterator(); it.hasNext();) {
            vdcId = (Long) it.next();
            vdc = vdcService.findById(vdcId);

            if (vdc != null && vdc.getVdcNetwork() != null) {
                vdcNetworkId = vdc.getVdcNetwork().getId();

                if (vdcNetworkId.longValue() > 0) {
                    // We are not interested in the VDCs in the top-level
                    // network (network id 0); because the top-level network
                    // already contains all the studies in it. Whatever 
                    // studies the dynamic collections may be linking, they 
                    // are still in the same DVN. 
                    linkedStudyIds = indexer.findStudiesInCollections(vdc);

                    if (linkedStudyIds != null) {
                        logger.fine("Found " + linkedStudyIds.size() + " linked studies in VDC " + vdc.getId()
                                + ", subnetwork " + vdcNetworkId.toString());

                        for (Long studyId : linkedStudyIds) {
                            if (studyId.longValue() <= maxStudyId.longValue()) {
                                // otherwise this is a new study, created since we 
                                // have started this process; we'll be skipping it,
                                // this time around. 
                                try {
                                    linkedStudy = studyService.getStudy(studyId);
                                } catch (Exception ex) {
                                    linkedStudy = null;
                                }

                                if (linkedStudy != null) {
                                    studyNetworkId = linkedStudy.getOwner().getVdcNetwork().getId();
                                    if ((studyNetworkId != null)
                                            && (vdcNetworkId.compareTo(studyNetworkId) != 0)) {
                                        // this study is cross-linked from another VDC network!
                                        logger.fine("Study " + linkedStudy.getId() + " from subnetwork "
                                                + studyNetworkId + " is linked to this VDC (" + vdc.getId()
                                                + ").");

                                        linkedVdcNetworkMap[linkedStudy.getId()
                                                .intValue()] |= (1 << vdcNetworkId.intValue());
                                    }
                                }
                                linkedStudy = null;
                                studyNetworkId = null;
                            }
                        }
                    }
                    linkedStudyIds = null;
                    vdcNetworkId = null;
                }
            }
            vdcId = null;
            vdc = null;
        }

        // Now go through the list of studies and reindex those for which 
        // the cross-linked status has changed:

        logger.fine("Checking the cross-linking status and reindexing the studies for which it has changed:");

        List<Long> linkedToNetworkIds = null;
        boolean reindexNecessary = false;

        // Check for the studies that are no longer linked to any foreign
        // subnetworks: 

        List<Long> existingLinkedStudies = studyService.getAllLinkedStudyIds();

        Long sid = null;
        for (Iterator it = existingLinkedStudies.iterator(); it.hasNext();) {
            sid = (Long) it.next();
            if (linkedVdcNetworkMap[sid.intValue()] == 0) {
                // study no longer linked to any subnetworks
                linkedVdcNetworkMap[sid.intValue()] = -1;
            }
        }
        // TODO: would be faster still to retrieve the entire map of crosslinks
        // from the db in a single query here, cook another array of bitstrings
        // and then just go and compare the 2, without making any further 
        // queries... --L.A.

        List<VDCNetwork> currentCrossLinks = null;

        for (int i = 0; i < maxStudyId.intValue() + 1; i++) {
            if (linkedVdcNetworkMap[i] != 0) {
                logger.fine("study " + i
                        + ": cross-linked outside of its network; (still need to check if we need to reindex it)");
                try {
                    linkedStudy = studyService.getStudy(new Long(i));
                } catch (Exception ex) {
                    linkedStudy = null;
                }
                reindexNecessary = false;

                if (linkedStudy != null) {
                    // Only released studies get indexed.
                    // (but studies that are no longer released may 
                    // need to be dropped from the crosslinking map, and
                    // from the index)

                    currentCrossLinks = linkedStudy.getLinkedToNetworks();

                    if (linkedVdcNetworkMap[i] == -1) {
                        // If it's an "unlinked" study,
                        // remove the existing links in the database: 
                        logger.fine("study " + i + " no longer cross-linked to any subnetworks.");
                        //linkedStudy.setLinkedToNetworks(null);
                        linkedStudy = studyService.setLinkedToNetworks(linkedStudy.getId(), null);

                        reindexNecessary = true;
                    } else if (linkedStudy.isReleased()) {
                        // else find what subnetworks this study is already linked 
                        // to in the database:

                        linkedToNetworkIds = linkedStudy.getLinkedToNetworkIds();

                        long linkedNetworkBitString = produceLinkedNetworksBitstring(linkedToNetworkIds);

                        if (linkedNetworkBitString != linkedVdcNetworkMap[i]) {
                            // This means the cross-linking status of the study has changed!

                            logger.fine("study " + i + ": cross-linked status has changed; updating");

                            // Update it in the database: 
                            //linkedStudy.setLinkedToNetworks(newLinkedToNetworks(subNetworks, linkedVdcNetworkMap[i]));
                            linkedStudy = studyService.setLinkedToNetworks(linkedStudy.getId(),
                                    newLinkedToNetworks(subNetworks, linkedVdcNetworkMap[i]));

                            //studyService.updateStudy(linkedStudy);

                            reindexNecessary = true;
                        }
                    }

                    if (reindexNecessary) {
                        // Re-index the study: 

                        indexer = Indexer.getInstance();
                        boolean indexSuccess = true;
                        try {
                            indexer.deleteDocumentCarefully(linkedStudy.getId());
                        } catch (IOException ioe) {
                            indexSuccess = false;
                        }

                        if (indexSuccess) {
                            try {
                                //indexer.addDocument(linkedStudy);
                                addDocument(linkedStudy);
                            } catch (Exception ex) {
                                ioProblem = true;
                                ioProblemCount++;
                                logger.severe("Caught exception attempting to re-index re-linked study "
                                        + linkedStudy.getId() + "; " + ex.getMessage());
                                ex.printStackTrace();
                                indexSuccess = false;
                            }
                        } else {
                            logger.fine("Could not delete study " + linkedStudy.getId()
                                    + " from index; skipping reindexing.");
                        }

                        if (!indexSuccess) {
                            // Make sure we leave the db linking status entry
                            // in the same shape it was before the reindexing
                            // attempt; so that it'll hopefully get caught
                            // by the next reindexing now. 
                            //linkedStudy.setLinkedToNetworks(currentCrossLinks);
                            linkedStudy = studyService.setLinkedToNetworks(linkedStudy.getId(),
                                    currentCrossLinks);
                        }
                    }
                }
            }
        }
        logger.info("Done reindexing collection-linked studies.");

    } catch (Exception ex) {
        ioProblem = true;
        ioProblemCount++;
        logger.severe("Caught exception while trying to update studies in collections: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        // delete the lock file:
        if (collReindexLockFile.exists()) {
            collReindexLockFile.delete();
        }
    }

    handleIOProblems(ioProblem, ioProblemCount);
}

From source file:org.apache.nifi.controller.FlowController.java

static boolean areEqual(final Long a, final Long b) {
    if (a == null && b == null) {
        return true;
    }//from www.  j a va  2s. c o m
    if (a == b) {
        return true;
    }

    if (a == null || b == null) {
        return false;
    }
    return a.compareTo(b) == 0;
}

From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinReviewServiceImpl.java

public String getIconColorforScore(Long score) {

    if (score.equals(Long.valueOf(0))) {
        return "blue";
    } else if (score.compareTo(Long.valueOf(25)) < 0) {
        return "green";
    } else if (score.compareTo(Long.valueOf(50)) < 0) {
        return "yellow";
    } else if (score.compareTo(Long.valueOf(75)) < 0) {
        return "orange";
    } else {//w  w  w .  j  a v a  2  s  .c om
        return "red";
    }

}