Example usage for com.google.common.collect ImmutableMultimap.Builder put

List of usage examples for com.google.common.collect ImmutableMultimap.Builder put

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMultimap.Builder put.

Prototype

@Deprecated
@Override
public boolean put(K key, V value) 

Source Link

Document

Guaranteed to throw an exception and leave the multimap unmodified.

Usage

From source file:com.facebook.presto.execution.SqlStageExecution.java

private synchronized RemoteTask scheduleTask(Node node, PlanNodeId sourceId, Iterable<Split> sourceSplits) {
    TaskId taskId = new TaskId(stateMachine.getStageId(), String.valueOf(nextTaskId.getAndIncrement()));

    ImmutableMultimap.Builder<PlanNodeId, Split> initialSplits = ImmutableMultimap.builder();
    for (Split sourceSplit : sourceSplits) {
        initialSplits.put(sourceId, sourceSplit);
    }/*from  w  ww .j a va  2 s . c om*/
    for (Entry<PlanNodeId, URI> entry : exchangeLocations.entries()) {
        initialSplits.put(entry.getKey(), createRemoteSplitFor(taskId, entry.getValue()));
    }

    RemoteTask task = remoteTaskFactory.createRemoteTask(stateMachine.getSession(), taskId, node,
            stateMachine.getFragment(), initialSplits.build(), outputBuffers.get(),
            nodeTaskMap.getSplitCountChangeListener(node));

    completeSources.forEach(task::noMoreSplits);

    allTasks.add(taskId);
    tasks.computeIfAbsent(node, key -> newConcurrentHashSet()).add(task);
    nodeTaskMap.addTask(node, task);

    task.addStateChangeListener(taskInfo -> {
        StageState stageState = getState();
        if (stageState.isDone()) {
            return;
        }

        TaskState taskState = taskInfo.getState();
        if (taskState == TaskState.FAILED) {
            RuntimeException failure = taskInfo.getFailures().stream().findFirst()
                    .map(ExecutionFailureInfo::toException).orElse(new PrestoException(
                            StandardErrorCode.INTERNAL_ERROR, "A task failed for an unknown reason"));
            stateMachine.transitionToFailed(failure);
        } else if (taskState == TaskState.ABORTED) {
            // A task should only be in the aborted state if the STAGE is done (ABORTED or FAILED)
            stateMachine.transitionToFailed(new PrestoException(StandardErrorCode.INTERNAL_ERROR,
                    "A task is in the ABORTED state but stage is " + stageState));
        } else if (taskState == TaskState.FINISHED) {
            finishedTasks.add(task.getTaskId());
        }

        if (stageState == StageState.SCHEDULED || stageState == StageState.RUNNING) {
            if (taskState == TaskState.RUNNING) {
                stateMachine.transitionToRunning();
            }
            if (finishedTasks.containsAll(allTasks)) {
                stateMachine.transitionToFinished();
            }
        }
    });

    if (!stateMachine.getState().isDone()) {
        task.start();
    } else {
        // stage finished while we were scheduling this task
        task.abort();
    }

    return task;
}

From source file:com.ibm.common.activitystreams.internal.MultimapAdapter.java

/**
 * Method deserialize./*  ww w  . j  a  v  a 2 s. co  m*/
 * @param json JsonElement
 * @param typeOfT Type
 * @param context JsonDeserializationContext
        
        
        
 * @return Multimap * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public Multimap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    ImmutableMultimap.Builder mm = ImmutableMultimap.builder();
    JsonObject obj = json.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String key = entry.getKey();
        JsonElement val = entry.getValue();
        if (val.isJsonArray()) {
            for (JsonElement el : val.getAsJsonArray()) {
                if (el.isJsonArray())
                    mm.put(key, arraydes(el.getAsJsonArray(), context));
                else if (el.isJsonObject())
                    mm.put(key, context.deserialize(el, ASObject.class));
                else if (el.isJsonPrimitive())
                    mm.put(key, primConverter.convert(el.getAsJsonPrimitive()));
            }
        } else if (val.isJsonObject()) {
            mm.put(key, context.deserialize(val, ASObject.class));
        } else if (val.isJsonPrimitive()) {
            mm.put(key, primConverter.convert(val.getAsJsonPrimitive()));
        }
    }
    return mm.build();
}

From source file:com.google.devtools.build.lib.sandbox.SandboxActionContextConsumer.java

public SandboxActionContextConsumer(CommandEnvironment env) {
    ImmutableMultimap.Builder<Class<? extends ActionContext>, String> contexts = ImmutableMultimap.builder();
    ImmutableMap.Builder<String, String> spawnContexts = ImmutableMap.builder();

    // This makes the "sandboxed" strategy available via --spawn_strategy=sandboxed,
    // but it is not necessarily the default.
    if ((OS.getCurrent() == OS.LINUX && LinuxSandboxedStrategy.isSupported(env))
            || (OS.getCurrent() == OS.DARWIN && DarwinSandboxRunner.isSupported())) {
        contexts.put(SpawnActionContext.class, "sandboxed");

        // This makes the "sandboxed" strategy the default Spawn strategy, unless it is
        // overridden by a later BlazeModule.
        spawnContexts.put("", "sandboxed");
    }// w  w w .  jav a  2  s .com

    this.contexts = contexts.build();
    this.spawnContexts = spawnContexts.build();
}

From source file:org.jclouds.azurecompute.arm.compute.AzureComputeService.java

@Override
protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {
    ImmutableMultimap.Builder<String, String> regionGroups = ImmutableMultimap.builder();
    ImmutableSet.Builder<String> resourceGroups = ImmutableSet.builder();

    for (NodeMetadata deadNode : deadNodes) {
        String resourceGroupName = ResourceGroupAndName.fromSlashEncoded(deadNode.getId()).resourceGroup();
        resourceGroups.add(resourceGroupName);

        if (deadNode.getGroup() != null) {
            regionGroups.put(resourceGroupName, deadNode.getGroup());
        }//from w w  w  .  ja  v a2s .  co  m

        try {
            cleanupResources.cleanupNode(deadNode.getId());
        } catch (Exception ex) {
            logger.warn(ex, "Error cleaning up resources for node %s", deadNode);
        }
    }

    for (Entry<String, String> regionGroup : regionGroups.build().entries()) {
        cleanupResources.cleanupSecurityGroupIfOrphaned(regionGroup.getKey(), regionGroup.getValue());
    }

    for (String resourceGroup : resourceGroups.build()) {
        cleanupResources.deleteResourceGroupIfEmpty(resourceGroup);
    }
}

From source file:org.apache.shindig.gadgets.spec.Feature.java

/**
 * Creates a new Feature from an xml node.
 *
 * @param feature The feature to create//from   w w w . ja v a 2 s . com
 * @throws SpecParserException When the Require or Optional tag is not valid
 */
public Feature(Element feature) throws SpecParserException {
    this.required = feature.getNodeName().equals("Require");
    String name = XmlUtil.getAttribute(feature, "feature");
    if (name == null) {
        throw new SpecParserException((required ? "Require" : "Optional") + "@feature is required.");
    }
    this.name = name;
    NodeList children = feature.getElementsByTagName("Param");
    if (children.getLength() > 0) {
        ImmutableMultimap.Builder<String, String> params = ImmutableMultimap.builder();

        for (int i = 0, j = children.getLength(); i < j; ++i) {
            Element param = (Element) children.item(i);
            String paramName = XmlUtil.getAttribute(param, "name");
            if (paramName == null) {
                throw new SpecParserException("Param@name is required");
            }
            params.put(paramName, param.getTextContent());
        }
        this.params = params.build();
    } else {
        this.params = ImmutableMultimap.of();
    }
}

From source file:org.jclouds.json.internal.IgnoreNullMultimapTypeAdapterFactory.java

private <K, V> TypeAdapter<Multimap<K, V>> newMapAdapter(final TypeAdapter<K> keyAdapter,
        final TypeAdapter<V> valueAdapter) {
    return new TypeAdapter<Multimap<K, V>>() {
        public void write(JsonWriter out, Multimap<K, V> map) throws IOException {
            out.beginObject();/* w  w  w  .ja v  a  2s  .  c o  m*/
            for (K key : map.keySet()) {
                out.name(String.valueOf(key));
                out.beginArray();
                for (V value : map.get(key)) {
                    valueAdapter.write(out, value);
                }
                out.endArray();
            }
            out.endObject();
        }

        public Multimap<K, V> read(JsonReader in) throws IOException {
            ImmutableMultimap.Builder<K, V> result = ImmutableListMultimap.builder();
            in.beginObject();
            while (in.hasNext()) {
                JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);
                K name = keyAdapter.read(in);
                in.beginArray();
                while (in.hasNext()) {
                    V value = valueAdapter.read(in);
                    if (value != null)
                        result.put(name, value);
                }
                in.endArray();
            }
            in.endObject();
            return result.build();
        }
    }.nullSafe();
}

From source file:org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider.java

public <M extends Metadata> Multimap<Method, MetadataHandler<M>> handlers(MetadataDef<M> def) {
    final ImmutableMultimap.Builder<Method, MetadataHandler<M>> builder = ImmutableMultimap.builder();
    for (Map.Entry<Method, MetadataHandler> entry : handlerMap.entries()) {
        if (def.methods.contains(entry.getKey())) {
            //noinspection unchecked
            builder.put(entry.getKey(), entry.getValue());
        }// w  w  w.  j  ava  2  s.c o  m
    }
    return builder.build();
}

From source file:org.graylog2.search.SearchQueryParser.java

public SearchQuery parse(String queryString) {
    if (Strings.isNullOrEmpty(queryString) || "*".equals(queryString)) {
        return new SearchQuery(queryString);
    }//  ww  w .j  a  v  a2 s  . c o  m

    final Matcher matcher = querySplitterMatcher(requireNonNull(queryString).trim());
    final ImmutableMultimap.Builder<String, FieldValue> builder = ImmutableMultimap.builder();
    final ImmutableSet.Builder<String> disallowedKeys = ImmutableSet.builder();

    while (matcher.find()) {
        final String entry = matcher.group();

        if (!entry.contains(":")) {
            builder.put(defaultField, createFieldValue(defaultFieldKey, entry, false));
            continue;
        }

        final Iterator<String> entryFields = FIELD_VALUE_SPLITTER.splitToList(entry).iterator();

        checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
        final String key = entryFields.next();

        // Skip if there are no valid k/v pairs. (i.e. "action:")
        if (!entryFields.hasNext()) {
            continue;
        }

        final boolean negate = key.startsWith("-");
        final String cleanKey = key.replaceFirst("^-", "");
        final String value = entryFields.next();
        VALUE_SPLITTER.splitToList(value).forEach(v -> {
            if (!dbFieldMapping.containsKey(cleanKey)) {
                disallowedKeys.add(cleanKey);
            }
            final SearchQueryField translatedKey = dbFieldMapping.get(cleanKey);
            if (translatedKey != null) {
                builder.put(translatedKey.getDbField(), createFieldValue(translatedKey, v, negate));
            } else {
                builder.put(defaultField, createFieldValue(defaultFieldKey, v, negate));
            }
        });

        checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
    }

    return new SearchQuery(queryString, builder.build(), disallowedKeys.build());
}

From source file:com.facebook.buck.android.apkmodule.APKModuleGraph.java

/**
 * Group the classes in the input jars into a multimap based on the APKModule they belong to
 *
 * @param apkModuleToJarPathMap the mapping of APKModules to the path for the jar files
 * @param translatorFunction function used to translate the class names to obfuscated names
 * @param filesystem filesystem representation for resolving paths
 * @return The mapping of APKModules to the class names they contain
 * @throws IOException//from w  ww . j av a2 s .  c o  m
 */
public static ImmutableMultimap<APKModule, String> getAPKModuleToClassesMap(
        ImmutableMultimap<APKModule, Path> apkModuleToJarPathMap, Function<String, String> translatorFunction,
        ProjectFilesystem filesystem) throws IOException {
    ImmutableMultimap.Builder<APKModule, String> builder = ImmutableSetMultimap.builder();
    if (!apkModuleToJarPathMap.isEmpty()) {
        for (APKModule dexStore : apkModuleToJarPathMap.keySet()) {
            for (Path jarFilePath : apkModuleToJarPathMap.get(dexStore)) {
                ClasspathTraverser classpathTraverser = new DefaultClasspathTraverser();
                classpathTraverser.traverse(new ClasspathTraversal(ImmutableSet.of(jarFilePath), filesystem) {
                    @Override
                    public void visit(FileLike entry) {
                        if (!entry.getRelativePath().endsWith(".class")) {
                            // ignore everything but class files in the jar.
                            return;
                        }

                        String classpath = entry.getRelativePath().replaceAll("\\.class$", "");

                        if (translatorFunction.apply(classpath) != null) {
                            builder.put(dexStore, translatorFunction.apply(classpath));
                        }
                    }
                });
            }
        }
    }
    return builder.build();
}

From source file:org.apache.beam.runners.flink.translation.functions.FlinkBatchSideInputHandlerFactory.java

private <K, V, W extends BoundedWindow> SideInputHandler<V, W> forMultimapSideInput(
        List<WindowedValue<KV<K, V>>> broadcastVariable, Coder<K> keyCoder, Coder<V> valueCoder,
        Coder<W> windowCoder) {// w  w  w.  ja v a 2  s  . c om
    ImmutableMultimap.Builder<SideInputKey, V> multimap = ImmutableMultimap.builder();
    for (WindowedValue<KV<K, V>> windowedValue : broadcastVariable) {
        K key = windowedValue.getValue().getKey();
        V value = windowedValue.getValue().getValue();

        for (BoundedWindow boundedWindow : windowedValue.getWindows()) {
            @SuppressWarnings("unchecked")
            W window = (W) boundedWindow;
            multimap.put(SideInputKey.of(keyCoder.structuralValue(key), windowCoder.structuralValue(window)),
                    value);
        }
    }

    return new MultimapSideInputHandler<>(multimap.build(), keyCoder, valueCoder, windowCoder);
}