Example usage for com.google.common.collect TreeMultimap create

List of usage examples for com.google.common.collect TreeMultimap create

Introduction

In this page you can find the example usage for com.google.common.collect TreeMultimap create.

Prototype

public static <K, V> TreeMultimap<K, V> create(Comparator<? super K> keyComparator,
        Comparator<? super V> valueComparator) 

Source Link

Document

Creates an empty TreeMultimap instance using explicit comparators.

Usage

From source file:org.onosproject.rest.resources.MetricsWebResource.java

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 (Map.Entry<String, Counter> entry : counters.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }/*from   w ww.j  a v a2 s.c  om*/
    Map<String, Gauge> gauges = metricsService.getGauges(filter);
    for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }
    Map<String, Histogram> histograms = metricsService.getHistograms(filter);
    for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }
    Map<String, Meter> meters = metricsService.getMeters(filter);
    for (Map.Entry<String, Meter> entry : meters.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }
    Map<String, Timer> timers = metricsService.getTimers(filter);
    for (Map.Entry<String, Timer> entry : timers.entrySet()) {
        metrics.put(entry.getKey(), entry.getValue());
    }

    return metrics;
}

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

/**
 * Return list of settings by component uuid, sorted from project to lowest module
 *///from www  . j a  v  a 2 s .c o 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.createFromDto(propertyDto,
                getPropertySets(propertyKey, propertySets, componentId), definitions.get(propertyKey)));
    }
    return settingsByUuid;
}

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 w w  . j ava 2 s.c  o 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:com.facebook.buck.apple.toolchain.impl.AppleSdkDiscovery.java

/**
 * Given a path to an Xcode developer directory and a map of (xctoolchain ID: path) pairs as
 * returned by {@link AppleToolchainDiscovery}, walks through the platforms and builds a map of
 * ({@link AppleSdk}: {@link AppleSdkPaths}) objects describing the paths to the SDKs inside.
 *
 * <p>The {@link AppleSdk#getName()} strings match the ones displayed by {@code xcodebuild
 * -showsdks} and look like {@code macosx10.9}, {@code iphoneos8.0}, {@code iphonesimulator8.0},
 * etc./*from   w  w  w  .  ja  va2 s . c  om*/
 */
public static ImmutableMap<AppleSdk, AppleSdkPaths> discoverAppleSdkPaths(Optional<Path> developerDir,
        ImmutableList<Path> extraDirs, ImmutableMap<String, AppleToolchain> xcodeToolchains,
        AppleConfig appleConfig) throws IOException {
    Optional<AppleToolchain> defaultToolchain = Optional.ofNullable(xcodeToolchains.get(DEFAULT_TOOLCHAIN_ID));

    ImmutableMap.Builder<AppleSdk, AppleSdkPaths> appleSdkPathsBuilder = ImmutableMap.builder();

    HashSet<Path> platformPaths = new HashSet<Path>(extraDirs);
    if (developerDir.isPresent()) {
        Path platformsDir = developerDir.get().resolve("Platforms");
        LOG.debug("Searching for Xcode platforms under %s", platformsDir);
        platformPaths.add(platformsDir);
    }

    // We need to find the most recent SDK for each platform so we can
    // make the fall-back SDKs with no version number in their name
    // ("macosx", "iphonesimulator", "iphoneos").
    //
    // To do this, we store a map of (platform: [sdk1, sdk2, ...])
    // pairs where the SDKs for each platform are ordered by version.
    TreeMultimap<ApplePlatform, AppleSdk> orderedSdksForPlatform = TreeMultimap.create(Ordering.natural(),
            APPLE_SDK_VERSION_ORDERING);

    for (Path platforms : platformPaths) {
        if (!Files.exists(platforms)) {
            LOG.debug("Skipping platform search path %s that does not exist", platforms);
            continue;
        }
        LOG.debug("Searching for Xcode SDKs in %s", platforms);

        try (DirectoryStream<Path> platformStream = Files.newDirectoryStream(platforms, "*.platform")) {
            for (Path platformDir : platformStream) {
                Path developerSdksPath = platformDir.resolve("Developer/SDKs");
                try (DirectoryStream<Path> sdkStream = Files.newDirectoryStream(developerSdksPath, "*.sdk")) {
                    Set<Path> scannedSdkDirs = new HashSet<>();
                    for (Path sdkDir : sdkStream) {
                        LOG.debug("Fetching SDK name for %s", sdkDir);

                        try {
                            sdkDir = sdkDir.toRealPath();
                        } catch (NoSuchFileException e) {
                            LOG.warn(e, "SDK at path %s is a dangling link, ignoring", sdkDir);
                            continue;
                        }
                        if (scannedSdkDirs.contains(sdkDir)) {
                            LOG.debug("Skipping already scanned SDK directory %s", sdkDir);
                            continue;
                        }

                        AppleSdk.Builder sdkBuilder = AppleSdk.builder();
                        if (buildSdkFromPath(sdkDir, sdkBuilder, xcodeToolchains, defaultToolchain,
                                appleConfig)) {
                            AppleSdk sdk = sdkBuilder.build();
                            LOG.debug("Found SDK %s", sdk);

                            AppleSdkPaths.Builder xcodePathsBuilder = AppleSdkPaths.builder();
                            for (AppleToolchain toolchain : sdk.getToolchains()) {
                                xcodePathsBuilder.addToolchainPaths(toolchain.getPath());
                            }
                            AppleSdkPaths xcodePaths = xcodePathsBuilder.setDeveloperPath(developerDir)
                                    .setPlatformPath(platformDir).setSdkPath(sdkDir).build();
                            appleSdkPathsBuilder.put(sdk, xcodePaths);
                            orderedSdksForPlatform.put(sdk.getApplePlatform(), sdk);
                        }
                        scannedSdkDirs.add(sdkDir);
                    }
                } catch (NoSuchFileException e) {
                    LOG.warn(e, "Couldn't discover SDKs at path %s, ignoring platform %s", developerSdksPath,
                            platformDir);
                }
            }
        }
    }

    // Get a snapshot of what's in appleSdkPathsBuilder, then for each
    // ApplePlatform, add to appleSdkPathsBuilder the most recent
    // SDK with an unversioned name.
    ImmutableMap<AppleSdk, AppleSdkPaths> discoveredSdkPaths = appleSdkPathsBuilder.build();

    for (ApplePlatform platform : orderedSdksForPlatform.keySet()) {
        Set<AppleSdk> platformSdks = orderedSdksForPlatform.get(platform);
        boolean shouldCreateUnversionedSdk = true;
        for (AppleSdk sdk : platformSdks) {
            shouldCreateUnversionedSdk &= !sdk.getName().equals(platform.getName());
        }

        if (shouldCreateUnversionedSdk) {
            AppleSdk mostRecentSdkForPlatform = orderedSdksForPlatform.get(platform).last();
            appleSdkPathsBuilder.put(mostRecentSdkForPlatform.withName(platform.getName()),
                    discoveredSdkPaths.get(mostRecentSdkForPlatform));
        }
    }

    // This includes both the discovered SDKs with versions in their names, as well as
    // the unversioned aliases added just above.
    return appleSdkPathsBuilder.build();
}

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 va  2s . c  o m*/

    // 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:de.anycook.db.mysql.DBSearch.java

public SortedSetMultimap<Integer, String> getRecipesWithoutIngredient(String ingredient) throws SQLException {
    SortedSetMultimap<Integer, String> recipes = TreeMultimap.create(new InvertedComparator<Integer>(),
            new InvertedComparator<String>());
    PreparedStatement pStatement = connection.prepareStatement(
            "SELECT gerichte2.name, COUNT(schmeckt.users_id) AS schmecktcount FROM gerichte AS gerichte2 "
                    + "LEFT JOIN schmeckt ON gerichte2.name = schmeckt.gerichte_name "
                    + "WHERE gerichte2.name NOT IN (" + "SELECT gerichte.name FROM gerichte "
                    + "INNER JOIN versions ON gerichte.name = versions.gerichte_name AND gerichte.active_id = versions.id "
                    + "INNER JOIN versions_has_zutaten ON versions.gerichte_name = versions_gerichte_name AND id = versions_id "
                    + "WHERE zutaten_name = ?) " + "GROUP BY gerichte2.name");
    pStatement.setString(1, ingredient);
    try (ResultSet data = pStatement.executeQuery()) {
        while (data.next())
            recipes.put(data.getInt("schmecktcount"), data.getString("gerichte2.name"));
    }//from   w  ww . j  av  a 2 s . c om

    return recipes;
}

From source file:bio.gcat.operation.Operation.java

public static Multimap<String, Class<? extends Operation>> getGroups() {
    Multimap<String, Class<? extends Operation>> groups = TreeMultimap.create(Comparator.reverseOrder(),
            new Comparator<Class<? extends Operation>>() {
                @Override//from   w w  w .j a v  a  2  s  .  c  o  m
                public int compare(Class<? extends Operation> operationA,
                        Class<? extends Operation> operationB) {
                    Cataloged catalogedA = operationA.getAnnotation(Cataloged.class),
                            catalogedB = operationB.getAnnotation(Cataloged.class);
                    int orderA = catalogedA != null ? catalogedA.order() : Short.MAX_VALUE,
                            orderB = catalogedB != null ? catalogedB.order() : Short.MAX_VALUE;
                    return orderA != orderB ? Integer.compare(orderA, orderB)
                            : operationA.getSimpleName().compareTo(operationB.getSimpleName());
                }
            });
    for (Class<? extends Operation> operation : getOperations(true))
        groups.put(operation.getAnnotation(Cataloged.class).group(), operation);
    return groups;
}

From source file:org.opendaylight.yangtools.yang.model.util.FilteringSchemaContextProxy.java

private static TreeMultimap<String, Module> getStringModuleTreeMultimap() {
    return TreeMultimap.create(String::compareTo, REVISION_COMPARATOR);
}

From source file:org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.module.VirtualMachineCpuAnalysis.java

private static Multimap<Integer, ITmfStateInterval> createThreadMultimap() {

    /*/*from   ww  w .  jav a  2  s.  com*/
     * Create the multimap for threads with the appropriate comparator
     * objects for keys and values
     */
    final Multimap<Integer, ITmfStateInterval> map = TreeMultimap.create(
            /* Key comparator. Keys do not have to be sorted, just use natural sorting*/
            Comparator.naturalOrder(),

            /* Value comparator */
            (arg0, arg1) -> {
                if (arg1.getStateValue() == VCPU_PREEMPT_VALUE && arg0.getStateValue() != VCPU_PREEMPT_VALUE) {
                    /*
                     * For VCPU_PREEMPT state values, the state has to be
                     * after any other state that it overlaps, because those
                     * intervals usually decorate the other intervals.
                     */
                    if (((Long) arg0.getEndTime()).compareTo(arg1.getStartTime()) < 0) {
                        return -1;
                    }
                    return ((Long) arg0.getStartTime()).compareTo(arg1.getEndTime());
                }
                /* Otherwise, we use ordering by start time */
                return (((Long) arg0.getStartTime()).compareTo(arg1.getStartTime()));
            });
    return map;
}

From source file:org.eclipse.linuxtools.internal.tmf.ui.project.handlers.DeleteTraceSupplementaryFilesHandler.java

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    // Check if we are closing down
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window == null) {
        return null;
    }//from  ww w  . j ava  2 s. c o  m

    // Get the selection
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    if (!(selection instanceof IStructuredSelection)) {
        return null;
    }
    final Multimap<TmfCommonProjectElement, IResource> resourceMap = TreeMultimap
            .create(new ElementComparator(), new ResourceComparator());
    final Iterator<Object> iterator = ((IStructuredSelection) selection).iterator();

    while (iterator.hasNext()) {
        Object element = iterator.next();
        if (element instanceof TmfTraceElement) {
            TmfTraceElement trace = (TmfTraceElement) element;
            // If trace is under an experiment, use the original trace from the traces folder
            trace = trace.getElementUnderTraceFolder();
            for (IResource resource : trace.getSupplementaryResources()) {
                resourceMap.put(trace, resource);
            }

        } else if (element instanceof TmfExperimentElement) {
            TmfExperimentElement experiment = (TmfExperimentElement) element;
            for (IResource resource : experiment.getSupplementaryResources()) {
                resourceMap.put(experiment, resource);
            }
            for (TmfTraceElement trace : experiment.getTraces()) {
                // If trace is under an experiment, use the original trace from the traces folder
                trace = trace.getElementUnderTraceFolder();
                for (IResource resource : trace.getSupplementaryResources()) {
                    resourceMap.put(trace, resource);
                }
            }
        }
    }

    final SelectSupplementaryResourcesDialog dialog = new SelectSupplementaryResourcesDialog(window.getShell(),
            resourceMap);
    if (dialog.open() != Window.OK) {
        return null;
    }

    TmfWorkspaceModifyOperation operation = new TmfWorkspaceModifyOperation() {
        @Override
        public void execute(IProgressMonitor monitor) throws CoreException {

            Set<IProject> projectsToRefresh = new HashSet<>();

            // Delete the resources that were selected
            List<IResource> allResourcesToDelete = Arrays.asList(dialog.getResources());

            SubMonitor subMonitor = SubMonitor.convert(monitor, allResourcesToDelete.size());

            for (TmfCommonProjectElement element : resourceMap.keySet()) {
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
                List<IResource> traceResourcesToDelete = new ArrayList<>(resourceMap.get(element));
                traceResourcesToDelete.retainAll(allResourcesToDelete);
                if (!traceResourcesToDelete.isEmpty()) {
                    subMonitor.setTaskName(
                            NLS.bind(Messages.DeleteSupplementaryFiles_DeletionTask, element.getElementPath()));
                    // Delete the selected resources
                    element.closeEditors();
                    element.deleteSupplementaryResources(traceResourcesToDelete.toArray(new IResource[0]));
                    projectsToRefresh.add(element.getProject().getResource());
                }
                subMonitor.worked(traceResourcesToDelete.size());
            }

            subMonitor = SubMonitor.convert(monitor, projectsToRefresh.size());

            // Refresh projects
            Iterator<IProject> projectIterator = projectsToRefresh.iterator();
            while (projectIterator.hasNext()) {
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
                IProject project = projectIterator.next();
                subMonitor.setTaskName(
                        NLS.bind(Messages.DeleteSupplementaryFiles_ProjectRefreshTask, project.getName()));
                try {
                    project.refreshLocal(IResource.DEPTH_INFINITE, null);
                } catch (CoreException e) {
                    Activator.getDefault().logError("Error refreshing project " + project, e); //$NON-NLS-1$
                }
                subMonitor.worked(1);
            }
        }
    };

    try {
        PlatformUI.getWorkbench().getProgressService().run(true, true, operation);
    } catch (InterruptedException e) {
        return null;
    } catch (InvocationTargetException e) {
        MessageDialog.openError(window.getShell(), e.toString(), e.getTargetException().toString());
        return null;
    }
    return null;
}