Example usage for com.google.common.collect Maps transformValues

List of usage examples for com.google.common.collect Maps transformValues

Introduction

In this page you can find the example usage for com.google.common.collect Maps transformValues.

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap,
        Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a navigable map where each value is transformed by a function.

Usage

From source file:ninja.leaping.permissionsex.backend.memory.MemorySubjectData.java

@Override
public Map<Set<Entry<String, String>>, Map<String, Integer>> getAllPermissions() {
    return Maps.filterValues(
            Maps.transformValues(contexts, dataEntry -> dataEntry == null ? null : dataEntry.permissions),
            o -> o != null);//from www .j  ava2 s  . co  m
}

From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.GenericLogicDiscoverer.java

/**
 * Generic implementation for finding all the Services or Operations that have SOME of the given types as inputs or outputs.
 *
 * @param entityType   the MSM URI of the type of entity we are looking for. Only supports Service and Operation.
 * @param relationship the MSM URI of the relationship we are looking for. Only supports hasInput and hasOutput.
 * @param types        the input/output types (modelReferences that is) we are looking for
 * @return a Map mapping operation/services URIs to MatchResults.
 *//*from  w  w w . ja  v  a2 s  . c  o  m*/
private Map<URI, MatchResult> findSome(URI entityType, URI relationship, Set<URI> types) {

    // Ensure that we have been given correct parameters
    if (types == null || types.isEmpty()
            || (!entityType.toASCIIString().equals(MSM.Service.getURI())
                    && !entityType.toASCIIString().equals(MSM.Operation.getURI()))
            || (!relationship.toASCIIString().equals(MSM.hasInput.getURI())
                    && !entityType.toASCIIString().equals(MSM.hasOutput.getURI())
                    && !relationship.toASCIIString().equals(SAWSDL.modelReference.getURI()))) {

        return ImmutableMap.of();
    }

    // Expand the input types to get all that match enough to be consumed
    // TODO: The leastOfType should be configurable
    Table<URI, URI, MatchResult> expandedTypes;
    if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) {
        expandedTypes = HashBasedTable.create();
        //TODO: fix this properly
        for (URI type : types) {
            expandedTypes.putAll(this.conceptMatcher.listMatchesAtMostOfType(ImmutableSet.of(type),
                    LogicConceptMatchType.Subsume));
            expandedTypes.putAll(
                    this.conceptMatcher.listMatchesOfType(ImmutableSet.of(type), LogicConceptMatchType.Exact));
        }

    } else {
        expandedTypes = this.conceptMatcher.listMatchesAtLeastOfType(types, LogicConceptMatchType.Plugin);
    }

    // Track all the results in a multimap to push the details up the stack
    Multimap<URI, MatchResult> result = ArrayListMultimap.create();

    // Find all the entities with modelReferences to the expanded types
    // The column view is the one with all the possible matches since a class will always match itself
    Map<URI, Map<URI, MatchResult>> columnMap = expandedTypes.columnMap();
    for (URI type : columnMap.keySet()) {
        Set<URI> entities = ImmutableSet.of();
        if (relationship.toASCIIString().equals(SAWSDL.modelReference.getURI())) {
            entities = listEntitesWithModelReference(entityType, type);
        } else if (relationship.toASCIIString().equals(MSM.hasInput.getURI())
                || relationship.toASCIIString().equals(MSM.hasOutput.getURI())) {
            entities = listEntitiesWithType(entityType, relationship, type);
        }

        for (URI entity : entities) {
            result.putAll(entity, columnMap.get(type).values());
        }
    }

    // Merge the results into a single map using Union
    return Maps.transformValues(result.asMap(), MatchResultsMerger.UNION);

}

From source file:com.cloudera.director.aws.ec2.VirtualizationMappings.java

/**
 * Gets a test instance of this class that uses only the given mapping.
 *
 * @param instanceTypes       map of virtualization types to instance types
 * @param localizationContext the localization context
 * @return new mapping object/*from  w  w w.j av a 2 s  .  c  om*/
 */
public static VirtualizationMappings getTestInstance(final Map<String, List<String>> instanceTypes,
        LocalizationContext localizationContext) {
    Map<String, String> propertyMap = Maps.transformValues(instanceTypes, new Function<List<String>, String>() {
        @Override
        public String apply(@Nonnull List<String> input) {
            return JOINER.join(input);
        }
    });
    PropertyResolver virtualizationMappingsResolver = PropertyResolvers.newMapPropertyResolver(propertyMap);
    File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();
    VirtualizationMappingsConfigProperties virtualizationMappingsConfigProperties = new VirtualizationMappingsConfigProperties(
            new SimpleConfiguration(), tempDir, localizationContext);
    return new VirtualizationMappings(virtualizationMappingsConfigProperties, virtualizationMappingsResolver);
}

From source file:org.bitstrings.maven.plugins.portallocator.PortAllocatorMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*  ww w  . ja va  2s .c om*/
        if (portAllocators != null) {
            for (PortAllocator portAllocator : portAllocators) {
                initPortAllocator(portAllocator);

                final PortAllocatorService existingPas = PORT_ALLOCATOR_SERVICE_MAP.get(portAllocator.getId());

                if (portAllocator.isPermitOverride() || (existingPas == null)
                        || (portAllocator.getId().equals(PORT_ALLOCATOR_DEFAULT_ID)
                                && (existingPas == PORT_ALLOCATOR_SERVICE_DEFAULT))) {
                    PORT_ALLOCATOR_SERVICE_MAP.put(portAllocator.getId(),
                            createPortAllocatorService(portAllocator));

                    if (!quiet && getLog().isInfoEnabled()) {
                        getLog().info("Registering port allocator [" + portAllocator.getId() + "]");
                    }
                }
            }
        }

        if (ports != null) {
            if ((ports.getPortAllocatorRef() != null) && (ports.getPortAllocator() != null)) {
                throw new MojoExecutionException(
                        "Either use a port allocator reference or define an inner allocator but you can use both.");
            }

            PortAllocatorService pas = ports.getPortAllocator() == null
                    ? PORT_ALLOCATOR_SERVICE_MAP
                            .get(firstNonNull(ports.getPortAllocatorRef(), PORT_ALLOCATOR_DEFAULT_ID))
                    : createPortAllocatorService(initPortAllocator(ports.getPortAllocator()));

            if (pas == null) {
                throw new MojoExecutionException(
                        "Cannot find port allocator [" + ports.getPortAllocatorRef() + "]");
            }

            // assign
            final LinkedListMultimap<String, Port> portGroupMap = LinkedListMultimap.create();

            for (Port port : ports) {
                final String offsetFrom = port.getOffsetFrom();
                final String portGroupName = findGroupRoot(port, portGroupMap);

                portGroupMap.put(portGroupName, port);

                if ((offsetFrom != null) && !executionPortMap.containsKey(getPortName(portGroupName))) {
                    throw new MojoExecutionException(
                            "Port [" + port.getName() + "] using offset from undefined [" + offsetFrom + "].");
                }

                Iterator<Port> portIterator = Iterators.singletonIterator(port);

                while (portIterator.hasNext()) {
                    final Port portToAllocate = portIterator.next();

                    final Integer previousPort = executionPortMap.remove(getPortName(portToAllocate.getName()));
                    executionPortMap.remove(getOffsetName(portToAllocate.getName()));

                    if (!allocatePort(pas, portToAllocate)) {
                        if (portToAllocate.getOffsetFrom() != null) {
                            portIterator = portGroupMap.get(portGroupName).listIterator();
                        }
                    }

                    ALLOCATION_LOCK.lock();
                    ALLOCATED_PORTS.remove(previousPort);
                    ALLOCATION_LOCK.unlock();
                }
            }

            // log ports
            for (Port port : ports) {
                if (!quiet && getLog().isInfoEnabled()) {
                    String name = getPortName(port.getName());
                    Integer value = executionPortMap.get(name);

                    if (value != null) {
                        getLog().info("Assigning port [" + value + "] to property [" + name + "]");
                    }

                    name = getOffsetName(port.getName());
                    value = executionPortMap.get(name);

                    if (value != null) {
                        getLog().info("Assigning offset [" + value + "] " + "using preferred port ["
                                + port.getPreferredPort() + "] " + "to property [" + name + "]");
                    }
                }
            }
        }

        if (writePropertiesFile != null) {
            final File parent = writePropertiesFile.getParentFile();

            if ((parent != null) && !parent.exists()) {
                parent.mkdirs();
            }

            try (final Writer out = new BufferedWriter(new FileWriter(writePropertiesFile))) {
                if (!quiet && getLog().isInfoEnabled()) {
                    getLog().info("Writing ports file [" + writePropertiesFile + "]");
                }

                final Properties outProps = new Properties();
                outProps.putAll(Maps.transformValues(executionPortMap, new Function<Integer, String>() {
                    @Override
                    public String apply(Integer input) {
                        return input.toString();
                    }
                }));
                outProps.store(out, null);
            } catch (Exception e) {
                throw new MojoExecutionException("Problem writing ports file [" + writePropertiesFile + "]", e);
            }
        }
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    }
}

From source file:org.apache.atlas.repository.graphdb.titan1.Titan1Graph.java

private Object convertGremlinValue(Object rawValue) {

    if (rawValue instanceof Vertex) {
        return GraphDbObjectFactory.createVertex(this, (Vertex) rawValue);
    } else if (rawValue instanceof Edge) {
        return GraphDbObjectFactory.createEdge(this, (Edge) rawValue);
    } else if (rawValue instanceof Map) {
        Map<String, Object> rowValue = (Map<String, Object>) rawValue;
        return Maps.transformValues(rowValue, GREMLIN_VALUE_CONVERSION_FUNCTION);
    } else if (rawValue instanceof ImmutablePath) {
        ImmutablePath path = (ImmutablePath) rawValue;
        return convertGremlinValue(path.objects());
    } else if (rawValue instanceof List) {
        return Lists.transform((List) rawValue, GREMLIN_VALUE_CONVERSION_FUNCTION);
    } else if (rawValue instanceof Collection) {
        throw new UnsupportedOperationException("Unhandled collection type: " + rawValue.getClass());
    }/*from  w  w w. ja  va2  s .  co  m*/
    return rawValue;
}

From source file:ninja.leaping.permissionsex.backend.memory.MemoryOptionSubjectData.java

@Override
public ImmutableOptionSubjectData clearOptions() {
    if (this.contexts.isEmpty()) {
        return this;
    }/*from w  ww. ja v a  2 s.  co m*/

    Map<Set<Entry<String, String>>, DataEntry> newValue = Maps.transformValues(this.contexts,
            new Function<DataEntry, DataEntry>() {
                @Nullable
                @Override
                public DataEntry apply(@Nullable DataEntry dataEntry) {
                    return dataEntry == null ? null : dataEntry.withoutOptions();
                }
            });
    return newData(newValue);
}

From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

@Override
public Response getConfigSummary(JobKey job) throws TException {
    IJobKey jobKey = JobKeys.assertValid(IJobKey.build(job));

    Iterable<IAssignedTask> assignedTasks = Iterables.transform(
            Storage.Util.fetchTasks(storage, Query.jobScoped(jobKey).active()),
            IScheduledTask::getAssignedTask);
    Map<Integer, ITaskConfig> tasksByInstance = Maps.transformValues(
            Maps.uniqueIndex(assignedTasks, IAssignedTask::getInstanceId), IAssignedTask::getTask);
    Set<ConfigGroup> groups = instancesToConfigGroups(tasksByInstance);

    return ok(Result.configSummaryResult(new ConfigSummaryResult().setSummary(new ConfigSummary(job, groups))));
}

From source file:org.quil.interpreter.strata.QuilMarketDataBuilder.java

/**
 * Gets all rates curves.// w  w  w  . j  av a2 s .  com
 *
 * @return the map of all rates curves
 */
public SortedMap<LocalDate, CurveGroup> loadAllRatesCurves() {
    if (!subdirectoryExists(CURVES_DIR)) {
        throw new IllegalArgumentException("No rates curves directory found");
    }
    ResourceLocator curveGroupsResource = getResource(CURVES_DIR, CURVES_GROUPS_FILE);
    if (curveGroupsResource == null) {
        throw new IllegalArgumentException(
                Messages.format("Unable to load rates curves: curve groups file not found at {}/{}", CURVES_DIR,
                        CURVES_GROUPS_FILE));
    }
    ResourceLocator curveSettingsResource = getResource(CURVES_DIR, CURVES_SETTINGS_FILE);
    if (curveSettingsResource == null) {
        throw new IllegalArgumentException(
                Messages.format("Unable to load rates curves: curve settings file not found at {}/{}",
                        CURVES_DIR, CURVES_SETTINGS_FILE));
    }
    ListMultimap<LocalDate, CurveGroup> curveGroups = RatesCurvesCsvLoader.loadAllDates(curveGroupsResource,
            curveSettingsResource, getRatesCurvesResources());

    // There is only one curve group in the market data file so this will always succeed
    Map<LocalDate, CurveGroup> curveGroupMap = Maps.transformValues(curveGroups.asMap(),
            groups -> groups.iterator().next());
    return new TreeMap<>(curveGroupMap);
}

From source file:com.google.devtools.build.skyframe.AbstractSkyFunctionEnvironment.java

@Override
public Map<SkyKey, SkyValue> getValues(Iterable<SkyKey> depKeys) throws InterruptedException {
    return Maps.transformValues(getValuesOrThrow(depKeys, BottomException.class), GET_VALUE_FROM_VOE);
}

From source file:org.apache.brooklyn.core.internal.BrooklynPropertiesImpl.java

@SuppressWarnings("unchecked")
public BrooklynPropertiesImpl addFrom(Map map) {
    putAll(Maps.transformValues(map, StringFunctions.trim()));
    return this;
}