Example usage for com.google.common.collect ImmutableMap.Builder putAll

List of usage examples for com.google.common.collect ImmutableMap.Builder putAll

Introduction

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

Prototype

public final void putAll(Map<? extends K, ? extends V> map) 

Source Link

Usage

From source file:me.lucko.luckperms.core.Node.java

/**
 * Make an immutable node instance//from   w  w  w.j  a v  a2  s .c o m
 * @param permission the actual permission node
 * @param value the value (if it's *not* negated)
 * @param expireAt the time when the node will expire
 * @param server the server this node applies on
 * @param world the world this node applies on
 * @param extraContexts any additional contexts applying to this node
 */
public Node(String permission, boolean value, boolean override, long expireAt, String server, String world,
        Map<String, String> extraContexts) {
    if (permission == null || permission.equals("")) {
        throw new IllegalArgumentException("Empty permission");
    }

    if (server != null && (server.equalsIgnoreCase("global") || server.equals(""))) {
        server = null;
    }

    if (world != null && world.equals("")) {
        world = null;
    }

    if (world != null && server == null) {
        server = "global";
    }

    this.permission = permission;
    this.value = value;
    this.override = override;
    this.expireAt = expireAt;
    this.server = server;
    this.world = world;

    ImmutableMap.Builder<String, String> contexts = ImmutableMap.builder();
    if (extraContexts != null) {
        contexts.putAll(extraContexts);
    }
    this.extraContexts = contexts.build();
}

From source file:org.elasticsearch.snapshots.SnapshotShardsService.java

/**
 * Checks if any new shards should be snapshotted on this node
 *
 * @param event cluster state changed event
 *//*from  w w  w  .  j a v  a  2s .c  o m*/
private void processIndexShardSnapshots(ClusterChangedEvent event) {
    SnapshotsInProgress snapshotsInProgress = event.state().custom(SnapshotsInProgress.TYPE);
    Map<SnapshotId, SnapshotShards> survivors = newHashMap();
    // First, remove snapshots that are no longer there
    for (Map.Entry<SnapshotId, SnapshotShards> entry : shardSnapshots.entrySet()) {
        if (snapshotsInProgress != null && snapshotsInProgress.snapshot(entry.getKey()) != null) {
            survivors.put(entry.getKey(), entry.getValue());
        }
    }

    // For now we will be mostly dealing with a single snapshot at a time but might have multiple simultaneously running
    // snapshots in the future
    Map<SnapshotId, Map<ShardId, IndexShardSnapshotStatus>> newSnapshots = newHashMap();
    // Now go through all snapshots and update existing or create missing
    final String localNodeId = clusterService.localNode().id();
    if (snapshotsInProgress != null) {
        for (SnapshotsInProgress.Entry entry : snapshotsInProgress.entries()) {
            if (entry.state() == SnapshotsInProgress.State.STARTED) {
                Map<ShardId, IndexShardSnapshotStatus> startedShards = newHashMap();
                SnapshotShards snapshotShards = shardSnapshots.get(entry.snapshotId());
                for (Map.Entry<ShardId, SnapshotsInProgress.ShardSnapshotStatus> shard : entry.shards()
                        .entrySet()) {
                    // Add all new shards to start processing on
                    if (localNodeId.equals(shard.getValue().nodeId())) {
                        if (shard.getValue().state() == SnapshotsInProgress.State.INIT
                                && (snapshotShards == null
                                        || !snapshotShards.shards.containsKey(shard.getKey()))) {
                            logger.trace("[{}] - Adding shard to the queue", shard.getKey());
                            startedShards.put(shard.getKey(), new IndexShardSnapshotStatus());
                        }
                    }
                }
                if (!startedShards.isEmpty()) {
                    newSnapshots.put(entry.snapshotId(), startedShards);
                    if (snapshotShards != null) {
                        // We already saw this snapshot but we need to add more started shards
                        ImmutableMap.Builder<ShardId, IndexShardSnapshotStatus> shards = ImmutableMap.builder();
                        // Put all shards that were already running on this node
                        shards.putAll(snapshotShards.shards);
                        // Put all newly started shards
                        shards.putAll(startedShards);
                        survivors.put(entry.snapshotId(), new SnapshotShards(shards.build()));
                    } else {
                        // Brand new snapshot that we haven't seen before
                        survivors.put(entry.snapshotId(),
                                new SnapshotShards(ImmutableMap.copyOf(startedShards)));
                    }
                }
            } else if (entry.state() == SnapshotsInProgress.State.ABORTED) {
                // Abort all running shards for this snapshot
                SnapshotShards snapshotShards = shardSnapshots.get(entry.snapshotId());
                if (snapshotShards != null) {
                    for (Map.Entry<ShardId, SnapshotsInProgress.ShardSnapshotStatus> shard : entry.shards()
                            .entrySet()) {
                        IndexShardSnapshotStatus snapshotStatus = snapshotShards.shards.get(shard.getKey());
                        if (snapshotStatus != null) {
                            switch (snapshotStatus.stage()) {
                            case INIT:
                            case STARTED:
                                snapshotStatus.abort();
                                break;
                            case FINALIZE:
                                logger.debug(
                                        "[{}] trying to cancel snapshot on shard [{}] that is finalizing, letting it finish",
                                        entry.snapshotId(), shard.getKey());
                                break;
                            case DONE:
                                logger.debug(
                                        "[{}] trying to cancel snapshot on the shard [{}] that is already done, updating status on the master",
                                        entry.snapshotId(), shard.getKey());
                                updateIndexShardSnapshotStatus(entry.snapshotId(), shard.getKey(),
                                        new SnapshotsInProgress.ShardSnapshotStatus(
                                                event.state().nodes().localNodeId(),
                                                SnapshotsInProgress.State.SUCCESS));
                                break;
                            case FAILURE:
                                logger.debug(
                                        "[{}] trying to cancel snapshot on the shard [{}] that has already failed, updating status on the master",
                                        entry.snapshotId(), shard.getKey());
                                updateIndexShardSnapshotStatus(entry.snapshotId(), shard.getKey(),
                                        new SnapshotsInProgress.ShardSnapshotStatus(
                                                event.state().nodes().localNodeId(),
                                                SnapshotsInProgress.State.FAILED, snapshotStatus.failure()));
                                break;
                            default:
                                throw new IllegalStateException(
                                        "Unknown snapshot shard stage " + snapshotStatus.stage());
                            }
                        }
                    }
                }
            }
        }
    }

    // Update the list of snapshots that we saw and tried to started
    // If startup of these shards fails later, we don't want to try starting these shards again
    shutdownLock.lock();
    try {
        shardSnapshots = ImmutableMap.copyOf(survivors);
        if (shardSnapshots.isEmpty()) {
            // Notify all waiting threads that no more snapshots
            shutdownCondition.signalAll();
        }
    } finally {
        shutdownLock.unlock();
    }

    // We have new shards to starts
    if (newSnapshots.isEmpty() == false) {
        Executor executor = threadPool.executor(ThreadPool.Names.SNAPSHOT);
        for (final Map.Entry<SnapshotId, Map<ShardId, IndexShardSnapshotStatus>> entry : newSnapshots
                .entrySet()) {
            for (final Map.Entry<ShardId, IndexShardSnapshotStatus> shardEntry : entry.getValue().entrySet()) {
                final ShardId shardId = shardEntry.getKey();
                try {
                    final IndexShard indexShard = indicesService.indexServiceSafe(shardId.getIndex())
                            .shard(shardId.id());
                    executor.execute(new AbstractRunnable() {
                        @Override
                        public void doRun() {
                            snapshot(indexShard, entry.getKey(), shardEntry.getValue());
                            updateIndexShardSnapshotStatus(entry.getKey(), shardId,
                                    new SnapshotsInProgress.ShardSnapshotStatus(localNodeId,
                                            SnapshotsInProgress.State.SUCCESS));
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            logger.warn("[{}] [{}] failed to create snapshot", t, shardId, entry.getKey());
                            updateIndexShardSnapshotStatus(entry.getKey(), shardId,
                                    new SnapshotsInProgress.ShardSnapshotStatus(localNodeId,
                                            SnapshotsInProgress.State.FAILED,
                                            ExceptionsHelper.detailedMessage(t)));
                        }

                    });
                } catch (Throwable t) {
                    updateIndexShardSnapshotStatus(entry.getKey(), shardId,
                            new SnapshotsInProgress.ShardSnapshotStatus(localNodeId,
                                    SnapshotsInProgress.State.FAILED, ExceptionsHelper.detailedMessage(t)));
                }
            }
        }
    }
}

From source file:cz.cuni.mff.ms.brodecva.botnicek.ide.project.model.Project.java

private void exportConfigs(final Path directory) throws IOException {
    final ImmutableMap.Builder<String, Properties> propertiesUnitsBuilder = ImmutableMap.builder();
    propertiesUnitsBuilder.putAll(this.runtimeSettings.getBotConfiguration().toNamedProperties());
    propertiesUnitsBuilder.putAll(this.runtimeSettings.getLanguageConfiguration().toNamedProperties());
    propertiesUnitsBuilder.putAll(this.runtimeSettings.getConversationConfiguration().toNamedProperties());
    final Map<String, Properties> propertiesUnits = propertiesUnitsBuilder.build();

    final Set<Entry<String, Properties>> propertiesUnitsEntries = propertiesUnits.entrySet();
    for (final Entry<String, Properties> unit : propertiesUnitsEntries) {
        final String name = unit.getKey();
        final Properties content = unit.getValue();

        final String unitName = String.format("%s.%s", name, PROPERTIES_EXTENSION);

        writePropertiesUnit(directory, unitName, content);
    }/*from w w w . jav  a 2 s .c  o  m*/
}

From source file:io.soliton.shapeshifter.NamedSchema.java

/**
 * Returns a new schema that will serialize repeated objects as a JSON
 * object instead of a JSON array./* w  ww.j a v a2 s.  c  om*/
 * <p/>
 * <p>This transformation is useful in cases where the source object
 * contains a list of objects identified by a given field. Normally, such
 * a list would be serialized as:<pre>{@code
 * <p/>
 * "users": [
 *       {"username": "lrichie", name: "Lionel Richie"},
 *       {"username": "stwain", "name": "Shania Twain"}
 * ]}</pre>
 * <p/>
 * <p>A common JSON idiom is to represent such collections as pseudo-maps,
 * i.e.objects with non-predefined keys:<pre>{@code
 * <p/>
 * "users": {
 *    "lrichie": {"name": "Lionel Richie"},
 *    "stwain": {"name": "Shania Twain"}
 * }}</pre>
 * <p/>
 * <p>To achieve this effect, call this method with {@code "users"} and
 * {@code "username"} as parameters, respectively.
 *
 * @param fieldName    Must point to a repeated object field in this schema
 * @param keyFieldName Must be a string field in the repeated field
 */
public NamedSchema mapRepeatedField(String fieldName, String keyFieldName) {
    Preconditions.checkNotNull(fieldName);
    Preconditions.checkArgument(has(fieldName));
    Preconditions.checkNotNull(keyFieldName);
    FieldDescriptor field = fields.get(fieldName);
    Preconditions.checkArgument(field.isRepeated() && Type.MESSAGE.equals(field.getType()));
    Descriptor fieldDescriptor = field.getMessageType();
    boolean found = false;
    FieldDescriptor keyField = null;
    for (FieldDescriptor subField : fieldDescriptor.getFields()) {
        if (subField.getName().equals(keyFieldName)) {
            found = true;
            keyField = subField;
        }
    }
    if (!found || keyField.isRepeated() || !Type.STRING.equals(keyField.getType())) {
        throw new IllegalArgumentException();
    }
    ImmutableMap.Builder<String, FieldDescriptor> mappingsCopy = ImmutableMap
            .<String, FieldDescriptor>builder();
    mappingsCopy.putAll(mappings);
    mappingsCopy.put(fieldName, keyField);
    return new NamedSchema(descriptor, name, skippedFields, constants, enumCaseFormat, substitutions,
            transforms, mappingsCopy.build(), descriptions, subObjectSchemas, formats, treatLongsAsStrings);
}

From source file:org.dcache.util.configuration.ConfigurationMapFactoryBean.java

@PostConstruct
public void buildMap() {
    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();

    Replaceable replaceable = name -> {
        Object value = _environment.get(name);
        return (value == null) ? null : value.toString().trim();
    };/*ww w.  ja  v a  2  s  .  co  m*/

    int prefixLength = _prefix.length();
    for (Map.Entry<String, Object> item : _environment.entrySet()) {
        String name = item.getKey();
        if (item.getValue() instanceof String && name.startsWith(_prefix)) {
            String value = (String) item.getValue();
            String key = name.substring(prefixLength);
            if (!key.isEmpty() && (_staticEnvironment == null || !_staticEnvironment.containsKey(key))) {
                builder.put(key, Formats.replaceKeywords(value, replaceable));
            }
        }
    }

    if (_staticEnvironment != null) {
        builder.putAll((Map<? extends String, ? extends String>) _staticEnvironment);
    }

    _object = builder.build();
}

From source file:com.google.template.soy.passes.PluginResolver.java

public PluginResolver(Mode mode, ImmutableMap<String, SoyPrintDirective> soyPrintDirectives,
        ImmutableMap<String, SoyFunction> soyFunctions, ImmutableMap<String, SoySourceFunction> sourceFunctions,
        ErrorReporter reporter) {//  w w  w.  j  av  a 2s.  co  m
    this.mode = checkNotNull(mode);
    this.printDirectives = checkNotNull(soyPrintDirectives);
    this.reporter = checkNotNull(reporter);
    for (String illegalName : BaseUtils.ILLEGAL_PLUGIN_NAMES) {
        if (soyFunctions.containsKey(illegalName) || sourceFunctions.containsKey(illegalName)) {
            reporter.report(SourceLocation.UNKNOWN, PLUGIN_NAME_NOT_ALLOWED, illegalName);
        }
    }
    // Merge the SoyFunctions & SoySourceFunctions.  While merging, confirm that we only have
    // one implementation for each plugin. They can overlap, but impl must be the same. This
    // indicates a partially migrated plugin.
    // Also confirm that each SoySourceFunction has a @SoyFunctionSignature, which is required.
    ImmutableMap.Builder<String, Object> mergedFunctions = ImmutableMap.builder();
    for (Map.Entry<String, SoyFunction> entry : soyFunctions.entrySet()) {
        SoySourceFunction source = sourceFunctions.get(entry.getKey());
        if (source != null) {
            if (source != entry.getValue()) {
                reporter.report(SourceLocation.UNKNOWN, DIFFERENT_IMPLS_REGISTERED, entry.getKey(),
                        entry.getValue(), source);
            }
        } else {
            // We only insert non-duplicates into the merged map to avoid IllegalArugmentExceptions
            // building the map.
            mergedFunctions.put(entry.getKey(), entry.getValue());
        }
    }
    mergedFunctions.putAll(sourceFunctions);
    this.functions = mergedFunctions.build();

    // Go back over our merged functions and validate all the SoySourceFunction implementations.
    // We explicitly look *after* merging because SoySourceFunctions might be registered
    // as SoyFunctions if they also implemented other backends like SoyJsFunction.
    for (Object function : this.functions.values()) {
        if (function instanceof SoySourceFunction) {
            if (!function.getClass().isAnnotationPresent(SoyFunctionSignature.class)) {
                // Make sure a function sig exists.
                reporter.report(SourceLocation.UNKNOWN, MISSING_FUNCTION_SIGNATURE,
                        function.getClass().getName());
            } else if (function instanceof SoyJavaSourceFunction) {
                // Also make sure that the applyForJavaSource impl uses a single plugin instance.
                // We don't support multiple instances.
                Set<Class<?>> instances = PluginInstanceFinder.find((SoyJavaSourceFunction) function);
                if (instances.size() > 1) {
                    reporter.report(SourceLocation.UNKNOWN, MULTIPLE_PLUGIN_INSTANCES,
                            function.getClass().getName(), instances);
                }
            }
        }
    }
}

From source file:com.google.template.soy.soyparse.PluginResolver.java

public PluginResolver(Mode mode, ImmutableMap<String, SoyPrintDirective> soyPrintDirectives,
        ImmutableMap<String, SoyFunction> soyFunctions, ImmutableMap<String, SoySourceFunction> sourceFunctions,
        ErrorReporter reporter) {/*from  w ww.j a  v a  2 s.  co  m*/
    this.mode = checkNotNull(mode);
    this.printDirectives = checkNotNull(soyPrintDirectives);
    this.reporter = checkNotNull(reporter);
    for (String illegalName : ILLEGAL_PLUGIN_NAMES) {
        if (soyFunctions.containsKey(illegalName) || sourceFunctions.containsKey(illegalName)) {
            reporter.report(SourceLocation.UNKNOWN, PLUGIN_NAME_NOT_ALLOWED, illegalName);
        }
    }
    // Merge the SoyFunctions & SoySourceFunctions.  While merging, confirm that we only have
    // one implementation for each plugin. They can overlap, but impl must be the same. This
    // indicates a partially migrated plugin.
    // Also confirm that each SoySourceFunction has a @SoyFunctionSignature, which is required.
    ImmutableMap.Builder<String, Object> mergedFunctions = ImmutableMap.builder();
    for (Map.Entry<String, SoyFunction> entry : soyFunctions.entrySet()) {
        SoySourceFunction source = sourceFunctions.get(entry.getKey());
        if (source != null) {
            if (source != entry.getValue()) {
                reporter.report(SourceLocation.UNKNOWN, DIFFERENT_IMPLS_REGISTERED, entry.getKey(),
                        entry.getValue(), source);
            }
        } else {
            // We only insert non-duplicates into the merged map to avoid IllegalArugmentExceptions
            // building the map.
            mergedFunctions.put(entry.getKey(), entry.getValue());
        }
    }
    mergedFunctions.putAll(sourceFunctions);
    this.functions = mergedFunctions.build();

    // Go back over our merged functions and validate all the SoySourceFunction implementations.
    // We explicitly look *after* merging because SoySourceFunctions might be registered
    // as SoyFunctions if they also implemented other backends like SoyJsFunction.
    for (Object function : this.functions.values()) {
        if (function instanceof SoySourceFunction) {
            if (!function.getClass().isAnnotationPresent(SoyFunctionSignature.class)) {
                // Make sure a function sig exists.
                reporter.report(SourceLocation.UNKNOWN, MISSING_FUNCTION_SIGNATURE,
                        function.getClass().getName());
            } else if (function instanceof SoyJavaSourceFunction) {
                // Also make sure that the applyForJavaSource impl uses a single plugin instance.
                // We don't support multiple instances.
                Set<Class<?>> instances = PluginInstanceFinder.find((SoyJavaSourceFunction) function);
                if (instances.size() > 1) {
                    reporter.report(SourceLocation.UNKNOWN, MULTIPLE_PLUGIN_INSTANCES,
                            function.getClass().getName(), instances);
                }
            }
        }
    }
}

From source file:co.cask.common.cli.CommandMatch.java

/**
 * Parse arguments from the split input and pattern.
 * Used for parsing optional parameters. Does not cause the effect in case specified parameter absent.
 *
 * @param splitInput the split input/*from   w w w . j a  v  a 2s .c  o m*/
 * @param pattern the pattern
 * @return the map of arguments
 */
private Map<String, String> parseOptional(List<String> splitInput, String pattern) {
    ImmutableMap.Builder<String, String> args = ImmutableMap.builder();

    List<String> copyInput = new ArrayList<String>(splitInput);
    List<String> splitPattern = Parser.parsePattern(pattern);

    while (!splitPattern.isEmpty()) {
        if (copyInput.isEmpty()) {
            return Collections.emptyMap();
        }
        String patternPart = splitPattern.get(0);
        String inputPart = processInputArgument(copyInput.get(0));
        if (patternPart.startsWith((Character.toString(MANDATORY_ARG_BEGINNING)))
                && patternPart.endsWith((Character.toString(MANDATORY_ARG_ENDING)))) {
            args.put(getEntry(patternPart), inputPart);
        } else if (patternPart.startsWith((Character.toString(OPTIONAL_PART_BEGINNING)))
                && patternPart.endsWith((Character.toString(OPTIONAL_PART_ENDING)))) {
            args.putAll(parseOptional(copyInput, getEntry(patternPart)));
        } else if (!patternPart.equals(inputPart)) {
            return Collections.emptyMap();
        }
        splitPattern.remove(0);
        copyInput.remove(0);
    }

    splitInput.clear();
    splitInput.addAll(copyInput);
    return args.build();
}

From source file:com.google.firebase.messaging.Aps.java

private Aps(Builder builder) {
    checkArgument(Strings.isNullOrEmpty(builder.alertString) || (builder.alert == null),
            "Multiple alert specifications (string and ApsAlert) found.");
    ImmutableMap.Builder<String, Object> fields = ImmutableMap.builder();
    if (builder.alert != null) {
        fields.put("alert", builder.alert);
    } else if (builder.alertString != null) {
        fields.put("alert", builder.alertString);
    }//from ww  w .j  a va 2s  . c  o  m
    if (builder.badge != null) {
        fields.put("badge", builder.badge);
    }
    if (builder.sound != null) {
        fields.put("sound", builder.sound);
    }
    if (builder.contentAvailable) {
        fields.put("content-available", 1);
    }
    if (builder.mutableContent) {
        fields.put("mutable-content", 1);
    }
    if (builder.category != null) {
        fields.put("category", builder.category);
    }
    if (builder.threadId != null) {
        fields.put("thread-id", builder.threadId);
    }
    fields.putAll(builder.customData);
    this.fields = fields.build();
}

From source file:org.sonatype.nexus.repository.storage.StorageTxImpl.java

@Override
@Guarded(by = ACTIVE)//  w  w w.j  av  a2  s  .  com
public AssetBlob createBlob(final String blobName, final Path sourceFile,
        final Map<HashAlgorithm, HashCode> hashes, @Nullable final Map<String, String> headers,
        final String declaredContentType, final long size) throws IOException {
    checkNotNull(blobName);
    checkNotNull(sourceFile);
    checkNotNull(hashes);
    checkArgument(!Strings2.isBlank(declaredContentType), "no declaredContentType provided");

    if (!writePolicy.checkCreateAllowed()) {
        throw new IllegalOperationException("Repository is read only: " + bucket.getRepositoryName());
    }

    ImmutableMap.Builder<String, String> storageHeaders = ImmutableMap.builder();
    storageHeaders.put(Bucket.REPO_NAME_HEADER, bucket.getRepositoryName());
    storageHeaders.put(BlobStore.BLOB_NAME_HEADER, blobName);
    storageHeaders.put(BlobStore.CREATED_BY_HEADER, createdBy);
    storageHeaders.put(BlobStore.CONTENT_TYPE_HEADER, declaredContentType);
    if (headers != null) {
        storageHeaders.putAll(headers);
    }
    return blobTx.createByHardLinking(sourceFile, storageHeaders.build(), hashes, declaredContentType, size);
}