Example usage for java.lang Integer compare

List of usage examples for java.lang Integer compare

Introduction

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

Prototype

public static int compare(int x, int y) 

Source Link

Document

Compares two int values numerically.

Usage

From source file:org.search.niem.uml.search.ui.ReferenceLibrarySearchPage.java

private void readCriteria() {
    final IDialogSettings s = Activator.getPlugin().getDialogSettings().getSection(PAGE_NAME);
    if (s == null) {
        return;//from   w  ww  . j av a  2 s .c  om
    }
    final IDialogSettings allCriteria = s.getSection(STORE_SEARCH_CRITERIA);
    if (allCriteria == null) {
        return;
    }
    final IDialogSettings[] sections = allCriteria.getSections();
    if (sections == null) {
        return;
    }
    final ArrayList<IDialogSettings> sortedSections = new ArrayList<>(asList(sections));
    Collections.sort(sortedSections, new Comparator<IDialogSettings>() {
        @Override
        public int compare(final IDialogSettings left, final IDialogSettings right) {
            return Integer.compare(getIndex(left.getName()), getIndex(right.getName()));
        }
    });
    for (final IDialogSettings searchCriteria : sortedSections) {
        int matchType = 0;
        try {
            matchType = searchCriteria.getInt(STORE_MATCH_TYPES);
        } catch (final NumberFormatException e) {
            // no-op
        }
        history.add(new Criteria(searchCriteria.get(STORE_SEARCH_TERM), matchType));
    }
}

From source file:no.imr.sea2data.stox.InstallerUtil.java

public static Boolean retrieveFromFTP(String ftpPath, String outFile, FTPFileFilter filter) {
    try {// w  ww  .j a va2s  . com
        FTPClient ftpClient = new FTPClient();
        // pass directory path on server to connect
        if (ftpPath == null) {
            return false;
        }
        ftpPath = ftpPath.replace("ftp://", "");
        String[] s = ftpPath.split("/", 2);
        if (s.length != 2) {
            return false;
        }
        String server = s[0];
        String subPath = s[1];
        ftpClient.setConnectTimeout(5000);
        ftpClient.connect(server);
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        if (!ftpClient.login("anonymous", "")) {
            return false;
        }
        ftpClient.enterLocalPassiveMode(); // bug : mac doesnt allow ftp server connect through through local firewall - thus use passive server
        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            try {
                String path = subPath + "/";
                FTPFile[] files = ftpClient.listFiles(path, filter);
                Optional<FTPFile> opt = Arrays.stream(files)
                        .sorted((f1, f2) -> Integer.compare(f1.getName().length(), f2.getName().length()))
                        .findFirst();
                if (opt.isPresent()) {
                    ftpClient.retrieveFile(path + opt.get().getName(), fos);
                }
            } finally {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
        return true;
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:org.rhwlab.BHC.NodeBase.java

@Override
public int compareTo(Object o) {
    NodeBase other = (NodeBase) o;/*www  .ja v a 2s.  com*/
    int ret = Double.compare(this.lnR, other.lnR);
    //        int ret = Double.compare(this.lnLike,other.lnLike);        
    if (ret == 0) {
        ret = Integer.compare(this.hashCode(), other.hashCode());
    }
    return ret;
}

From source file:com.vmware.photon.controller.api.frontend.backends.utils.TaskUtils.java

/**
 * Converts task from middle-end representation to front-end representation.
 *
 * Legacy code. This function is usually called by front-end clients. Once a middle-end represented task object
 * is created or returned, the front-end client converts the task object to front-end representation to
 * be returned to end user./* w ww  . ja va  2  s  . c o  m*/
 */
@Deprecated
public static Task convertMiddleEndToFrontEnd(TaskEntity taskEntity) {
    Task task = new Task();

    Task.Entity entity = new Task.Entity();
    entity.setId(taskEntity.getEntityId());
    entity.setKind(taskEntity.getEntityKind());
    task.setEntity(entity);

    task.setId(taskEntity.getId());
    task.setQueuedTime(taskEntity.getQueuedTime());
    task.setStartedTime(taskEntity.getStartedTime());
    task.setEndTime(taskEntity.getEndTime());
    task.setOperation(taskEntity.getOperation().toString());
    task.setState(taskEntity.getState().toString());

    if (StringUtils.isNotBlank(taskEntity.getResourceProperties())) {
        try {
            Object resourceProperties = objectMapper.readValue(taskEntity.getResourceProperties(),
                    Object.class);
            task.setResourceProperties(resourceProperties);
        } catch (IOException e) {
            throw new IllegalArgumentException(
                    String.format("Error deserializing taskEntity resourceProperties %s, error %s",
                            taskEntity.getResourceProperties(), e.getMessage()));
        }
    }

    List<Step> steps = new ArrayList<>();
    taskEntity.getSteps().stream().sorted(
            (stepEntity1, stepEntity2) -> Integer.compare(stepEntity1.getSequence(), stepEntity2.getSequence()))
            .forEach(stepEntity -> steps.add(StepUtils.convertMiddleEndToFrontEnd(stepEntity)));
    task.setSteps(steps);

    return task;
}

From source file:tds.student.sql.repository.ItemBankRepository.java

/**
 * This has been replaced by ItemBankService.getTestAccommodations and utilizes caching.
 *
 * @deprecated use {@link #ItemBankService.getTestAccommodations()} instead.
 *//*from w  ww.j  a va 2  s  . com*/
@Deprecated
public AccList getTestAccommodations(String testKey) throws ReturnStatusException {
    AccList accList = new AccList();
    try (SQLConnection connection = getSQLConnection()) {

        Iterator<SingleDataResultSet> results = _commonDll.IB_GetTestAccommodations_SP(connection, testKey)
                .getResultSets();
        if (results.hasNext()) {
            SingleDataResultSet firstResultSet = results.next();
            ReturnStatusException.getInstanceIfAvailable(firstResultSet);
            Iterator<DbResultRecord> records = firstResultSet.getRecords();
            while (records.hasNext()) {
                DbResultRecord record = records.next();
                Data accData = AccListParseData.parseData(record);
                // HACK: Skip loading non-functional accommodations
                if (!accData.isFunctional())
                    continue;
                accList.add(accData);
            }
            if (results.hasNext()) {
                SingleDataResultSet secondResultSet = results.next();
                records = secondResultSet.getRecords();
                while (records.hasNext()) {
                    DbResultRecord record = records.next();
                    accList.getDependencies().add(AccListParseData.parseDependency(record));
                }
            }
        }
        Collections.sort(accList.getData(), new Comparator<Data>() {
            @Override
            public int compare(Data acc1, Data acc2) {
                if (acc1.getSegmentPosition() != acc2.getSegmentPosition())
                    return Integer.compare(acc1.getSegmentPosition(), acc2.getSegmentPosition());
                if (acc1.getToolTypeSortOrder() != acc2.getToolTypeSortOrder())
                    return Integer.compare(acc1.getToolTypeSortOrder(), acc2.getToolTypeSortOrder());
                if (acc1.getToolValueSortOrder() != acc2.getToolValueSortOrder())
                    return Integer.compare(acc1.getToolValueSortOrder(), acc2.getToolValueSortOrder());
                return 0;
            }
        });
    } catch (SQLException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }
    return accList;
}

From source file:org.datavec.api.records.reader.impl.LineRecordReader.java

@Override
public List<Record> loadFromMetaData(List<RecordMetaData> recordMetaDatas) throws IOException {
    //First: create a sorted list of the RecordMetaData
    List<Triple<Integer, RecordMetaDataLine, List<Writable>>> list = new ArrayList<>();
    Set<URI> uris = new HashSet<>();
    Iterator<RecordMetaData> iter = recordMetaDatas.iterator();
    int count = 0;
    while (iter.hasNext()) {
        RecordMetaData rmd = iter.next();
        if (!(rmd instanceof RecordMetaDataLine)) {
            throw new IllegalArgumentException(
                    "Invalid metadata; expected RecordMetaDataLine instance; got: " + rmd);
        }/*from   w  ww  .j a v a 2 s.  co m*/
        list.add(new Triple<>(count++, (RecordMetaDataLine) rmd, (List<Writable>) null));
        if (rmd.getURI() != null)
            uris.add(rmd.getURI());
    }
    List<URI> sortedURIs = null;
    if (uris.size() > 0) {
        sortedURIs = new ArrayList<>(uris);
        Collections.sort(sortedURIs);
    }

    //Sort by URI first (if possible - don't always have URIs though, for String split etc), then sort by line number:
    Collections.sort(list, new Comparator<Triple<Integer, RecordMetaDataLine, List<Writable>>>() {
        @Override
        public int compare(Triple<Integer, RecordMetaDataLine, List<Writable>> o1,
                Triple<Integer, RecordMetaDataLine, List<Writable>> o2) {
            if (o1.getSecond().getURI() != null) {
                if (!o1.getSecond().getURI().equals(o2.getSecond().getURI())) {
                    return o1.getSecond().getURI().compareTo(o2.getSecond().getURI());
                }
            }
            return Integer.compare(o1.getSecond().getLineNumber(), o2.getSecond().getLineNumber());
        }
    });

    if (uris.size() > 0 && sortedURIs != null) {
        //URIs case - possibly with multiple URIs
        Iterator<Triple<Integer, RecordMetaDataLine, List<Writable>>> metaIter = list.iterator(); //Currently sorted by URI, then line number

        URI currentURI = sortedURIs.get(0);
        Iterator<String> currentUriIter = IOUtils
                .lineIterator(new InputStreamReader(currentURI.toURL().openStream()));
        int currentURIIdx = 0; //Index of URI
        int currentLineIdx = 0; //Index of the line for the current URI
        String line = currentUriIter.next();
        while (metaIter.hasNext()) {
            Triple<Integer, RecordMetaDataLine, List<Writable>> t = metaIter.next();
            URI thisURI = t.getSecond().getURI();
            int nextLineIdx = t.getSecond().getLineNumber();

            //First: find the right URI for this record...
            while (!currentURI.equals(thisURI)) {
                //Iterate to the next URI
                currentURIIdx++;
                if (currentURIIdx >= sortedURIs.size()) {
                    //Should never happen
                    throw new IllegalStateException(
                            "Count not find URI " + thisURI + " in URIs list: " + sortedURIs);
                }
                currentURI = sortedURIs.get(currentURIIdx);
                currentLineIdx = 0;
                if (currentURI.equals(thisURI)) {
                    //Found the correct URI for this MetaData instance
                    closeIfRequired(currentUriIter);
                    currentUriIter = IOUtils
                            .lineIterator(new InputStreamReader(currentURI.toURL().openStream()));
                    line = currentUriIter.next();
                }
            }

            //Have the correct URI/iter open -> scan to the required line
            while (currentLineIdx < nextLineIdx && currentUriIter.hasNext()) {
                line = currentUriIter.next();
                currentLineIdx++;
            }
            if (currentLineIdx < nextLineIdx && !currentUriIter.hasNext()) {
                throw new IllegalStateException("Could not get line " + nextLineIdx + " from URI " + currentURI
                        + ": has only " + currentLineIdx + " lines");
            }
            t.setThird(Collections.<Writable>singletonList(new Text(line)));
        }
    } else {
        //Not URI based: String split, etc
        Iterator<String> iterator = getIterator(0);
        Iterator<Triple<Integer, RecordMetaDataLine, List<Writable>>> metaIter = list.iterator();
        int currentLineIdx = 0;
        String line = iterator.next();
        while (metaIter.hasNext()) {
            Triple<Integer, RecordMetaDataLine, List<Writable>> t = metaIter.next();
            int nextLineIdx = t.getSecond().getLineNumber();
            while (currentLineIdx < nextLineIdx && iterator.hasNext()) {
                line = iterator.next();
                currentLineIdx++;
            }
            t.setThird(Collections.<Writable>singletonList(new Text(line)));
        }
        closeIfRequired(iterator);
    }

    //Now, sort by the original (request) order:
    Collections.sort(list, new Comparator<Triple<Integer, RecordMetaDataLine, List<Writable>>>() {
        @Override
        public int compare(Triple<Integer, RecordMetaDataLine, List<Writable>> o1,
                Triple<Integer, RecordMetaDataLine, List<Writable>> o2) {
            return Integer.compare(o1.getFirst(), o2.getFirst());
        }
    });

    //And return...
    List<Record> out = new ArrayList<>();
    for (Triple<Integer, RecordMetaDataLine, List<Writable>> t : list) {
        out.add(new org.datavec.api.records.impl.Record(t.getThird(), t.getSecond()));
    }
    return out;
}

From source file:org.wso2.carbon.analytics.dataservice.core.indexing.sort.RecordSortUtils.java

private static int compareValues(AnalyticsSchema.ColumnType type, Object value1, Object value2)
        throws AnalyticsException {
    int compareInt;
    switch (type) {
    case STRING:/*  ww w . j av a  2s  .  c  o m*/
        compareInt = ((String) value1).compareTo(((String) value2));
        break;
    case INTEGER:
        compareInt = Integer.compare((Integer) value1, (Integer) value2);
        break;
    case LONG:
        compareInt = Long.compare((Long) value1, (Long) value2);
        break;
    case FLOAT:
        compareInt = Float.compare((Float) value1, (Float) value2);
        break;
    case DOUBLE:
        compareInt = Double.compare((Double) value1, (Double) value2);
        break;
    case BOOLEAN:
        compareInt = Boolean.compare((Boolean) value1, (Boolean) value2);
        break;
    default:
        throw new AnalyticsException("Cannot sort values of type: " + type);
    }
    return compareInt;
}

From source file:org.nuxeo.apidoc.browse.Distribution.java

public List<DistributionSnapshot> listPersistedDistributions() {
    SnapshotManager sm = getSnapshotManager();
    return sm.listPersistentSnapshots(ctx.getCoreSession()).stream().sorted((o1, o2) -> {
        Matcher m1 = VERSION_REGEX.matcher(o1.getVersion());
        Matcher m2 = VERSION_REGEX.matcher(o2.getVersion());

        if (m1.matches() && m2.matches()) {
            for (int i = 0; i < 3; i++) {
                String s1 = m1.group(i + 1);
                int c1 = s1 != null ? Integer.parseInt(s1) : 0;
                String s2 = m2.group(i + 1);
                int c2 = s2 != null ? Integer.parseInt(s2) : 0;

                if (c1 != c2 || i == 2) {
                    return Integer.compare(c2, c1);
                }//w ww. j  a  v  a 2 s.com
            }
        }
        log.info(String.format("Comparing version using String between %s - %s", o1.getVersion(),
                o2.getVersion()));
        return o2.getVersion().compareTo(o1.getVersion());
    }).filter(s -> !s.isHidden()).collect(Collectors.toList());
}

From source file:com.linkedin.pinot.controller.helix.core.relocation.RealtimeSegmentRelocator.java

/**
 * Given a realtime tag config and an ideal state, relocate the segments
 * which are completed but still hanging around on consuming servers, one replica at a time
 * @param  realtimeTagConfig//  ww  w . ja  v a2s  . co  m
 * @param idealState
 */
protected void relocateSegments(RealtimeTagConfig realtimeTagConfig, IdealState idealState) {

    List<String> consumingServers = _helixAdmin.getInstancesInClusterWithTag(_helixManager.getClusterName(),
            realtimeTagConfig.getConsumingServerTag());
    if (consumingServers.isEmpty()) {
        throw new IllegalStateException(
                "Found no realtime consuming servers with tag " + realtimeTagConfig.getConsumingServerTag());
    }
    List<String> completedServers = _helixAdmin.getInstancesInClusterWithTag(_helixManager.getClusterName(),
            realtimeTagConfig.getCompletedServerTag());
    if (completedServers.isEmpty()) {
        throw new IllegalStateException(
                "Found no realtime completed servers with tag " + realtimeTagConfig.getCompletedServerTag());
    }

    if (completedServers.size() < Integer.valueOf(idealState.getReplicas())) {
        throw new IllegalStateException("Number of completed servers: " + completedServers.size()
                + " is less than num replicas: " + idealState.getReplicas());
    }
    // TODO: use segment assignment strategy to decide where to place relocated segment

    // create map of completed server name to num segments it holds.
    // This will help us decide which completed server to choose for replacing a consuming server
    Map<String, Integer> completedServerToNumSegments = new HashMap<>(completedServers.size());
    for (String server : completedServers) {
        completedServerToNumSegments.put(server, 0);
    }
    for (String segmentName : idealState.getPartitionSet()) {
        Map<String, String> instanceStateMap = idealState.getInstanceStateMap(segmentName);
        for (String instance : instanceStateMap.keySet()) {
            if (completedServers.contains(instance)) {
                completedServerToNumSegments.put(instance, completedServerToNumSegments.get(instance) + 1);
            }
        }
    }
    MinMaxPriorityQueue<Map.Entry<String, Integer>> completedServersQueue = MinMaxPriorityQueue
            .orderedBy(new Comparator<Map.Entry<String, Integer>>() {
                @Override
                public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
                    return Integer.compare(entry1.getValue(), entry2.getValue());
                }
            }).maximumSize(completedServers.size()).create();
    completedServersQueue.addAll(completedServerToNumSegments.entrySet());

    // get new mapping for segments that need relocation
    createNewIdealState(idealState, consumingServers, completedServersQueue);
}

From source file:bear.plugins.groovy.GroovyCodeCompleter.java

public Replacements completeCode(String script, int position) {
    int[] range = scanForStart(script, position, -1);

    int start = range[0];
    int end = range[1] + 1;

    boolean endsWithDot = script.charAt(firstNonSpace(script, Math.min(end, script.length() - 1), -1)) == '.';

    List<Token> tokens = tokenize(script, start, end);

    //fo| => size 1
    //foo. => size 1
    Class<?> firstTokenClass;
    if (tokens.size() == 1 && !endsWithDot) {
        firstTokenClass = null;/*www  .  j  a  v a2s.  c om*/
        //match vars from binding, there should be a few

        Set<Map.Entry<String, ?>> entries = binding.getVariables().entrySet();
        List<Candidate> candidates = new ArrayList<Candidate>();

        for (Map.Entry<String, ?> entry : entries) {
            String varName = entry.getKey();

            char[] chars = tokens.get(0).name.toCharArray();

            int score = 0;

            for (int i = 0; i < chars.length; i++) {
                score += frequency(varName, chars[i]) * i == 0 ? 3 : (i == 1 ? 2 : 1);
            }

            if (score > 0) {
                candidates.add(new Candidate(
                        new Replacement(varName, entry.getValue().getClass().getSimpleName()), score));
            }
        }

        Collections.sort(candidates);

        return new Replacements(start, end).addAll(candidates);
    } else {
        Object variable = shell.getVariable(tokens.get(0).name);
        firstTokenClass = variable == null ? null : variable.getClass();
    }

    List<Class<?>> currentClasses = firstTokenClass == null ? new ArrayList<Class<?>>()
            : Lists.<Class<?>>newArrayList(firstTokenClass);

    for (int i = 1; i < tokens.size(); i++) {
        Token token = tokens.get(i);
        boolean lastToken = i == tokens.size() - 1;

        if (lastToken && !endsWithDot) {
            break;
        }

        //strict match
        List<Class<?>> returnTypes = new ArrayList<Class<?>>();

        if (token.method) {
            for (Class<?> currentClass : currentClasses) {
                for (MethodDesc method : OpenBean.methods(currentClass)) {
                    if (method.getName().equals(token.name)) {
                        returnTypes.add(method.getMethod().getReturnType());
                    }
                }
            }
        } else {
            for (Class<?> currentClass : currentClasses) {
                for (Field field : OpenBean.fields(currentClass)) {
                    if (field.getName().equals(token.name)) {
                        returnTypes.add(field.getType());
                    }
                }
            }
        }

        if (returnTypes.size() > 1) {
            currentClasses = Lists.newArrayList(new LinkedHashSet<Class<?>>(returnTypes));
        } else {
            currentClasses = returnTypes;
        }
    }

    String pattern = null;

    if (!endsWithDot) {
        pattern = tokens.get(tokens.size() - 1).name.toLowerCase();
    }

    Replacements replacements = endsWithDot ? new Replacements(position, position)
            : new Replacements(tokens.get(tokens.size() - 1).start, position);

    if (endsWithDot) {
        for (Class<?> currentClass : currentClasses) {
            for (Field field : OpenBean.fields(currentClass)) {
                replacements.add(new Replacement(field));
            }

            for (MethodDesc method : OpenBean.methods(currentClass)) {
                replacements.add(new Replacement(method));
            }
        }
    } else {
        final String patternLC = pattern.toLowerCase();
        Set<Field> usedFields = new HashSet<Field>();
        Set<Method> usedMethods = new HashSet<Method>();

        List<Candidate> candidates = new ArrayList<Candidate>();

        {
            int score = 10000;
            for (Class<?> currentClass : currentClasses) {
                for (Field field : OpenBean.fields(currentClass)) {
                    if (field.getName().toLowerCase().startsWith(patternLC)) {
                        usedFields.add(field);
                        candidates.add(new Candidate(new Replacement(field), score--));
                    }
                }

                for (MethodDesc method : OpenBean.methods(currentClass)) {
                    if (method.getName().toLowerCase().startsWith(patternLC)) {
                        usedMethods.add(method.getMethod());
                        candidates.add(new Candidate(new Replacement(method), score--));
                    }
                }
            }
        }

        Collections.sort(candidates, new Comparator<Candidate>() {
            @Override
            public int compare(Candidate o1, Candidate o2) {
                int d1 = StringUtils.getLevenshteinDistance(o1.r.name.toLowerCase(), patternLC);
                int d2 = StringUtils.getLevenshteinDistance(o2.r.name.toLowerCase(), patternLC, d1 + 1);
                return Integer.compare(d1, d2);
            }
        });

        for (int i = 0; i < candidates.size(); i++) {
            Candidate candidate = candidates.get(i);
            candidate.score = 10000 - i;
        }

        char[] chars = pattern.toCharArray();
        for (Class<?> currentClass : currentClasses) {
            for (Field field : OpenBean.fields(currentClass)) {
                if (usedFields.contains(field))
                    continue;

                int r = 0;

                for (char aChar : chars) {
                    r += frequency(field.getName(), aChar);
                }

                if (r > 0)
                    candidates.add(new Candidate(new Replacement(field), r));

            }

            for (MethodDesc method : OpenBean.methods(currentClass)) {
                if (usedMethods.contains(method.getMethod()))
                    continue;

                int r = 0;

                for (char aChar : chars) {
                    r += frequency(method.getName(), aChar);
                }

                if (r > 0)
                    candidates.add(new Candidate(new Replacement(method), r));
            }
        }

        Collections.sort(candidates);

        replacements.addAll(candidates);
    }

    return replacements;
}