Example usage for com.google.common.collect Ordering explicit

List of usage examples for com.google.common.collect Ordering explicit

Introduction

In this page you can find the example usage for com.google.common.collect Ordering explicit.

Prototype

@GwtCompatible(serializable = true)
public static <T> Ordering<T> explicit(List<T> valuesInOrder) 

Source Link

Document

Returns an ordering that compares objects according to the order in which they appear in the given list.

Usage

From source file:org.sonar.server.settings.ws.SettingsFinder.java

/**
 * Return list of settings by component uuid, sorted from project to lowest module
 *///from w  ww .j  av  a  2s  .co m
public Multimap<String, Setting> loadComponentSettings(DbSession dbSession, Set<String> keys,
        ComponentDto component) {
    List<String> componentUuids = DOT_SPLITTER.splitToList(component.moduleUuidPath());
    List<ComponentDto> componentDtos = dbClient.componentDao().selectByUuids(dbSession, componentUuids);
    Set<Long> componentIds = componentDtos.stream().map(ComponentDto::getId).collect(Collectors.toSet());
    Map<Long, String> uuidsById = componentDtos.stream()
            .collect(Collectors.toMap(ComponentDto::getId, ComponentDto::uuid));
    List<PropertyDto> properties = dbClient.propertiesDao().selectPropertiesByKeysAndComponentIds(dbSession,
            keys, componentIds);
    List<PropertyDto> propertySets = dbClient.propertiesDao().selectPropertiesByKeysAndComponentIds(dbSession,
            getPropertySetKeys(properties), componentIds);

    Multimap<String, Setting> settingsByUuid = TreeMultimap.create(Ordering.explicit(componentUuids),
            Ordering.arbitrary());
    for (PropertyDto propertyDto : properties) {
        Long componentId = propertyDto.getResourceId();
        String componentUuid = uuidsById.get(componentId);
        String propertyKey = propertyDto.getKey();
        settingsByUuid.put(componentUuid, Setting.createForDto(propertyDto,
                getPropertySets(propertyKey, propertySets, componentId), definitions.get(propertyKey)));
    }
    return settingsByUuid;
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericRacePositionsData.java

@Override
protected LinkedListMultimap<Integer, Pilot> calculateRacePositionsWithOrder(Race race) {
    // Create a lap order list containing all pilots
    List<Pilot> lapOrder = new ArrayList<Pilot>(scores.getPilots().size());
    lapOrder.addAll(scores.getLapOrder(race));
    Set<Pilot> pilotsWithLaps = ImmutableSet.copyOf(lapOrder);
    SortedSet<Pilot> pilotsWithoutLaps = new TreeSet<Pilot>(new PilotRaceNumberComparator());
    pilotsWithoutLaps.addAll(Sets.difference(scores.getPilots(), pilotsWithLaps));
    lapOrder.addAll(pilotsWithoutLaps);//from   w  ww .j a v a 2  s . com

    // Add penalties to race points
    Map<Pilot, Integer> racePoints = scores.getRacePoints(race);
    Map<Pilot, Integer> racePenalties = scores.getRacePenalties(race);
    Map<Pilot, Integer> racePointsWithPenalties = new HashMap<Pilot, Integer>(scores.getPilots().size() * 2);
    for (Pilot pilot : scores.getPilots()) {
        racePointsWithPenalties.put(pilot, racePoints.get(pilot) + racePenalties.get(pilot));
    }

    // Invert race points with ordered lists of pilots
    TreeMultimap<Integer, Pilot> invRacePoints = TreeMultimap.create(Ordering.natural(),
            Ordering.explicit(lapOrder));
    Multimaps.invertFrom(Multimaps.forMap(racePointsWithPenalties), invRacePoints);

    // Calculate race positions
    LinkedListMultimap<Integer, Pilot> racePositions = LinkedListMultimap.create();
    LinkedList<SortedSet<Pilot>> pilotPointsOrdering = new LinkedList<SortedSet<Pilot>>();
    int position = 1;

    if (simulatedToEnd) {
        Set<Pilot> simulatedRacePoints = scores.getSimulatedRacePoints(race);
        for (Integer points : invRacePoints.keySet()) {
            SortedSet<Pilot> pilots = Sets.filter(invRacePoints.get(points),
                    Predicates.not(Predicates.in(simulatedRacePoints)));
            if (!pilots.isEmpty()) {
                pilotPointsOrdering.add(pilots);
            }
        }
        for (Integer points : invRacePoints.keySet()) {
            SortedSet<Pilot> pilots = Sets.filter(invRacePoints.get(points),
                    Predicates.in(simulatedRacePoints));
            if (!pilots.isEmpty()) {
                pilotPointsOrdering.add(pilots);
            }
        }
    } else {
        for (Integer points : invRacePoints.keySet()) {
            pilotPointsOrdering.add(invRacePoints.get(points));
        }
    }

    for (SortedSet<Pilot> pilots : pilotPointsOrdering) {
        switch (equalPositioning) {
        case ALWAYS:
            // Always put pilots with the same points in the same position
            racePositions.putAll(position, pilots);
            position += pilots.size();
            break;

        case WITHOUT_LAPS:
            // Add everyone with laps (by removing pilots without laps from the set) in separate positions
            for (Pilot pilot : Sets.difference(pilots, pilotsWithoutLaps)) {
                racePositions.put(position, pilot);
                position++;
            }

            // Add everyone without laps (by removing pilots with laps from the set) in the same position
            Set<Pilot> pilots2 = Sets.difference(pilots, pilotsWithLaps);
            racePositions.putAll(position, pilots2);
            position += pilots2.size();
            break;

        case NEVER:
            // Always put pilots with the same points in separate positions
            for (Pilot pilot : pilots) {
                racePositions.put(position, pilot);
                position++;
            }
            break;
        }
    }

    return racePositions;
}

From source file:XFactHD.rfutilities.RFUtilities.java

@SuppressWarnings("unchecked")
private <F extends ItemStack> void initTabSorter() {
    List<Item> order = new ArrayList<>();
    order.add(Item.getItemFromBlock(RFUContent.blockCapacitor));
    order.add(Item.getItemFromBlock(RFUContent.blockSwitch));
    order.add(Item.getItemFromBlock(RFUContent.blockResistor));
    order.add(Item.getItemFromBlock(RFUContent.blockDiode));
    order.add(Item.getItemFromBlock(RFUContent.blockTransistor));
    order.add(Item.getItemFromBlock(RFUContent.blockRFMeter));
    order.add(Item.getItemFromBlock(RFUContent.blockInvisTess));
    order.add(RFUContent.itemDialer);// ww  w .  j a  v  a 2s.c  om
    order.add(RFUContent.itemMultimeter);
    order.add(RFUContent.itemMaterial);
    Function<F, Item> sorter = new Function<F, Item>() {
        @Nullable
        @Override
        public Item apply(F input) {
            return input.getItem();
        }
    };
    tabSorter = Ordering.explicit(order).onResultOf((Function<ItemStack, ? extends Item>) sorter);
}

From source file:com.mgmtp.perfload.perfalyzer.reporting.ReportCreator.java

public void createReport(final List<PerfAlyzerFile> files) throws IOException {
    Function<PerfAlyzerFile, String> classifier = perfAlyzerFile -> {
        String marker = perfAlyzerFile.getMarker();
        return marker == null ? "Overall" : marker;
    };/*from  ww w  .  ja v a 2  s .  c om*/
    Supplier<Map<String, List<PerfAlyzerFile>>> mapFactory = () -> new TreeMap<>(Ordering.explicit(tabNames));

    Map<String, List<PerfAlyzerFile>> filesByMarker = files.stream()
            .collect(Collectors.groupingBy(classifier, mapFactory, toList()));

    Map<String, SortedSetMultimap<String, PerfAlyzerFile>> contentItemFiles = new LinkedHashMap<>();

    for (Entry<String, List<PerfAlyzerFile>> entry : filesByMarker.entrySet()) {
        SortedSetMultimap<String, PerfAlyzerFile> contentItemFilesByMarker = contentItemFiles.computeIfAbsent(
                entry.getKey(),
                s -> TreeMultimap.create(new ItemComparator(reportContentsConfigMap.get("priorities")),
                        Ordering.natural()));

        for (PerfAlyzerFile perfAlyzerFile : entry.getValue()) {
            File file = perfAlyzerFile.getFile();
            String groupKey = removeExtension(file.getPath());
            boolean excluded = false;
            for (Pattern pattern : reportContentsConfigMap.get("exclusions")) {
                Matcher matcher = pattern.matcher(groupKey);
                if (matcher.matches()) {
                    excluded = true;
                    log.debug("Excluded from report: {}", groupKey);
                    break;
                }
            }
            if (!excluded) {
                contentItemFilesByMarker.put(groupKey, perfAlyzerFile);
            }
        }
    }

    // explicitly copy it because it is otherwise filtered from the report in order to only show in the overview
    String loadProfilePlot = new File("console", "[loadprofile].png").getPath();
    copyFile(new File(soureDir, loadProfilePlot), new File(destDir, loadProfilePlot));

    Map<String, List<ContentItem>> tabItems = new LinkedHashMap<>();
    Map<String, QuickJump> quickJumps = new HashMap<>();
    Set<String> tabNames = contentItemFiles.keySet();

    for (Entry<String, SortedSetMultimap<String, PerfAlyzerFile>> tabEntry : contentItemFiles.entrySet()) {
        String tab = tabEntry.getKey();
        SortedSetMultimap<String, PerfAlyzerFile> filesForTab = tabEntry.getValue();

        List<ContentItem> contentItems = tabItems.computeIfAbsent(tab, list -> new ArrayList<>());
        Map<String, String> quickJumpMap = new LinkedHashMap<>();
        quickJumps.put(tab, new QuickJump(tab, quickJumpMap));

        int itemIndex = 0;
        for (Entry<String, Collection<PerfAlyzerFile>> itemEntry : filesForTab.asMap().entrySet()) {
            String title = itemEntry.getKey();
            Collection<PerfAlyzerFile> itemFiles = itemEntry.getValue();

            TableData tableData = null;
            String plotSrc = null;
            for (PerfAlyzerFile file : itemFiles) {
                if ("png".equals(getExtension(file.getFile().getName()))) {
                    plotSrc = file.getFile().getPath();
                    copyFile(new File(soureDir, plotSrc), new File(destDir, plotSrc));
                } else {
                    tableData = createTableData(file.getFile());
                }
            }

            // strip off potential marker
            title = substringBefore(title, "{");

            String[] titleParts = split(title, SystemUtils.FILE_SEPARATOR);
            StringBuilder sb = new StringBuilder(50);
            String separator = " - ";
            sb.append(resourceBundle.getString(titleParts[0]));
            sb.append(separator);
            sb.append(resourceBundle.getString(titleParts[1]));

            List<String> fileNameParts = extractFileNameParts(titleParts[1], true);
            if (titleParts[1].contains("[distribution]")) {
                String operation = fileNameParts.get(1);
                sb.append(separator);
                sb.append(operation);
            } else if ("comparison".equals(titleParts[0])) {
                String operation = fileNameParts.get(1);
                sb.append(separator);
                sb.append(operation);
            } else if (titleParts[1].contains("[gclog]")) {
                if (fileNameParts.size() > 1) {
                    sb.append(separator);
                    sb.append(fileNameParts.get(1));
                }
            }

            title = sb.toString();
            ContentItem item = new ContentItem(tab, itemIndex, title, tableData, plotSrc,
                    resourceBundle.getString("report.topLink"));
            contentItems.add(item);

            quickJumpMap.put(tab + "_" + itemIndex, title);
            itemIndex++;
        }
    }

    NavBar navBar = new NavBar(tabNames, quickJumps);
    String testName = removeExtension(testMetadata.getTestPlanFile());
    OverviewItem overviewItem = new OverviewItem(testMetadata, resourceBundle, locale);
    Content content = new Content(tabItems);

    String perfAlyzerVersion;
    try {
        perfAlyzerVersion = Resources.toString(Resources.getResource("perfAlyzer.version"), Charsets.UTF_8);
    } catch (IOException ex) {
        log.error("Could not read perfAlyzer version from classpath resource 'perfAlyzer.version'", ex);
        perfAlyzerVersion = "";
    }

    String dateTimeString = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(locale)
            .format(ZonedDateTime.now());
    String createdString = String.format(resourceBundle.getString("footer.created"), perfAlyzerVersion,
            dateTimeString);
    HtmlSkeleton html = new HtmlSkeleton(testName, createdString, navBar, overviewItem, content);
    writeReport(html);
}

From source file:org.sonar.server.organization.ws.SearchMembersAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    try (DbSession dbSession = dbClient.openSession(false)) {
        OrganizationDto organization = getOrganization(dbSession, request.param("organization"));

        UserQuery.Builder userQuery = buildUserQuery(request, organization);
        SearchOptions searchOptions = buildSearchOptions(request);

        SearchResult<UserDoc> searchResults = userIndex.search(userQuery.build(), searchOptions);
        List<String> orderedLogins = searchResults.getDocs().stream().map(UserDoc::login)
                .collect(MoreCollectors.toList());

        List<UserDto> users = dbClient.userDao().selectByLogins(dbSession, orderedLogins).stream()
                .sorted(Ordering.explicit(orderedLogins).onResultOf(UserDto::getLogin))
                .collect(MoreCollectors.toList());

        Multiset<String> groupCountByLogin = null;
        if (userSession.hasPermission(OrganizationPermission.ADMINISTER, organization)) {
            groupCountByLogin = dbClient.groupMembershipDao().countGroupByLoginsAndOrganization(dbSession,
                    orderedLogins, organization.getUuid());
        }/*from w  w  w  .  j a  v  a 2  s. c o m*/

        Common.Paging wsPaging = buildWsPaging(request, searchResults);
        SearchMembersWsResponse wsResponse = buildResponse(users, wsPaging, groupCountByLogin);

        writeProtobuf(wsResponse, request, response);
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.AbstractEntityService.java

/** {@inheritDoc} */
public List<E> reload(Collection<E> identifiers) {
    if ((identifiers == null) || identifiers.isEmpty()) {
        return new ArrayList<E>(0);
    }/*from   w w  w . ja  v  a 2s.c  o m*/

    EntityToIdFunction<E, T> toIdFunction = new EntityToIdFunction<E, T>();
    Iterable<T> transform = Iterables.transform(identifiers, toIdFunction);

    List<E> loadElementListWithIds = getDao().loadElementListWithIds(Sets.newHashSet(transform));
    Collections.sort(loadElementListWithIds, Ordering.explicit(Lists.newArrayList(identifiers)));

    return loadElementListWithIds;
}

From source file:org.guavafx.ObservableLists.java

/**
 * Returns an unmodifiable view of the given ObservableList, where all
 * modifications are optimized./* www. j  a  va 2s .c  o m*/
 * 
 * @param originalList
 * @return
 */
public static <E> ObservableList<E> optimize(final ObservableList<E> originalList) {
    final ListeningList<E, E> listeningList = new ListeningList<>(originalList);
    final InvalidationListener listener = new InvalidationListener() {
        private int syncNumber = 0;

        private void synchronize(int sync) {
            if (syncNumber == sync) {
                listeningList.list.retainAll(originalList);

                Ordering<E> ordering = Ordering.explicit(originalList);
                FXCollections.sort(listeningList.list, ordering);

                List<E> elementsToAdd = Lists
                        .newArrayList(Iterables.filter(originalList, not(in(listeningList.list))));
                Collections.sort(elementsToAdd, ordering);
                for (E element : elementsToAdd) {
                    listeningList.list.add(originalList.indexOf(element), element);
                }
            }
        }

        @Override
        public void invalidated(Observable _) {
            final int nextSync = ++syncNumber;
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    synchronize(nextSync);
                }
            });
        }
    };
    listeningList.addListener(listener);
    listeningList.list.setAll(originalList);

    return listeningList.readOnlyList;
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericRaceLapsData.java

@Override
protected List<Pilot> calculateRaceLapsInOrder(Race race, Map<Pilot, Integer> laps) {
    ListMultimap<Integer, Pilot> raceOrder = ArrayListMultimap.create(EXPECTED_MAXIMUM_LAPS,
            scores.getPilots().size());/*  w  ww . j av a 2 s .  co  m*/

    extractRaceLaps(race, laps, raceOrder, null);

    // Get penalties for each pilot
    ListMultimap<Pilot, Penalty> cancelLaps = ArrayListMultimap.create(EXPECTED_MAXIMUM_PENALTIES,
            scores.getPilots().size());
    ListMultimap<Pilot, Penalty> adjustLaps = ArrayListMultimap.create(EXPECTED_MAXIMUM_PENALTIES,
            scores.getPilots().size());
    for (RaceAttendee attendee : Maps.filterKeys(race.getAttendees(), Predicates.in(scores.getPilots()))
            .values()) {
        for (Penalty penalty : Iterables.concat(Ordering.natural().immutableSortedCopy(attendee.getPenalties()),
                scores.getSimulatedRacePenalties(attendee.getPilot(), race))) {
            if (penalty.getValue() != 0) {
                switch (penalty.getType()) {
                case CANCEL_LAPS:
                    cancelLaps.put(attendee.getPilot(), penalty);
                    break;

                case ADJUST_LAPS:
                    adjustLaps.put(attendee.getPilot(), penalty);
                    break;

                default:
                    break;
                }
            }
        }
    }

    // Apply lap cancellation penalties
    if (!cancelLaps.isEmpty()) {
        final Multiset<Pilot> pilotLaps = HashMultiset.create(laps.size());

        for (Map.Entry<Pilot, Integer> pilotLapCount : laps.entrySet()) {
            pilotLaps.setCount(pilotLapCount.getKey(), pilotLapCount.getValue());
        }

        for (Map.Entry<Pilot, Penalty> entry : cancelLaps.entries()) {
            int value = entry.getValue().getValue();
            if (value > 0) {
                pilotLaps.remove(entry.getKey(), value);
            } else {
                pilotLaps.add(entry.getKey(), Math.abs(value));
            }
        }

        extractRaceLaps(race, laps, raceOrder, new Predicate<Pilot>() {
            @Override
            public boolean apply(@Nullable Pilot pilot) {
                return pilotLaps.remove(pilot);
            }
        });
    }

    // Save pilot order
    List<Pilot> origPilotOrder = getPilotOrder(raceOrder);
    SortedSet<Pilot> noLaps = new TreeSet<Pilot>(new PilotRaceNumberComparator());
    Set<Integer> changed = new HashSet<Integer>();

    // It is intentional that pilots can end up having 0 laps but be considered to have completed the race
    for (Map.Entry<Pilot, Penalty> entry : adjustLaps.entries()) {
        Pilot pilot = entry.getKey();
        int lapCount = laps.get(pilot);

        raceOrder.remove(lapCount, pilot);
        changed.add(lapCount);

        lapCount += entry.getValue().getValue();
        if (lapCount <= 0) {
            lapCount = 0;
            noLaps.add(pilot);
        }
        laps.put(pilot, lapCount);

        raceOrder.put(lapCount, pilot);
        changed.add(lapCount);
    }

    // Apply original pilot order
    if (!changed.isEmpty()) {
        origPilotOrder.addAll(noLaps);

        for (Integer lapCount : changed) {
            raceOrder.replaceValues(lapCount,
                    Ordering.explicit(origPilotOrder).immutableSortedCopy(raceOrder.get(lapCount)));
        }

        return getPilotOrder(raceOrder);
    } else {
        return origPilotOrder;
    }
}

From source file:org.nuxeo.ecm.core.storage.dbs.DBSCachingRepository.java

@Override
public List<State> readStates(List<String> ids) {
    ImmutableMap<String, State> statesMap = cache.getAllPresent(ids);
    List<String> idsToRetrieve = new ArrayList<>(ids);
    idsToRetrieve.removeAll(statesMap.keySet());
    // Read missing states from repository
    List<State> states = repository.readStates(idsToRetrieve);
    // Cache them
    states.forEach(this::putInCache);
    // Add previous cached one
    states.addAll(statesMap.values());/*from w  ww  . j  a  va2s  . c om*/
    // Sort them
    states.sort(Comparator.comparing(state -> state.get(KEY_ID).toString(), Ordering.explicit(ids)));
    return states;
}

From source file:org.atlasapi.application.v3.ApplicationConfiguration.java

public Ordering<Publisher> publisherPrecedenceOrdering() {
    return Ordering.explicit(precedence);
}