Example usage for com.google.common.collect ImmutableMap containsKey

List of usage examples for com.google.common.collect ImmutableMap containsKey

Introduction

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

Prototype

@Override
    public boolean containsKey(@Nullable Object key) 

Source Link

Usage

From source file:org.elasticsearch.index.gateway.blobstore.BlobStoreIndexShardGateway.java

private void recoverFile(final CommitPoint.FileInfo fileInfo, final ImmutableMap<String, BlobMetaData> blobs,
        final CountDownLatch latch, final List<Throwable> failures) {
    final IndexOutput indexOutput;
    try {/* w w w.j  a  va 2s  . c om*/
        // we create an output with no checksum, this is because the pure binary data of the file is not
        // the checksum (because of seek). We will create the checksum file once copying is done
        indexOutput = store.createOutputRaw(fileInfo.physicalName());
    } catch (IOException e) {
        failures.add(e);
        latch.countDown();
        return;
    }

    String firstFileToRecover = fileInfo.name();
    if (!blobs.containsKey(fileInfo.name())) {
        // chunking, append part0 to it
        firstFileToRecover = fileInfo.name() + ".part0";
    }
    if (!blobs.containsKey(firstFileToRecover)) {
        // no file, what to do, what to do?
        logger.warn("no file [{}]/[{}] to recover, ignoring it", fileInfo.name(), fileInfo.physicalName());
        latch.countDown();
        return;
    }
    final AtomicInteger partIndex = new AtomicInteger();

    blobContainer.readBlob(firstFileToRecover, new BlobContainer.ReadBlobListener() {
        @Override
        public synchronized void onPartial(byte[] data, int offset, int size) throws IOException {
            recoveryStatus.index().addCurrentFilesSize(size);
            indexOutput.writeBytes(data, offset, size);
        }

        @Override
        public synchronized void onCompleted() {
            int part = partIndex.incrementAndGet();
            String partName = fileInfo.name() + ".part" + part;
            if (blobs.containsKey(partName)) {
                // continue with the new part
                blobContainer.readBlob(partName, this);
                return;
            } else {
                // we are done...
                try {
                    indexOutput.close();
                    // write the checksum
                    if (fileInfo.checksum() != null) {
                        store.writeChecksum(fileInfo.physicalName(), fileInfo.checksum());
                    }
                    store.directory().sync(Collections.singleton(fileInfo.physicalName()));
                } catch (IOException e) {
                    onFailure(e);
                    return;
                }
            }
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            failures.add(t);
            latch.countDown();
        }
    });
}

From source file:com.google.polymer.JsRenamer.java

/**
 * Forwards renames to Polymer-relevant properties in the specified object map.
 * @param renameMap A mapping from symbol to renamed symbol.
 * @param objectMap A map of keys as property string names to values as nodes.
 *///from w w  w.  ja v  a 2 s . c  om
private static void renameObjectMap(ImmutableMap<String, String> renameMap,
        ImmutableMap<String, Node> objectMap) {
    // Rename 'computed' and 'observer' property description references.
    Node propertiesNode = objectMap.get("properties");
    if ((propertiesNode != null) && propertiesNode.isObjectLit()) {
        ImmutableMap<String, Node> propertiesMap = convertObjectLitNodeToMap(propertiesNode);
        for (Node propertyDescriptorNode : propertiesMap.values()) {
            if (propertyDescriptorNode.isObjectLit()) {
                ImmutableMap<String, Node> propertyDescriptorMap = convertObjectLitNodeToMap(
                        propertyDescriptorNode);
                renamePolymerJsStringNode(renameMap, propertyDescriptorMap.get("computed"));
                renamePolymerJsStringNode(renameMap, propertyDescriptorMap.get("observer"));
            }
        }
    }

    // Rename all JavaScript-like expressions in the 'observers' array.
    Node observersNode = objectMap.get("observers");
    if ((observersNode != null) && observersNode.isArrayLit()) {
        for (Node observerItem : observersNode.children()) {
            renamePolymerJsStringNode(renameMap, observerItem);
        }
    }

    // Rename all JavaScript-like expressions in the listeners descriptor.
    Node listenersNode = objectMap.get("listeners");
    if ((listenersNode != null) && listenersNode.isObjectLit()) {
        ImmutableMap<String, Node> listenersMap = convertObjectLitNodeToMap(listenersNode);
        for (Node listenerDescriptorNode : listenersMap.values()) {
            renamePolymerJsStringNode(renameMap, listenerDescriptorNode);
        }
    }

    // Rename the keyBindings string to method string map using in Polymer.IronA11yKeysBehavior.
    Node keyBindingsNode = objectMap.get("keyBindings");
    if ((keyBindingsNode != null) && keyBindingsNode.isObjectLit()) {
        renameKeyBindingsNode(renameMap, keyBindingsNode);
    }

    if (renameMap.containsKey("keyBindings")) {
        Node renamedKeyBindingsNode = objectMap.get(renameMap.get("keyBindings"));
        if ((renamedKeyBindingsNode != null) && renamedKeyBindingsNode.isObjectLit()) {
            renameKeyBindingsNode(renameMap, renamedKeyBindingsNode);
        }
    }
}

From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java

@Override
@VisibleForTesting//from   w ww . jav a2s  .  c om
protected void processConfigUpdate(byte[] bytes) throws Exception {
    MySQLConfigSchema mysqlConfig;
    mysqlConfig = MySQLConfigSchema.read(new ByteArrayInputStream(bytes),
            configuration.getString("SHARD_ALLOWED_HOSTNAME_PREFIX"));

    ImmutableMap.Builder<String, MySQLDataSources> shardMapBuilder = new ImmutableMap.Builder<String, MySQLDataSources>();
    ImmutableMap<String, MySQLDataSources> currentMap = shardMapRef.get();
    Map<String, Boolean> updatedMap = Maps.newHashMap();

    Set<String> queueNames = getQueueNamesImpl();
    // Check if we can reuse any old MySQLDataSource object. updatedMap indicates if a shard's
    // config has changed or it's a new shard (in these cases we'll need to initialize new
    // connections to the shard).
    for (MySQLConfigSchema.Shard shard : mysqlConfig.shards) {
        // Note: we only need to check if we can reuse the connection to the first database for each
        // MySQL instance. The number of databases per queue can't change at runtime, and all the
        // databases in the same MySQL instance share a same data source. So if the
        // connection to database 0 is reusable, it is guaranteed that we can reuse if for all other
        // databases within the same instance.
        String shardName = MySQLBackendUtils.constructShardName(shard.id, 0);
        if (currentMap != null && currentMap.containsKey(shardName)
                && currentMap.get(shardName).needNewConnection(shard.shardConfig.master.host,
                        shard.shardConfig.master.port, shard.shardConfig.user, shard.shardConfig.passwd)) {
            MySQLDataSources ds = currentMap.get(shardName);
            ds.setDequeueOnly(shard.shardConfig.dequeueOnly);
            for (int dbId = 0; dbId < numDbPerQueue; dbId++) {
                shardName = MySQLBackendUtils.constructShardName(shard.id, dbId);
                shardMapBuilder.put(shardName, ds);
                updatedMap.put(shardName, false);
            }
        } else {
            MySQLDataSources ds = new MySQLDataSources(configuration, shard.shardConfig.master.host,
                    shard.shardConfig.master.port, shard.shardConfig.user, shard.shardConfig.passwd,
                    shard.shardConfig.dequeueOnly);
            for (int dbId = 0; dbId < numDbPerQueue; dbId++) {
                shardName = MySQLBackendUtils.constructShardName(shard.id, dbId);
                shardMapBuilder.put(shardName, ds);
                updatedMap.put(shardName, true);
            }
        }
    }
    mySQLHealthMonitor.updateHealthMap(updatedMap);
    shardMapRef.set(shardMapBuilder.build());
    // Need to create queues for new added shards
    for (String queueName : queueNames) {
        createQueueImpl(queueName);
    }

    // Restart the JobQueueMonitor scheduled task.
    int delaySeconds = configuration.getInt("BACKEND_MONITOR_THREAD_DELAY_SECONDS");
    if (this.queueMonitorFuture != null) {
        this.queueMonitorFuture.cancel(true);
    }
    this.queueMonitorFuture = this.queueMonitorService.scheduleWithFixedDelay(
            new MySQLQueueMonitor(shardMapRef.get(), configuration),
            // Randomize initial delay to prevent all servers from running GC at the same time.
            delaySeconds + RANDOM.nextInt(delaySeconds), delaySeconds, TimeUnit.SECONDS);
    LOG.info("MySQL config update, new value: {}", mysqlConfig);
}

From source file:org.kiji.scoring.impl.InternalFreshKijiTableReader.java

/** {@inheritDoc} */
@Override/*from w ww.ja  va2s  .c om*/
public void rereadFreshenerRecords(final List<KijiColumnName> columnsToFreshen) throws IOException {
    requireState(LifecycleState.OPEN);
    LOG.debug("{} rereading Freshener records with columnsToFreshen: {}", mReaderUID, columnsToFreshen);
    // Collect and filter the current state of the meta table.
    final ImmutableMap<KijiColumnName, KijiFreshenerRecord> newRecords = filterRecords(
            mFreshnessManager.retrieveFreshenerRecords(mTable.getName()), columnsToFreshen);

    final Map<KijiColumnName, Freshener> oldFresheners = Maps.newHashMap();

    final RereadableState oldState = mRereadableState;
    // Retain old Fresheners if they are still valid. Invalid Fresheners will be closed by the old
    // RereadableState when it is closed.
    for (Map.Entry<KijiColumnName, Freshener> entry : oldState.mFresheners.entrySet()) {
        final KijiColumnName column = entry.getKey();
        final Freshener oldFreshener = entry.getValue();
        final KijiFreshenerRecord oldRecord = oldState.mFreshenerRecords.get(column);
        if (newRecords.containsKey(column) && newRecords.get(column).equals(oldRecord)) {
            // The Freshener record is unchanged, so retain the Freshener to transfer ownership from the
            // old RereadableState to the new one.
            LOG.debug("{} retaining still valid Freshener: {}", mReaderUID, oldFreshener);
            oldFreshener.retain();
            oldFresheners.put(column, oldFreshener);
        }
    }

    // Swap the new RereadableState into place and release the old one. When the old one closes, it
    // will release all the Fresheners it held, which will close any that are no longer valid and
    // not in use.
    mRereadableState = new RereadableState(columnsToFreshen, newRecords,
            fillFresheners(mReaderUID, newRecords, ImmutableMap.copyOf(oldFresheners)));
    oldState.release();
}

From source file:marytts.features.FeatureDefinition.java

/**
 * Print this feature definition plus weights to a .txt file
 * // www .ja  va 2 s  .  com
 * @param out
 *            the destination of the data
 */
public void generateFeatureWeightsFile(PrintWriter out) {
    out.println("# This file lists the features and their weights to be used for\n"
            + "# creating the MARY features file.\n"
            + "# The same file can also be used to override weights in a run-time system.\n"
            + "# Three sections are distinguished: Byte-valued, Short-valued, and\n"
            + "# Continuous features.\n" + "#\n"
            + "# Lines starting with '#' are ignored; they can be used for comments\n"
            + "# anywhere in the file. Empty lines are also ignored.\n"
            + "# Entries must have the following form:\n" + "# \n"
            + "# <weight definition> | <feature definition>\n" + "# \n"
            + "# For byte and short features, <weight definition> is simply the \n"
            + "# (float) number representing the weight.\n"
            + "# For continuous features, <weight definition> is the\n"
            + "# (float) number representing the weight, followed by an optional\n"
            + "# weighting function including arguments.\n" + "#\n"
            + "# The <feature definition> is the feature name, which in the case of\n"
            + "# byte and short features is followed by the full list of feature values.\n" + "#\n"
            + "# Note that the feature definitions must be identical between this file\n"
            + "# and all unit feature files for individual database utterances.\n"
            + "# THIS FILE WAS GENERATED AUTOMATICALLY");
    out.println();
    out.println("ByteValuedFeatureProcessors");
    List<String> getValuesOf10 = new ArrayList<String>();
    getValuesOf10.add("phone");
    getValuesOf10.add("ph_vc");
    getValuesOf10.add("prev_phone");
    getValuesOf10.add("next_phone");
    getValuesOf10.add("stressed");
    getValuesOf10.add("syl_break");
    getValuesOf10.add("prev_syl_break");
    getValuesOf10.add("next_is_pause");
    getValuesOf10.add("prev_is_pause");
    List<String> getValuesOf5 = new ArrayList<String>();
    getValuesOf5.add("cplace");
    getValuesOf5.add("ctype");
    getValuesOf5.add("cvox");
    getValuesOf5.add("vfront");
    getValuesOf5.add("vheight");
    getValuesOf5.add("vlng");
    getValuesOf5.add("vrnd");
    getValuesOf5.add("vc");
    for (int i = 0; i < numByteFeatures; i++) {
        String featureName = getFeatureName(i);
        if (getValuesOf10.contains(featureName)) {
            out.print("10 | " + featureName);
        } else {
            boolean found = false;
            for (String match : getValuesOf5) {
                if (featureName.matches(".*" + match)) {
                    out.print("5 | " + featureName);
                    found = true;
                    break;
                }
            }
            if (!found) {
                out.print("0 | " + featureName);
            }
        }
        for (int v = 0, vmax = getNumberOfValues(i); v < vmax; v++) {
            String val = getFeatureValueAsString(i, v);
            out.print(" " + val);
        }
        out.print("\n");
    }
    out.println("ShortValuedFeatureProcessors");
    for (int i = numByteFeatures; i < numShortFeatures; i++) {
        String featureName = getFeatureName(i);
        out.print("0 | " + featureName);
        for (int v = 0, vmax = getNumberOfValues(i); v < vmax; v++) {
            String val = getFeatureValueAsString(i, v);
            out.print(" " + val);
        }
        out.print("\n");
    }
    out.println("ContinuousFeatureProcessors");
    ImmutableMap<String, Integer> map = ImmutableMap.of("unit_duration", 1000, "unit_logf0", 100);
    for (int i = numByteFeatures; i < numByteFeatures + numContinuousFeatures; i++) {
        String featureName = getFeatureName(i);
        int featureValue = map.containsKey(featureName) ? map.get(featureName) : 0;
        out.printf("%d linear | %s\n", featureValue, featureName);
    }
    out.flush();
    out.close();
}

From source file:dagger2.internal.codegen.ComponentGenerator.java

private void initializeFrameworkTypes(BindingGraph input, ClassWriter componentWriter,
        ConstructorWriter constructorWriter, Optional<ClassName> builderName,
        Map<TypeElement, MemberSelect> componentContributionFields,
        ImmutableMap<BindingKey, MemberSelect> memberSelectSnippets,
        ImmutableMap<ContributionBinding, Snippet> parentMultibindingContributionSnippets,
        ImmutableMap<ContributionBinding, Snippet> multibindingContributionSnippets) throws AssertionError {
    List<List<BindingKey>> partitions = Lists.partition(input.resolvedBindings().keySet().asList(), 100);
    for (int i = 0; i < partitions.size(); i++) {
        MethodWriter initializeMethod = componentWriter.addMethod(VoidName.VOID,
                "initialize" + ((i == 0) ? "" : i));
        initializeMethod.body();/*from w w  w  .  j  ava 2s . com*/
        initializeMethod.addModifiers(PRIVATE);
        if (builderName.isPresent()) {
            initializeMethod.addParameter(builderName.get(), "builder").addModifiers(FINAL);
            constructorWriter.body().addSnippet("%s(builder);", initializeMethod.name());
        } else {
            constructorWriter.body().addSnippet("%s();", initializeMethod.name());
        }

        for (BindingKey bindingKey : partitions.get(i)) {
            Snippet memberSelectSnippet = memberSelectSnippets.get(bindingKey)
                    .getSnippetFor(componentWriter.name());
            ResolvedBindings resolvedBindings = input.resolvedBindings().get(bindingKey);
            switch (bindingKey.kind()) {
            case CONTRIBUTION:
                ImmutableSet<? extends ContributionBinding> bindings = resolvedBindings.contributionBindings();

                switch (ContributionBinding.bindingTypeFor(bindings)) {
                case SET:
                    boolean hasOnlyProvisions = Iterables.all(bindings,
                            Predicates.instanceOf(ProvisionBinding.class));
                    ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder();
                    for (ContributionBinding binding : bindings) {
                        if (multibindingContributionSnippets.containsKey(binding)) {
                            Snippet initializeSnippet = initializeFactoryForContributionBinding(binding, input,
                                    componentWriter.name(), componentContributionFields, memberSelectSnippets);
                            Snippet snippet = multibindingContributionSnippets.get(binding);
                            initializeMethod.body().addSnippet("this.%s = %s;", snippet, initializeSnippet);
                            parameterSnippets.add(snippet);
                        } else if (parentMultibindingContributionSnippets.containsKey(binding)) {
                            parameterSnippets.add(parentMultibindingContributionSnippets.get(binding));
                        } else {
                            throw new IllegalStateException(binding + " was not found in");
                        }
                    }
                    Snippet initializeSetSnippet = Snippet.format("%s.create(%s)",
                            hasOnlyProvisions ? ClassName.fromClass(SetFactory.class)
                                    : ClassName.fromClass(SetProducer.class),
                            Snippet.makeParametersSnippet(parameterSnippets.build()));
                    initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                            initializeSetSnippet);
                    break;
                case MAP:
                    if (Sets.filter(bindings, Predicates.instanceOf(ProductionBinding.class)).isEmpty()) {
                        @SuppressWarnings("unchecked") // checked by the instanceof filter above
                        ImmutableSet<ProvisionBinding> provisionBindings = (ImmutableSet<ProvisionBinding>) bindings;
                        for (ProvisionBinding provisionBinding : provisionBindings) {
                            if (!isNonProviderMap(provisionBinding)
                                    && multibindingContributionSnippets.containsKey(provisionBinding)) {
                                Snippet snippet = multibindingContributionSnippets.get(provisionBinding);
                                initializeMethod.body().addSnippet("this.%s = %s;", snippet,
                                        initializeFactoryForProvisionBinding(provisionBinding,
                                                componentWriter.name(),
                                                input.componentDescriptor().dependencyMethodIndex(),
                                                componentContributionFields, memberSelectSnippets));
                            }
                        }
                        if (!provisionBindings.isEmpty()) {
                            Snippet initializeMapSnippet = initializeMapBinding(componentWriter.name(),
                                    memberSelectSnippets,
                                    new ImmutableMap.Builder<ContributionBinding, Snippet>()
                                            .putAll(parentMultibindingContributionSnippets)
                                            .putAll(multibindingContributionSnippets).build(),
                                    provisionBindings);
                            initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                    initializeMapSnippet);
                        }
                    } else {
                        // TODO(user): Implement producer map bindings.
                        throw new IllegalStateException("producer map bindings not implemented yet");
                    }
                    break;
                case UNIQUE:
                    if (!resolvedBindings.ownedContributionBindings().isEmpty()) {
                        ContributionBinding binding = Iterables.getOnlyElement(bindings);
                        if (binding instanceof ProvisionBinding) {
                            ProvisionBinding provisionBinding = (ProvisionBinding) binding;
                            if (!provisionBinding.factoryCreationStrategy().equals(ENUM_INSTANCE)
                                    || provisionBinding.scope().isPresent()) {
                                initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                        initializeFactoryForProvisionBinding(provisionBinding,
                                                componentWriter.name(),
                                                input.componentDescriptor().dependencyMethodIndex(),
                                                componentContributionFields, memberSelectSnippets));
                            }
                        } else if (binding instanceof ProductionBinding) {
                            ProductionBinding productionBinding = (ProductionBinding) binding;
                            initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                    initializeFactoryForProductionBinding(productionBinding, input,
                                            componentWriter.name(),
                                            input.componentDescriptor().dependencyMethodIndex(),
                                            componentContributionFields, memberSelectSnippets));
                        } else {
                            throw new AssertionError();
                        }
                    }
                    break;
                default:
                    throw new IllegalStateException();
                }
                break;
            case MEMBERS_INJECTION:
                MembersInjectionBinding binding = Iterables
                        .getOnlyElement(resolvedBindings.membersInjectionBindings());
                if (!binding.injectionStrategy().equals(MembersInjectionBinding.Strategy.NO_OP)) {
                    initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                            initializeMembersInjectorForBinding(componentWriter.name(), binding,
                                    memberSelectSnippets));
                }
                break;
            default:
                throw new AssertionError();
            }
        }
    }
}

From source file:com.facebook.buck.features.apple.project.ProjectGenerator.java

private void addEntitlementsPlistIntoTarget(TargetNode<? extends HasAppleBundleFields> targetNode,
        PBXGroup targetGroup) {/* w  ww. j  a  v a  2  s.c o  m*/
    ImmutableMap<String, String> infoPlistSubstitutions = targetNode.getConstructorArg()
            .getInfoPlistSubstitutions();

    if (infoPlistSubstitutions.containsKey(AppleBundle.CODE_SIGN_ENTITLEMENTS)) {
        String entitlementsPlistPath = InfoPlistSubstitution.replaceVariablesInString(
                "$(" + AppleBundle.CODE_SIGN_ENTITLEMENTS + ")", AppleBundle.withDefaults(
                        infoPlistSubstitutions, ImmutableMap.of("SOURCE_ROOT", ".", "SRCROOT", ".")));

        targetGroup.getOrCreateFileReferenceBySourceTreePath(new SourceTreePath(
                PBXReference.SourceTree.SOURCE_ROOT, Paths.get(entitlementsPlistPath), Optional.empty()));
    }
}