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:com.netflix.genie.core.jobs.workflow.impl.InitialSetupTask.java

/**
 * Helper to convert a set of tags into a string that is a suitable value for a shell environment variable.
 * Adds double quotes as necessary (i.e. in case of spaces, newlines), performs escaping of in-tag quotes.
 * Input tags are sorted to produce a deterministic output value.
 * @param tags a set of tags or null/*from ww  w. j  a  v a  2s . c  o  m*/
 * @return a CSV string
 */
@VisibleForTesting
String tagsToString(final Set<String> tags) {
    final ArrayList<String> sortedTags = new ArrayList<>(tags == null ? Collections.emptySet() : tags);
    // Sort tags for the sake of determinism (e.g., tests)
    sortedTags.sort(Comparator.naturalOrder());
    final String joinedString = StringUtils.join(sortedTags, ',');
    // Escape quotes
    return StringUtils.replaceAll(StringUtils.replaceAll(joinedString, "\'", "\\\'"), "\"", "\\\"");
}

From source file:org.onosproject.EvacuateCommand.java

@SuppressWarnings("rawtypes")
private TreeMultimap<String, Metric> listMetrics(MetricsService metricsService, MetricFilter filter) {
    TreeMultimap<String, Metric> metrics = TreeMultimap.create(Comparator.naturalOrder(), Ordering.arbitrary());

    Map<String, Counter> counters = metricsService.getCounters(filter);
    for (Entry<String, Counter> entry : counters.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }/*from w w w .ja v a2 s. c o m*/
    Map<String, Gauge> gauges = metricsService.getGauges(filter);
    for (Entry<String, Gauge> entry : gauges.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }
    Map<String, Histogram> histograms = metricsService.getHistograms(filter);
    for (Entry<String, Histogram> entry : histograms.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }
    Map<String, Meter> meters = metricsService.getMeters(filter);
    for (Entry<String, Meter> entry : meters.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }
    Map<String, Timer> timers = metricsService.getTimers(filter);
    for (Entry<String, Timer> entry : timers.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }

    return metrics;
}

From source file:com.marand.thinkmed.medications.business.impl.DefaultMedicationsBo.java

@Override
public boolean isTherapyModifiedFromLastReview(@Nonnull final MedicationInstructionInstruction instruction,
        @Nonnull final List<MedicationActionAction> actionsList,
        @Nonnull final DateTime compositionCreatedTime) {
    Preconditions.checkNotNull(instruction, "instruction");
    Preconditions.checkNotNull(actionsList, "actionsList");
    Preconditions.checkNotNull(compositionCreatedTime, "compositionCreatedTime");

    final Optional<DateTime> latestModifyActionTime = actionsList.stream().filter(
            action -> MedicationActionEnum.getActionEnum(action) == MedicationActionEnum.MODIFY_EXISTING)
            .map(a -> DataValueUtils.getDateTime(a.getTime())).max(Comparator.naturalOrder());

    final boolean hasUpdateLink = MedicationsEhrUtils.hasLinksOfType(instruction, EhrLinkType.UPDATE);
    if (!hasUpdateLink && !latestModifyActionTime.isPresent()) {
        return false;
    }/*from   ww  w .j  a v a2s.c om*/

    final DateTime latestModifyTime = latestModifyActionTime.isPresent()
            && latestModifyActionTime.get().isAfter(compositionCreatedTime) ? latestModifyActionTime.get()
                    : compositionCreatedTime;

    for (final MedicationActionAction action : actionsList) {
        final MedicationActionEnum actionEnum = MedicationActionEnum.getActionEnum(action);
        final DateTime actionDateTime = DataValueUtils.getDateTime(action.getTime());
        if (MedicationActionEnum.THERAPY_REVIEW_ACTIONS.contains(actionEnum)
                && actionDateTime.isAfter(latestModifyTime)) {
            return false;
        }
    }

    return true;
}

From source file:com.netflix.genie.web.jobs.workflow.impl.InitialSetupTask.java

/**
 * Helper to convert a set of tags into a string that is a suitable value for a shell environment variable.
 * Adds double quotes as necessary (i.e. in case of spaces, newlines), performs escaping of in-tag quotes.
 * Input tags are sorted to produce a deterministic output value.
 *
 * @param tags a set of tags or null//w w  w . j  ava2 s. c o m
 * @return a CSV string
 */
@VisibleForTesting
String tagsToString(final Set<String> tags) {
    final ArrayList<String> sortedTags = new ArrayList<>(tags == null ? Collections.emptySet() : tags);
    // Sort tags for the sake of determinism (e.g., tests)
    sortedTags.sort(Comparator.naturalOrder());
    final String joinedString = StringUtils.join(sortedTags, ',');
    // Escape quotes
    return RegExUtils.replaceAll(RegExUtils.replaceAll(joinedString, "\'", "\\\'"), "\"", "\\\"");
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

/**
 * Method that looks at the supplied input and compares it with partial state in metadata store to determine
 * if the partial state corresponds to supplied input.
 * @param segmentsToSeal segments to seal
 * @param newRanges new ranges to create
 * @param historyTable history table/*  ww  w. ja va2s . co m*/
 * @param segmentTable segment table
 * @return true if input matches partial state, false otherwise
 */
public static boolean isRerunOf(final List<Integer> segmentsToSeal,
        final List<AbstractMap.SimpleEntry<Double, Double>> newRanges, final byte[] historyTable,
        final byte[] segmentTable) {
    HistoryRecord latestHistoryRecord = HistoryRecord.readLatestRecord(historyTable, false).get();

    int n = newRanges.size();
    List<SegmentRecord> lastN = SegmentRecord.readLastN(segmentTable, n);

    boolean newSegmentsPredicate = newRanges.stream().allMatch(x -> lastN.stream()
            .anyMatch(y -> y.getRoutingKeyStart() == x.getKey() && y.getRoutingKeyEnd() == x.getValue()));
    boolean segmentToSealPredicate;
    boolean exactMatchPredicate;

    // CASE 1: only segment table is updated.. history table isnt...
    if (!latestHistoryRecord.isPartial()) {
        // it is implicit: history.latest.containsNone(lastN)
        segmentToSealPredicate = latestHistoryRecord.getSegments().containsAll(segmentsToSeal);
        assert !latestHistoryRecord.getSegments().isEmpty();
        exactMatchPredicate = latestHistoryRecord.getSegments().stream().max(Comparator.naturalOrder()).get()
                + n == getLastSegmentNumber(segmentTable);
    } else { // CASE 2: segment table updated.. history table updated (partial record)..
        // since latest is partial so previous has to exist
        HistoryRecord previousHistoryRecord = HistoryRecord.fetchPrevious(latestHistoryRecord, historyTable)
                .get();

        segmentToSealPredicate = latestHistoryRecord.getSegments()
                .containsAll(lastN.stream().map(SegmentRecord::getSegmentNumber).collect(Collectors.toList()))
                && previousHistoryRecord.getSegments().containsAll(segmentsToSeal);
        exactMatchPredicate = previousHistoryRecord.getSegments().stream().max(Comparator.naturalOrder()).get()
                + n == getLastSegmentNumber(segmentTable);
    }

    return newSegmentsPredicate && segmentToSealPredicate && exactMatchPredicate;
}

From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java

/**
 * Gets local files.//from  w  w w .j  a va2s  .c  o  m
 *
 * @param file the file
 * @return the local files
 */
public static List<CharSequence> getLocalFiles(CharSequence file) {
    File[] array = new File(file.toString()).listFiles();
    if (null == array)
        throw new IllegalArgumentException("Not Found: " + file);
    return Arrays.stream(array).map(File::getAbsolutePath).sorted(Comparator.naturalOrder())
            .collect(Collectors.toList());
}

From source file:com.netflix.genie.web.services.impl.JobSpecificationServiceImpl.java

/**
 * Helper to convert a set of tags into a string that is a suitable value for a shell environment variable.
 * Adds double quotes as necessary (i.e. in case of spaces, newlines), performs escaping of in-tag quotes.
 * Input tags are sorted to produce a deterministic output value.
 *
 * @param tags a set of tags or null//from   w  w w .  j  a v  a2s  .  c  om
 * @return a CSV string
 */
private String tagsToString(final Set<String> tags) {
    final List<String> sortedTags = Lists.newArrayList(tags);
    // Sort tags for the sake of determinism (e.g., tests)
    sortedTags.sort(Comparator.naturalOrder());
    final String joinedString = StringUtils.join(sortedTags, ',');
    // Escape quotes
    return RegExUtils.replaceAll(RegExUtils.replaceAll(joinedString, "\'", "\\\'"), "\"", "\\\"");
}

From source file:com.google.api.codegen.config.GapicProductConfig.java

/**
 * Create all the ResourceNameOneofConfig from the protofile and GAPIC config, and let the GAPIC
 * config resourceNames override the protofile resourceNames in event of clashes.
 *///w  w w.ja  va 2 s  .  c  om
@VisibleForTesting
@Nullable
static ImmutableMap<String, ResourceNameConfig> createResourceNameConfigs(DiagCollector diagCollector,
        ConfigProto configProto, @Nullable List<ProtoFile> protoFiles, TargetLanguage language,
        Map<Resource, ProtoFile> resourceDefs, Map<ResourceSet, ProtoFile> resourceSetDefs,
        ProtoParser protoParser) {
    ProtoFile file = null;
    if (protoFiles != null) {
        file = protoFiles.get(0);
    }
    ImmutableMap<String, SingleResourceNameConfig> singleResourceNameConfigsFromGapicConfig = createSingleResourceNameConfigs(
            diagCollector, configProto, protoFiles, language);
    ImmutableMap<String, FixedResourceNameConfig> fixedResourceNameConfigs = createFixedResourceNameConfigs(
            diagCollector, configProto.getFixedResourceNameValuesList(), file);
    ImmutableMap<String, ResourceNameOneofConfig> resourceNameOneofConfigsFromGapicConfig = createResourceNameOneofConfigs(
            diagCollector, configProto.getCollectionOneofsList(), singleResourceNameConfigsFromGapicConfig,
            fixedResourceNameConfigs, file);
    if (diagCollector.getErrorCount() > 0) {
        ToolUtil.reportDiags(diagCollector, true);
        return null;
    }

    ImmutableMap<String, SingleResourceNameConfig> fullyQualifiedSingleResourceNameConfigsFromProtoFile = createSingleResourceNameConfigsFromProtoFile(
            diagCollector, resourceDefs, protoParser);
    ImmutableMap<String, ResourceNameOneofConfig> resourceNameOneofConfigsFromProtoFile = createResourceNameOneofConfigsFromProtoFile(
            diagCollector, fullyQualifiedSingleResourceNameConfigsFromProtoFile, resourceSetDefs, protoParser);

    // Populate a SingleResourceNameConfigs map, using just the unqualified names.
    Map<String, SingleResourceNameConfig> singleResourceConfigsFromProtoFile = new HashMap<>();
    for (String fullName : fullyQualifiedSingleResourceNameConfigsFromProtoFile.keySet()) {
        int periodIndex = fullName.lastIndexOf('.');
        SingleResourceNameConfig config = fullyQualifiedSingleResourceNameConfigsFromProtoFile.get(fullName);
        singleResourceConfigsFromProtoFile.put(fullName.substring(periodIndex + 1), config);
    }

    // Combine the ResourceNameConfigs from the GAPIC and protofile.
    Map<String, SingleResourceNameConfig> finalSingleResourceNameConfigs = mergeResourceNameConfigs(
            diagCollector, singleResourceNameConfigsFromGapicConfig, singleResourceConfigsFromProtoFile);
    Map<String, ResourceNameOneofConfig> finalResourceOneofNameConfigs = mergeResourceNameConfigs(diagCollector,
            resourceNameOneofConfigsFromGapicConfig, resourceNameOneofConfigsFromProtoFile);

    ImmutableMap.Builder<String, ResourceNameConfig> resourceNameConfigs = new ImmutableSortedMap.Builder<>(
            Comparator.naturalOrder());
    resourceNameConfigs.putAll(finalSingleResourceNameConfigs);
    resourceNameConfigs.putAll(fixedResourceNameConfigs);
    resourceNameConfigs.putAll(finalResourceOneofNameConfigs);
    return resourceNameConfigs.build();
}

From source file:com.marand.thinkmed.medications.business.util.MedicationsEhrUtils.java

public static DateTime getLastModifiedTimestamp(final MedicationOrderComposition composition,
        final MedicationInstructionInstruction instruction) {
    final List<MedicationActionAction> actions = getInstructionActions(composition, instruction);
    return actions.stream().filter(
            action -> MedicationActionEnum.getActionEnum(action) == MedicationActionEnum.MODIFY_EXISTING)
            .map(action -> DataValueUtils.getDateTime(action.getTime())).max(Comparator.naturalOrder())
            .orElse(null);/*from  ww  w  .java2s .c o  m*/
}

From source file:com.marand.thinkmed.medications.business.impl.DefaultMedicationsBo.java

@Override
@Transactional//from ww  w .j  a  v a 2 s.c  o m
@ServiceMethod(auditing = @Auditing(level = Level.FULL))
public DateTime findPreviousTaskForTherapy(final String patientId, final String compositionUid,
        final String ehrOrderName, final DateTime when) {
    Pair<MedicationOrderComposition, MedicationInstructionInstruction> instructionPair = medicationsOpenEhrDao
            .getTherapyInstructionPair(patientId, compositionUid, ehrOrderName);

    while (instructionPair != null) {
        final List<AdministrationDto> administrations = administrationProvider
                .getTherapiesAdministrations(patientId, Collections.singletonList(instructionPair), null);

        final String therapyId = TherapyIdUtils.createTherapyId(instructionPair.getFirst(),
                instructionPair.getSecond());

        final DateTime lastTask = medicationsTasksProvider.findLastAdministrationTaskTimeForTherapy(patientId,
                therapyId, new Interval(when.minusDays(10), when), false).orElse(null);

        final DateTime lastAdministration = administrations.stream()
                .filter(a -> a.getAdministrationResult() != AdministrationResultEnum.NOT_GIVEN)
                .map(AdministrationDto::getAdministrationTime).max(Comparator.naturalOrder()).orElse(null);

        final DateTime lastTime = getMostRecent(lastTask, lastAdministration);
        if (lastTime != null) {
            return lastTime;
        }

        instructionPair = getInstructionFromLink(patientId, instructionPair.getSecond(), EhrLinkType.UPDATE,
                true);
    }
    return null;
}