Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:org.phoenicis.repository.types.ClasspathRepository.java

private List<ApplicationDTO> buildApplications(String typeId, String categoryId, String typeFileName,
        String categoryFileName) throws RepositoryException {
    try {//from   ww  w. ja v a 2 s . c om
        final String categoryScanClassPath = packagePath + "/" + typeFileName + "/" + categoryFileName;
        Resource[] resources = resourceResolver.getResources(categoryScanClassPath + "/*");
        final List<ApplicationDTO> applicationDTOS = new ArrayList<>();

        for (Resource resource : resources) {
            final String fileName = resource.getFilename();
            if (!"icon.png".equals(fileName) && !"category.json".equals(fileName)) {
                final ApplicationDTO application = buildApplication(typeId, categoryId, typeFileName,
                        categoryFileName, fileName);
                if (!application.getScripts().isEmpty()) {
                    applicationDTOS.add(application);
                }
            }
        }

        applicationDTOS.sort(Comparator.comparing(ApplicationDTO::getName));
        return applicationDTOS;
    } catch (IOException e) {
        throw new RepositoryException("Could not build applications", e);
    }
}

From source file:eu.itesla_project.online.tools.PrintOnlineWorkflowPostContingencyViolationsTool.java

private void printStateContingencyViolations(TableFormatter formatter, Integer stateId, String contingencyId,
        List<LimitViolation> violations, LimitViolationFilter violationsFilter) {
    if (violations != null) {
        if (violationsFilter != null) {
            violations = violationsFilter.apply(violations);
        }/*  w ww . jav  a2  s . co m*/
        violations.stream().sorted(Comparator.comparing(o -> o.getSubject().getId())).forEach(violation -> {
            try {
                formatter.writeCell(stateId);
                formatter.writeCell(contingencyId);
                formatter.writeCell(violation.getSubject().getId());
                formatter.writeCell(violation.getLimitType().name());
                formatter.writeCell(violation.getValue());
                formatter.writeCell(violation.getLimit());
                formatter.writeCell(violation.getLimitReduction());
                formatter.writeCell(violation.getBaseVoltage());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}

From source file:org.age.services.topology.internal.DefaultTopologyService.java

/**
 * Simple master selection. We rely on Hazelcast, so we just need to perform local, deterministic selection.
 *
 * In this case we selects the node with the largest nodeId.
 *//*from   w w  w  .j  av  a  2 s .c  o  m*/
private void electMaster(@NonNull final FSM<State, Event> fsm) {
    log.debug("Locally selecting master.");

    final Set<@NonNull NodeDescriptor> computeNodes = getComputeNodes();
    final Optional<NodeDescriptor> maxIdentity = computeNodes.parallelStream()
            .max(Comparator.comparing(NodeDescriptor::id));
    log.debug("Max identity is {}.", maxIdentity);

    assert maxIdentity.isPresent();

    if (identityService.nodeId().equals(maxIdentity.get().id())) {
        log.debug("I am master.");
        master = true;
        runtimeConfig.put(ConfigKeys.MASTER, identityService.nodeId());

        // Select initial topology type if this is the first election
        if (!runtimeConfig.containsKey(ConfigKeys.TOPOLOGY_TYPE)) {
            log.debug("Seems to be the first election. Selecting topology.");
            final Optional<TopologyProcessor> selectedProcessor = topologyProcessors.parallelStream()
                    .max(Comparator.comparing(TopologyProcessor::priority));
            assert selectedProcessor.isPresent();

            currentTopologyProcessor = selectedProcessor.get();
            log.debug("Selected initial topology: {}.", currentTopologyProcessor);
            runtimeConfig.put(ConfigKeys.TOPOLOGY_TYPE, currentTopologyProcessor.name());
        }
        listenerKey = runtimeConfig.addEntryListener(new TopologyTypeChangeListener(), ConfigKeys.TOPOLOGY_TYPE,
                true);

        service.fire(Event.TOPOLOGY_TYPE_CHANGED);
        fsm.goTo(State.MASTER_ELECTED_MASTER);
        topic.publish(TopologyMessage.createWithoutPayload(MASTER_ELECTED));

    } else {
        log.debug("I am slave.");
        master = false;
        if (listenerKey != null) {
            runtimeConfig.removeEntryListener(listenerKey);
        }

        fsm.goTo(State.MASTER_ELECTED_SLAVE);
    }
}

From source file:org.kuali.coeus.common.budget.impl.calculator.SalaryCalculator.java

private QueryList<BudgetPerson> filterBudgetPersons() {

    final List<BudgetPerson> persons = budget.getBudgetPersons();
    if (persons.isEmpty()) {
        return new QueryList<>();
    }//from   w w  w .  j a v a 2  s  .c  o  m

    final Optional<BudgetPerson> first = persons.stream().filter(
            person -> person.getPersonSequenceNumber().equals(personnelLineItem.getPersonSequenceNumber()))
            .findFirst();
    if (!first.isPresent()) {
        return new QueryList<>();
    }

    final List<BudgetPerson> filteredPersons = persons.stream().filter(person -> {
        final boolean personIdEquals = StringUtils.equals(person.getPersonId(), first.get().getPersonId());
        final boolean jobCodeEquals = StringUtils.equals(person.getJobCode(), first.get().getJobCode());
        final boolean rolodexIdEquals = Objects.equals(person.getRolodexId(), first.get().getRolodexId());
        final boolean effectiveDateLtEqualsEndDate = Objects.compare(person.getEffectiveDate(), this.endDate,
                Comparator.<Date>naturalOrder()) <= 0;
        return personIdEquals && jobCodeEquals && rolodexIdEquals && effectiveDateLtEqualsEndDate;
    }).collect(Collectors.toList());

    final Optional<BudgetPerson> tmpFirst = filteredPersons.stream().filter(person -> {
        final boolean effectiveDateLtEqualsStartDate = Objects.compare(person.getEffectiveDate(),
                this.startDate, Comparator.<Date>naturalOrder()) <= 0;
        final boolean effectiveDateEquals = Objects.compare(person.getEffectiveDate(),
                first.get().getEffectiveDate(), Comparator.<java.sql.Date>naturalOrder()) == 0;
        final boolean seqNotEquals = person.getPersonSequenceNumber().intValue() != first.get()
                .getPersonSequenceNumber();
        return effectiveDateLtEqualsStartDate && !(effectiveDateEquals && seqNotEquals);
    }).sorted(Comparator.comparing(BudgetPerson::getEffectiveDate).reversed()).findFirst();

    if (tmpFirst.isPresent()) {
        filteredPersons.clear();
        filteredPersons.add(tmpFirst.get());
    } else {
        StringBuilder warningMsg = new StringBuilder(
                "Base salary information is not available for the person ");
        StringBuilder errMsg = new StringBuilder("Error finding the calculation base for the person ");
        errMsg.append(this.personnelLineItem.getPersonId());
        errMsg.append(" with Job Code ");
        errMsg.append(this.personnelLineItem.getJobCode());

        warningMsg.append(this.personnelLineItem.getPersonId());
        warningMsg.append(" with Job Code ");
        warningMsg.append(this.personnelLineItem.getJobCode());
        warningMsg.append(" for the period ");
        warningMsg.append(dateTimeService.toDateString(startDate));
        warningMsg.append(" to ");
        if (!filteredPersons.isEmpty()) {
            warningMsg.append(dateTimeService.toDateString(add(filteredPersons.get(0).getEffectiveDate(), -1)));
        } else {
            warningMsg.append(dateTimeService.toDateString(personnelLineItem.getEndDate()));
        }
        warningMsg.append("\n");
        warningMsg.append("Salary for this period will be set to 0\n");
        warningMsg.append("Please make changes to budget person details and recalculate the budget");
        warningList.add(warningMsg.toString());
        errorList.add(errMsg.toString());
    }

    return new QueryList<>(filteredPersons);
}

From source file:org.wso2.security.tools.advisorytool.builders.CustomerSecurityAdvisoryBuilder.java

@Override
public void buildAdvisory() throws AdvisoryToolException {
    List<String> affectedPatchNames = new ArrayList<>();
    List<Patch> supportedPatchListForAdvisory = new ArrayList<>();

    //creating the list of patch supported products.
    List<Product> affectedPatchSupportedProducts = getPatchSupportedProducts(
            securityAdvisory.getAffectedAllProducts());
    securityAdvisory.setAffectedPatchProducts(affectedPatchSupportedProducts);

    //generate the patch details file to be used to upload the patches to the customer patch locations.
    generatePatchUploadDataFile(securityAdvisory.getName(), affectedPatchSupportedProducts);

    //creating the list of WUM supported products.
    List<Product> affectedWUMProductsList = getWUMProductsFromAffectedProducts(
            securityAdvisory.getAffectedAllProducts());
    securityAdvisory.setAffectedWUMProducts(affectedWUMProductsList);

    //creating the patch list with the customer patch download link.
    for (Product affectedPatchSupportedProduct : affectedPatchSupportedProducts) {
        for (Version affectedPatchSupportedVersion : affectedPatchSupportedProduct.getVersionList()) {
            for (String patchName : affectedPatchSupportedVersion.getPatchNamesList()) {

                for (Platform platform : Configuration.getInstance().getPlatforms()) {

                    if (affectedPatchSupportedVersion.getPlatformVersionNumber()
                            .equals(platform.getVersionNumber())) {

                        Patch patch = new Patch();
                        patch.setName(patchName);

                        //building the customer patch download URL.
                        String url = Configuration.getInstance().getPatchZIPCustomerLocation()
                                + platform.getPatchDirectoryName() + "/Product/"
                                + affectedPatchSupportedProduct.getCodeName() + " "
                                + affectedPatchSupportedVersion.getVersionNumber() + "/"
                                + patchName.replace(" ", "") + ".zip";

                        patch.setZipLocation(url);

                        if (!affectedPatchNames.contains(patchName)) {
                            affectedPatchNames.add(patchName);
                            supportedPatchListForAdvisory.add(patch);
                        }/* ww w  .jav  a2  s.c  om*/
                    }
                }
            }
        }

    }
    supportedPatchListForAdvisory.sort(Comparator.comparing(Patch::getName));
    securityAdvisory.setApplicablePatchList(supportedPatchListForAdvisory);
}

From source file:org.jenkinsci.plugins.androidsigning.SignApksBuilder.java

@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
        @Nonnull TaskListener listener) throws InterruptedException, IOException {
    if (isIntermediateFailure(run)) {
        listener.getLogger()/*from   w w w . j a va2 s . c o  m*/
                .println("[SignApksBuilder] skipping Sign APKs step because a previous step failed");
        return;
    }

    if (getEntries() != null && !getEntries().isEmpty()) {
        List<SignApksBuilder> newModelBuilders = singleEntryBuildersFromEntriesOfBuilder(this);
        for (SignApksBuilder builder : newModelBuilders) {
            builder.perform(run, workspace, launcher, listener);
        }
        return;
    }

    EnvVars env;
    if (run instanceof AbstractBuild) {
        env = run.getEnvironment(listener);
        env.overrideAll(((AbstractBuild<?, ?>) run).getBuildVariables());
    } else {
        env = new EnvVars();
    }

    FilePath builderDir = workspace.child(BUILDER_DIR);
    String excludeBuilderDir = builderDir.getName() + "/**";
    ZipalignTool zipalign = new ZipalignTool(env, workspace, listener.getLogger(), androidHome, zipalignPath);
    Map<String, String> apksToArchive = new LinkedHashMap<>();

    StandardCertificateCredentials keyStoreCredential = getKeystore(getKeyStoreId(), run.getParent());
    char[] storePassword = keyStoreCredential.getPassword().getPlainText().toCharArray();
    // TODO: add key password support
    char[] keyPassword = storePassword;
    KeyStore keyStore = keyStoreCredential.getKeyStore();
    String alias = getKeyAlias();
    PrivateKey key;
    Certificate[] certChain;
    try {
        if (getKeyAlias() == null) {
            // TODO: search all entries to find key, throw error if multiple keys
        }
        key = (PrivateKey) keyStore.getKey(alias, keyPassword);
        certChain = keyStore.getCertificateChain(alias);
    } catch (GeneralSecurityException e) {
        PrintWriter details = listener.fatalError("Error reading keystore " + getKeyStoreId());
        e.printStackTrace(details);
        throw new AbortException("Error reading keystore " + getKeyStoreId());
    }

    if (key == null || certChain == null) {
        throw new AbortException("Alias " + alias
                + " does not exist or does not point to a key and certificate in certificate credentials "
                + getKeyStoreId());
    }

    String v1SigName = alias;
    if (v1SigName == null) {
        v1SigName = keyStoreCredential.getId();
    }

    Set<FilePath> matchedApks = new TreeSet<>(Comparator.comparing(FilePath::getRemote));
    String[] globs = getSelectionGlobs();
    for (String glob : globs) {
        FilePath[] globMatch = workspace.list(glob, excludeBuilderDir);
        if (globMatch.length == 0) {
            throw new AbortException("No APKs in workspace matching " + glob);
        }
        matchedApks.addAll(Arrays.asList(globMatch));
    }

    for (FilePath unsignedApk : matchedApks) {
        unsignedApk = unsignedApk.absolutize();
        FilePath archiveDir = builderDir.child(unsignedApk.getName());
        if (archiveDir.isDirectory()) {
            archiveDir.deleteContents();
        } else {
            archiveDir.mkdirs();
        }
        String archiveDirRelName = relativeToWorkspace(workspace, archiveDir);
        String unsignedPathName = unsignedApk.getRemote();
        Pattern stripUnsignedPattern = Pattern.compile("(-?unsigned)?.apk$", Pattern.CASE_INSENSITIVE);
        Matcher stripUnsigned = stripUnsignedPattern.matcher(unsignedApk.getName());
        String strippedApkName = stripUnsigned.replaceFirst("");
        String alignedRelName = archiveDirRelName + "/" + strippedApkName + "-aligned.apk";
        String signedRelName = archiveDirRelName + "/" + strippedApkName + "-signed.apk";

        ArgumentListBuilder zipalignCommand = zipalign.commandFor(unsignedPathName, alignedRelName);
        listener.getLogger().printf("[SignApksBuilder] %s%n", zipalignCommand);
        int zipalignResult = launcher.launch().cmds(zipalignCommand).pwd(workspace).stdout(listener)
                .stderr(listener.getLogger()).join();

        if (zipalignResult != 0) {
            listener.fatalError("[SignApksBuilder] zipalign failed: exit code %d", zipalignResult);
            throw new AbortException(
                    String.format("zipalign failed on APK %s: exit code %d", unsignedPathName, zipalignResult));
        }

        FilePath alignedPath = workspace.child(alignedRelName);
        if (!alignedPath.exists()) {
            throw new AbortException(String.format("aligned APK does not exist: %s", alignedRelName));
        }

        listener.getLogger().printf("[SignApksBuilder] signing APK %s%n", alignedRelName);

        FilePath signedPath = workspace.child(signedRelName);
        final SignApkCallable signApk = new SignApkCallable(key, certChain, v1SigName, signedPath.getRemote(),
                listener);
        alignedPath.act(signApk);

        listener.getLogger().printf("[SignApksBuilder] signed APK %s%n", signedRelName);

        if (getArchiveUnsignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving unsigned APK %s%n", unsignedPathName);
            apksToArchive.put(archiveDirRelName + "/" + unsignedApk.getName(),
                    relativeToWorkspace(workspace, unsignedApk));
        }
        if (getArchiveSignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving signed APK %s%n", signedRelName);
            apksToArchive.put(signedRelName, signedRelName);
        }
    }

    listener.getLogger().println("[SignApksBuilder] finished signing APKs");

    if (apksToArchive.size() > 0) {
        run.pickArtifactManager().archive(workspace, launcher, BuildListenerAdapter.wrap(listener),
                apksToArchive);
    }
}

From source file:org.dcache.util.collector.pools.PoolInfoCollectorUtils.java

/**
 * <p>Accesses current state of selection unit.</p>
 *///from w ww.ja  va 2 s  .  c o m
public static String[] listPools(String group, PoolSelectionUnit poolSelectionUnit) {
    if (group == null || ALL.equalsIgnoreCase(group)) {
        return listPools(poolSelectionUnit);
    }

    if (poolSelectionUnit == null) {
        return new String[0];
    }

    return poolSelectionUnit.getPoolsByPoolGroup(group).stream()
            .sorted(Comparator.comparing(SelectionPool::getName)).map(SelectionPool::getName)
            .toArray(String[]::new);
}

From source file:de.ks.idnadrev.information.chart.ChartDataEditor.java

protected void sortGridPane() {
    ArrayList<Node> childrensToSort = new ArrayList<>(dataContainer.getChildren());

    Comparator<Node> rowCompare = Comparator.comparing(GridPane::getRowIndex);
    Comparator<Node> columnCompare = Comparator.comparing(GridPane::getColumnIndex);

    Collections.sort(childrensToSort, rowCompare.thenComparing(columnCompare));

    dataContainer.getChildren().clear();
    dataContainer.getChildren().addAll(childrensToSort);
}

From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java

@Override
public List<TopicVO> getTopics() {
    validateInitialized();//from w w w.  ja va  2 s  .com
    return getTopicMetadata().values().stream().sorted(Comparator.comparing(TopicVO::getName))
            .collect(Collectors.toList());
}

From source file:View.Visualize.java

public void getStackedBarChartData(Integer nameColumn, Integer valueColumn, Table table,
        StackedBarChart stackedBarChart, Boolean newSeries, Boolean rowCounter) {
    data.clear();//from   www. j  a va2 s . c  o  m
    ObservableList<XYChart.Data> barChartData = FXCollections.observableArrayList();
    XYChart.Series series1 = new XYChart.Series();

    if (!newSeries) {
        series1.getData().clear();
        stackedBarChart.getData().clear();

    }
    stackedBarChart.setAnimated(false);//bug fix
    addDataFromTable(table, nameColumn, valueColumn, rowCounter);

    data.entrySet().stream().map(entry -> new XYChart.Data(entry.getKey(), entry.getValue()))
            .forEach(barChartData::add);

    stackedBarChart.getData().addAll(series1);
    series1.getData().addAll(barChartData);

    series1.getData().sort(Comparator.comparing(BarChart.Data<String, Double>::getYValue).reversed());

    setupHover(series1);
    addColorChangeOnIndividual(barChartData);
}