Example usage for java.util Comparator naturalOrder

List of usage examples for java.util Comparator naturalOrder

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() 

Source Link

Document

Returns a comparator that compares Comparable objects in natural order.

Usage

From source file:net.sourceforge.pmd.docs.DeadLinksChecker.java

private Map<Path, List<String>> joinFutures(Map<Path, List<Future<String>>> map) {
    Map<Path, List<String>> joined = new HashMap<>();

    for (Path p : map.keySet()) {

        List<String> evaluatedResult = map.get(p).stream().map(f -> {
            try {
                return f.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();//from w w w .  j  av a2  s  . c o m
                return null;
            }
        }).filter(Objects::nonNull).sorted(Comparator.naturalOrder()).collect(Collectors.toList());

        if (!evaluatedResult.isEmpty()) {
            joined.put(p, evaluatedResult);
        }
    }
    return joined;
}

From source file:org.apache.lens.cube.parse.PruneCauses.java

public String getBriefCause() {
    CandidateTablePruneCode maxCause = getReversed().keySet().stream().map(CandidateTablePruneCause::getCause)
            .max(Comparator.naturalOrder()).get();
    Map<CandidateTablePruneCause, String> maxCauseMap = Maps.newHashMap();
    for (Map.Entry<CandidateTablePruneCause, List<T>> entry : getReversed().entrySet()) {
        if (entry.getKey().getCause().equals(maxCause)) {
            maxCauseMap.put(entry.getKey(), StringUtils.join(entry.getValue(), ","));
        }// w w w. j ava  2s  .  c om
    }
    return maxCause.getBriefError(maxCauseMap.keySet());
}

From source file:org.apache.lens.cube.parse.SegmentationCandidate.java

@Override
public Optional<Date> getColumnStartTime(String column) {
    if (areCandidatesPicked()) {
        return candidateStream().map(c -> c.getColumnStartTime(column)).filter(Optional::isPresent)
                .map(Optional::get).min(Comparator.naturalOrder());
    } else {//  w  w  w .j  a v  a  2  s.  c  om
        return cubeStream().map(cube -> cube.getColumnByName(column)).map(CubeColumn::getStartTime)
                .filter(Objects::nonNull).min(Comparator.naturalOrder());
    }
}

From source file:org.apache.lens.cube.parse.SegmentationCandidate.java

@Override
public Optional<Date> getColumnEndTime(String column) {
    if (areCandidatesPicked()) {
        return candidateStream().map(c -> c.getColumnEndTime(column)).filter(Optional::isPresent) // use flatmap(Optional::stream) after migration to java9
                .map(Optional::get) // https://bugs.openjdk.java.net/browse/JDK-8050820
                .max(Comparator.naturalOrder());
    } else {//from w  ww  . j  ava 2s . com
        return cubeStream().map(cube -> cube.getColumnByName(column)).map(CubeColumn::getEndTime)
                .filter(Objects::nonNull).max(Comparator.naturalOrder());
    }
}

From source file:org.hyperledger.fabric.sdk.helper.SDKUtil.java

/**
 * Generate hash of a chain code directory
 * @param rootDir Root directory/*from  w  w w.j  a  v  a2s . co  m*/
 * @param chaincodeDir Chain code directory
 * @param hash Previous hash (if any)
 * @return hash of the directory
 * @throws IOException
 */
public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash)
        throws IOException {
    // Generate the project directory
    Path projectPath = null;
    if (rootDir == null) {
        projectPath = Paths.get(chaincodeDir);
    } else {
        projectPath = Paths.get(rootDir, chaincodeDir);
    }

    File dir = projectPath.toFile();
    if (!dir.exists() || !dir.isDirectory()) {
        throw new IOException(String.format("The chaincode path \"%s\" is invalid", projectPath));
    }

    StringBuilder hashBuilder = new StringBuilder(hash);
    Files.walk(projectPath).sorted(Comparator.naturalOrder()).filter(Files::isRegularFile).map(Path::toFile)
            .forEach(file -> {
                try {
                    byte[] buf = readFile(file);
                    byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes());
                    hashBuilder.setLength(0);
                    hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest())));
                } catch (IOException ex) {
                    throw new RuntimeException(
                            String.format("Error while reading file %s", file.getAbsolutePath()), ex);
                }
            });

    // If original hash and final hash are the same, it indicates that no new contents were found
    if (hashBuilder.toString().equals(hash)) {
        throw new IOException(String.format("The chaincode directory \"%s\" has no files", projectPath));
    }
    return hashBuilder.toString();
}

From source file:org.hyperledger.fabric.sdk.helper.Utils.java

/**
 * Generate hash of a chaincode directory
 *
 * @param rootDir      Root directory//w w  w. java  2 s .c  om
 * @param chaincodeDir Channel code directory
 * @param hash         Previous hash (if any)
 * @return hash of the directory
 * @throws IOException
 */
public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash)
        throws IOException {
    // Generate the project directory
    Path projectPath = null;
    if (rootDir == null) {
        projectPath = Paths.get(chaincodeDir);
    } else {
        projectPath = Paths.get(rootDir, chaincodeDir);
    }

    File dir = projectPath.toFile();
    if (!dir.exists() || !dir.isDirectory()) {
        throw new IOException(format("The chaincode path \"%s\" is invalid", projectPath));
    }

    StringBuilder hashBuilder = new StringBuilder(hash);
    Files.walk(projectPath).sorted(Comparator.naturalOrder()).filter(Files::isRegularFile).map(Path::toFile)
            .forEach(file -> {
                try {
                    byte[] buf = readFile(file);
                    byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes(UTF_8));
                    hashBuilder.setLength(0);
                    hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest())));
                } catch (IOException ex) {
                    throw new RuntimeException(format("Error while reading file %s", file.getAbsolutePath()),
                            ex);
                }
            });

    // If original hash and final hash are the same, it indicates that no new contents were found
    if (hashBuilder.toString().equals(hash)) {
        throw new IOException(format("The chaincode directory \"%s\" has no files", projectPath));
    }
    return hashBuilder.toString();
}

From source file:org.kitodo.production.services.data.ProcessService.java

/**
 * Filter and sort after creation date list of process properties for
 * correction and solution messages./*ww w  .j a va  2s.  co  m*/
 *
 * @return list of ProcessProperty objects
 */
public List<PropertyDTO> getSortedCorrectionSolutionMessages(ProcessDTO process) {
    List<PropertyDTO> filteredList = filterForCorrectionSolutionMessages(process.getProperties());

    if (filteredList.size() > 1) {
        filteredList.sort(Comparator.comparing(PropertyDTO::getCreationDate,
                Comparator.nullsFirst(Comparator.naturalOrder())));
    }

    return filteredList;
}

From source file:org.opencb.commons.utils.CommandLineUtils.java

public static void printCommandUsage(JCommander commander, PrintStream printStream) {

    Integer paramNameMaxSize = Math.max(commander.getParameters().stream().map(pd -> pd.getNames().length())
            .collect(Collectors.maxBy(Comparator.naturalOrder())).orElse(20), 20);
    Integer typeMaxSize = Math.max(commander.getParameters().stream().map(pd -> getType(pd).length())
            .collect(Collectors.maxBy(Comparator.naturalOrder())).orElse(10), 10);

    int nameAndTypeLength = paramNameMaxSize + typeMaxSize + 8;
    int maxLineLength = nameAndTypeLength + DESCRIPTION_LENGTH; //160

    Comparator<ParameterDescription> parameterDescriptionComparator = Comparator
            .comparing((ParameterDescription p) -> p.getDescription().contains("DEPRECATED"))
            .thenComparing(ParameterDescription::getLongestName);
    commander.getParameters().stream().sorted(parameterDescriptionComparator).forEach(parameterDescription -> {
        if (parameterDescription.getParameter() != null && !parameterDescription.getParameter().hidden()) {
            String type = getType(parameterDescription);
            String defaultValue = "";
            if (parameterDescription.getDefault() != null) {
                if (parameterDescription.isDynamicParameter()) {
                    Object def = parameterDescription.getDefault();
                    if (def instanceof Map && !((Map) def).isEmpty()) {
                        defaultValue = " [" + def + "]";
                    }/*from  w  w  w.  j  a  v  a2 s. co m*/
                } else {
                    defaultValue = " [" + parameterDescription.getDefault() + "]";
                }
            }
            String usage = String.format("%5s %-" + paramNameMaxSize + "s %-" + typeMaxSize + "s %s%s\n",
                    (parameterDescription.getParameterized().getParameter() != null
                            && parameterDescription.getParameterized().getParameter().required()) ? "*" : "",
                    parameterDescription.getNames(), type, parameterDescription.getDescription(), defaultValue);

            // if lines are longer than the maximum they are trimmed and printed in several lines
            List<String> lines = new LinkedList<>();
            while (usage.length() > maxLineLength + 1) {
                int splitPosition = Math.min(1 + usage.lastIndexOf(" ", maxLineLength), usage.length());
                if (splitPosition <= nameAndTypeLength + DESCRIPTION_INDENT) {
                    splitPosition = Math.min(1 + usage.indexOf(" ", maxLineLength), usage.length());
                }
                lines.add(usage.substring(0, splitPosition) + "\n");
                usage = String.format("%" + (nameAndTypeLength + DESCRIPTION_INDENT) + "s", "") + ""
                        + usage.substring(splitPosition);
            }
            // this is empty for short lines and so no prints anything
            lines.forEach(printStream::print);
            // in long lines this prints the last trimmed line
            printStream.print(usage);
        }
    });
}

From source file:org.opensingular.form.wicket.mapper.masterdetail.MasterDetailPanel.java

private IBSAction<SInstance> buildShowErrorsAction() {
    return new IBSAction<SInstance>() {
        @Override//from   w ww  . j  ava 2s .co m
        public void execute(AjaxRequestTarget target, IModel<SInstance> model) {
            SInstance baseInstance = model.getObject();
            SDocument doc = baseInstance.getDocument();
            Collection<IValidationError> errors = baseInstance.getNestedValidationErrors();
            if ((errors != null) && !errors.isEmpty()) {
                String alertLevel = errors.stream().map(IValidationError::getErrorLevel)
                        .max(Comparator.naturalOrder())
                        .map(it -> it.le(ValidationErrorLevel.WARNING) ? "alert-warning" : "alert-danger")
                        .orElse(null);

                final StringBuilder sb = new StringBuilder("<div><ul class='list-unstyled alert ")
                        .append(alertLevel).append("'>");
                for (IValidationError error : errors) {
                    Optional<SInstance> inst = doc.findInstanceById(error.getInstanceId());
                    inst.ifPresent(sInstance -> sb.append("<li>")
                            .append(SFormUtil.generateUserFriendlyPath(sInstance, baseInstance)).append(": ")
                            .append(error.getMessage()).append("</li>"));
                }
                sb.append("</ul></div>");

                target.appendJavaScript(
                        ";bootbox.alert('" + JavaScriptUtils.javaScriptEscape(sb.toString()) + "');");
                target.appendJavaScript(Scripts.multipleModalBackDrop());
            }
        }

        @Override
        public boolean isVisible(IModel<SInstance> model) {
            return model != null && model.getObject() != null && model.getObject().hasNestedValidationErrors();
        }
    };
}

From source file:org.opensingular.form.wicket.SValidationFeedbackHandler.java

public Optional<ValidationErrorLevel> findNestedErrorsMaxLevel(FeedbackFence feedbackFence,
        IPredicate<IValidationError> filter) {
    return collectNestedErrors(feedbackFence, resolveRootInstances(feedbackFence.getMainContainer()), filter)
            .stream().map(IValidationError::getErrorLevel).collect(Collectors.maxBy(Comparator.naturalOrder()));
}