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:com.pinterest.pinlater.PinLaterQueueConfig.java

@VisibleForTesting
double getDequeueRate(String queueName) {
    MorePreconditions.checkNotBlank(queueName);
    ImmutableMap<String, QueueRateLimiter.IFace> queueRateLimitMap = queueRateLimitMapRef.get();
    if (queueRateLimitMap != null && queueRateLimitMap.containsKey(queueName)) {
        return queueRateLimitMap.get(queueName).getRate();
    } else {// w  ww.ja v a2  s  . c o m
        // No rate limit specified for this queue.
        return Double.MAX_VALUE;
    }
}

From source file:com.pinterest.pinlater.PinLaterQueueConfig.java

/**
 * Determines whether a dequeue request should be allowed.
 *
 * @param queueName  name of the queue.// w w w. j  av  a  2s .  c  om
 * @param numJobs    number of jobs intended to be dequeued.
 * @return whether to allow the request.
 */
public boolean allowDequeue(String queueName, int numJobs) {
    MorePreconditions.checkNotBlank(queueName);
    Preconditions.checkArgument(numJobs > 0);
    ImmutableMap<String, QueueRateLimiter.IFace> queueRateLimitMap = queueRateLimitMapRef.get();
    if (queueRateLimitMap != null && queueRateLimitMap.containsKey(queueName)) {
        return queueRateLimitMap.get(queueName).allowDequeue(numJobs);
    } else {
        // No rate limit specified for this queue, so always allow.
        return true;
    }
}

From source file:com.google.devtools.build.android.ParsedAndroidDataSubject.java

private <T extends DataValue> void compareDataValues(Iterable<Entry<DataKey, T>> actual,
        Iterable<Entry<DataKey, T>> expected, List<String> out, String valueType) {
    List<String> errors = new ArrayList<>();
    ImmutableMap<DataKey, T> actualMap = ImmutableMap.copyOf(actual);
    ImmutableMap<DataKey, T> expectedMap = ImmutableMap.copyOf(expected);
    for (DataKey key : Sets.union(actualMap.keySet(), expectedMap.keySet())) {
        if (!(actualMap.containsKey(key) && expectedMap.containsKey(key))) {
            if (!actualMap.containsKey(key)) {
                errors.add(error("\tExpected %s.", key.toPrettyString()));
            }/*from   w  w  w .  ja v a 2  s. com*/
            if (!expectedMap.containsKey(key)) {
                errors.add(error("\tHad unexpected %s.", key.toPrettyString()));
            }
        } else {
            T actualValue = actualMap.get(key);
            T expectedValue = expectedMap.get(key);
            if (!actualValue.equals(expectedValue)) {
                errors.add(error("\t%s is not equal", key.toPrettyString()));
                if (!actualValue.source().equals(expectedValue.source())) {
                    if (!actualValue.source().getPath().equals(expectedValue.source().getPath())) {
                        errors.add(error("\t\t%-10s: %s", "Expected path", expectedValue.source().getPath()));
                        errors.add(error("\t\t%-10s: %s", "Actual path", actualValue.source().getPath()));
                    }
                    if (!actualValue.source().overrides().equals(expectedValue.source().overrides())) {
                        errors.add(error("\t\t%-10s: %s", "Expected overrides", expectedValue.source()));
                        errors.add(error("\t\t%-10s: %s", "Actual overrides", actualValue.source()));
                    }
                }
                if (!actualValue.getClass().equals(expectedValue.getClass())) {
                    errors.add(error("\t\t%-10s: %s", "Expected class", expectedValue.getClass()));
                    errors.add(error("\t\t%-10s: %s", "Actual class", actualValue.getClass()));
                } else if (actualValue instanceof DataResourceXml) {
                    errors.add(error("\t\t%-10s: %s", "Expected xml", expectedValue));
                    errors.add(error("\t\t%-10s: %s", "Actual xml", actualValue));
                }
            }
        }
    }
    if (errors.isEmpty()) {
        return;
    }
    out.add(valueType);
    out.add(Joiner.on("\n").join(errors));
}

From source file:com.srotya.flume.kinesis.sink.KinesisSink.java

@Override
public void configure(Context ctx) {
    ImmutableMap<String, String> props = ctx.getSubProperties(Constants.SETTINGS);
    if (!props.containsKey(Constants.ACCESS_KEY) || !props.containsKey(Constants.ACCESS_SECRET)) {
        Throwables.propagate(/*from ww w .j  a va 2  s.  c  o  m*/
                new InvalidArgumentException("Must provide AWS credentials i.e. accessKey and accessSecret"));
    }
    awsCredentials = new BasicAWSCredentials(props.get(Constants.ACCESS_KEY),
            props.get(Constants.ACCESS_SECRET));
    clientConfig = new ClientConfiguration();
    if (props.containsKey(Constants.PROXY_HOST)) {
        clientConfig.setProxyHost(props.get(Constants.PROXY_HOST));
        clientConfig.setProxyPort(Integer.parseInt(props.getOrDefault(Constants.PROXY_PORT, "80")));
        clientConfig.setProtocol(Protocol.valueOf(props.getOrDefault(Constants.PROTOCOL, "HTTPS")));
    }
    if (!props.containsKey(Constants.STREAM_NAME)) {
        Throwables.propagate(new InvalidArgumentException("Must provide Kinesis stream name"));
    }
    streamName = props.get(Constants.STREAM_NAME);
    putSize = Integer.parseInt(props.getOrDefault(Constants.PUT_SIZE, "100"));
    if (putSize > 500) {
        Throwables.propagate(
                new InvalidArgumentException("AWS Kinesis doesn't allow more than 500 put requests"));
    }
    endpoint = props.getOrDefault(Constants.ENDPOINT, Constants.DEFAULT_ENDPOINT);
    String serializerClass = props.getOrDefault(Constants.SERIALIZER, GsonSerializer.class.getName());
    try {
        serializer = (KinesisSerializer) Class.forName(serializerClass).newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        Throwables.propagate(e);
    }
    serializer.configure(props);
}

From source file:com.facebook.buck.skylark.parser.RuleFunctionFactory.java

/**
 * Populates provided {@code builder} with values from {@code kwargs} assuming {@code ruleClass}
 * as the target {@link BaseDescription} class.
 *
 * @param kwargs The keyword arguments and their values passed to rule function in build file.
 * @param builder The map builder used for storing extracted attributes and their values.
 * @param allParamInfo The parameter information for every build rule attribute.
 *///from  w  w w .ja v  a  2s  .  c  o m
private void populateAttributes(Map<String, Object> kwargs, ImmutableMap.Builder<String, Object> builder,
        ImmutableMap<String, ParamInfo> allParamInfo) {
    for (Map.Entry<String, Object> kwargEntry : kwargs.entrySet()) {
        String paramName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, kwargEntry.getKey());
        if (!allParamInfo.containsKey(paramName) && !(IMPLICIT_ATTRIBUTES.contains(kwargEntry.getKey()))) {
            throw new IllegalArgumentException(kwargEntry.getKey() + " is not a recognized attribute");
        }
        if (Runtime.NONE.equals(kwargEntry.getValue())) {
            continue;
        }
        builder.put(paramName, kwargEntry.getValue());
    }
}

From source file:com.facebook.buck.tools.consistency.RuleKeyFileParser.java

/**
 * Parse a thrift compact serialized file
 *
 * @param filename The name of the file// w w w . ja  va2 s.c o  m
 * @param targetNames The name of the targets that should be found
 * @return A {@link ParsedRuleKeyFile} object that all deserialized rules, and the rule key hash
 *     of the specified target
 * @throws ParseException If an IO or serialization error occurs, or if the target could not be
 *     found in the file
 */
public ParsedRuleKeyFile parseFile(Path filename, ImmutableSet<String> targetNames) throws ParseException {
    // If //foo/bar/... is passed in, we want to find all targets that start with
    // //foo/bar, and that are of the right type, and add them as root nodes
    ImmutableList<String> recursiveTargetPrefixes = targetNames.stream()
            .filter(name -> name.endsWith("/...") || name.endsWith(":")).map(name -> {
                int idx = name.lastIndexOf("/...");
                if (idx != -1) {
                    return name.substring(0, idx);
                } else {
                    return name;
                }
            }).collect(ImmutableList.toImmutableList());
    long startNanos = System.nanoTime();
    int initialSize;
    try {
        initialSize = Math.toIntExact(filename.toFile().length() / THRIFT_STRUCT_SIZE);
    } catch (ArithmeticException e) {
        throw new ParseException(e, filename,
                "File size is too large (>2.1 billion objects would be deserialized");
    }

    ImmutableMap.Builder<String, RuleKeyNode> rootNodesBuilder = ImmutableMap.builder();
    Map<String, RuleKeyNode> rules = new HashMap<>();

    try {
        reader.readFile(filename, ruleKey -> {
            RuleKeyNode newNode = new RuleKeyNode(ruleKey);
            if ("DEFAULT".equals(ruleKey.type)) {
                // If either a specific rule is present, or if the target starts with one of the
                // prefixes
                if (targetNames.contains(ruleKey.name) || recursiveTargetPrefixes.stream()
                        .filter(prefix -> ruleKey.name.startsWith(prefix)).findFirst().isPresent()) {
                    rootNodesBuilder.put(ruleKey.name, newNode);
                }
            }
            RuleKeyNode oldValue = rules.put(ruleKey.key, newNode);
            if (oldValue != null && !oldValue.ruleKey.equals(newNode.ruleKey)) {
                throw new RuntimeException(new ParseException(filename,
                        "Found two rules with the same key, but different values. Key: %s, first value: "
                                + "%s, second value: %s",
                        ruleKey.key, oldValue.ruleKey, newNode.ruleKey));
            }
            return false;
        });
    } catch (RuntimeException e) {
        if (e.getCause() instanceof ParseException) {
            throw (ParseException) e.getCause();
        }
    }

    ImmutableMap<String, RuleKeyNode> rootNodes = rootNodesBuilder.build();
    for (String targetName : targetNames) {
        if (!targetName.endsWith("/...") && !targetName.endsWith(":") && !rootNodes.containsKey(targetName)) {
            throw new ParseException(filename, "Could not find %s in %s", targetName, filename);
        }
    }
    Duration runtime = Duration.ofNanos(System.nanoTime() - startNanos);
    return new ParsedRuleKeyFile(filename, rootNodes, rules, runtime);
}

From source file:com.google.idea.blaze.base.sync.aspects.BlazeIdeInterfaceAspectsImpl.java

@Nullable
static State updateState(BlazeContext parentContext, @Nullable State prevState,
        ImmutableMap<File, Long> fileState, WorkspaceLanguageSettings workspaceLanguageSettings,
        ArtifactLocationDecoder artifactLocationDecoder, AspectStrategy aspectStrategy, List<File> newFiles,
        List<File> removedFiles, boolean mergeWithOldState) {
    Result<State> result = Scope.push(parentContext, (ScopedFunction<Result<State>>) context -> {
        context.push(new TimingScope("UpdateTargetMap"));

        // If we're not removing we have to merge the old state
        // into the new one or we'll miss file removes next time
        ImmutableMap<File, Long> nextFileState = fileState;
        if (mergeWithOldState && prevState != null) {
            ImmutableMap.Builder<File, Long> fileStateBuilder = ImmutableMap.<File, Long>builder()
                    .putAll(fileState);/*from w w w .j a va 2  s.co  m*/
            for (Map.Entry<File, Long> entry : prevState.fileState.entrySet()) {
                if (!fileState.containsKey(entry.getKey())) {
                    fileStateBuilder.put(entry);
                }
            }
            nextFileState = fileStateBuilder.build();
        }

        State state = new State();
        state.fileState = nextFileState;
        state.workspaceLanguageSettings = workspaceLanguageSettings;
        state.aspectStrategyName = aspectStrategy.getName();

        Map<TargetKey, TargetIdeInfo> targetMap = Maps.newHashMap();
        Map<TargetKey, TargetIdeInfo> updatedTargets = Maps.newHashMap();
        if (prevState != null) {
            targetMap.putAll(prevState.targetMap.map());
            state.fileToTargetMapKey.putAll(prevState.fileToTargetMapKey);
        }

        // Update removed unless we're merging with the old state
        if (!mergeWithOldState) {
            for (File removedFile : removedFiles) {
                TargetKey key = state.fileToTargetMapKey.remove(removedFile);
                if (key != null) {
                    targetMap.remove(key);
                }
            }
        }

        AtomicLong totalSizeLoaded = new AtomicLong(0);

        ListeningExecutorService executor = BlazeExecutor.getInstance().getExecutor();

        // Read protos from any new files
        List<ListenableFuture<TargetFilePair>> futures = Lists.newArrayList();
        for (File file : newFiles) {
            futures.add(executor.submit(() -> {
                totalSizeLoaded.addAndGet(file.length());
                try (InputStream inputStream = getAspectInputStream(file)) {
                    IntellijIdeInfo.TargetIdeInfo ruleProto = aspectStrategy.readAspectFile(inputStream);
                    TargetIdeInfo target = IdeInfoFromProtobuf.makeTargetIdeInfo(workspaceLanguageSettings,
                            ruleProto);
                    return new TargetFilePair(file, target);
                }
            }));
        }

        // Update state with result from proto files
        int duplicateTargetLabels = 0;
        try {
            for (TargetFilePair targetFilePairs : Futures.allAsList(futures).get()) {
                if (targetFilePairs.target != null) {
                    File file = targetFilePairs.file;
                    TargetKey key = targetFilePairs.target.key;
                    TargetIdeInfo previousTarget = updatedTargets.putIfAbsent(key, targetFilePairs.target);
                    if (previousTarget == null) {
                        state.fileToTargetMapKey.put(file, key);
                    } else {
                        duplicateTargetLabels++;
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return Result.error(null);
        } catch (ExecutionException e) {
            return Result.error(e);
        }
        targetMap.putAll(updatedTargets);

        context.output(PrintOutput.log(String.format("Loaded %d aspect files, total size %dkB", newFiles.size(),
                totalSizeLoaded.get() / 1024)));
        if (duplicateTargetLabels > 0) {
            context.output(new PerformanceWarning(String.format(
                    "There were %d duplicate rules. "
                            + "You may be including multiple configurations in your build. "
                            + "Your IDE sync is slowed down by ~%d%%.",
                    duplicateTargetLabels, (100 * duplicateTargetLabels / targetMap.size()))));
        }

        state.targetMap = new TargetMap(ImmutableMap.copyOf(targetMap));
        return Result.of(state);
    });

    if (result.error != null) {
        LOG.error(result.error);
        return null;
    }
    return result.result;
}

From source file:org.elasticsearch.action.admin.indices.exists.types.TransportTypesExistsAction.java

@Override
protected TypesExistsResponse masterOperation(TypesExistsRequest request, ClusterState state)
        throws ElasticSearchException {
    String[] concreteIndices = state.metaData().concreteIndices(request.indices(), request.ignoreIndices(),
            false);/*  www .j  a  va 2s. c om*/
    if (concreteIndices.length == 0) {
        return new TypesExistsResponse(false);
    }

    for (String concreteIndex : concreteIndices) {
        if (!state.metaData().hasConcreteIndex(concreteIndex)) {
            return new TypesExistsResponse(false);
        }

        ImmutableMap<String, MappingMetaData> mappings = state.metaData().getIndices().get(concreteIndex)
                .mappings();
        if (mappings.isEmpty()) {
            return new TypesExistsResponse(false);
        }

        for (String type : request.types()) {
            if (!mappings.containsKey(type)) {
                return new TypesExistsResponse(false);
            }
        }
    }

    return new TypesExistsResponse(true);
}

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

/**
 * Fills a partial map of Fresheners by creating new Fresheners for each record not already
 * reflected by the fresheners map.// w ww.ja  va  2s  .  c om
 *
 * @param readerUID unique identifier for the reader which called this method. Used for logging.
 * @param records a map of records for which to create Fresheners.
 * @param oldFresheners a partially filled map of Fresheners to be completed with new Fresheners
 *    built from the records map.
 * @return a map of Fresheners for each KijiFreshenerRecord in records.
 * @throws IOException in case of an error setting up a KijiFreshnessPolicy or ScoreFunction.
 */
private static ImmutableMap<KijiColumnName, Freshener> fillFresheners(final String readerUID,
        final ImmutableMap<KijiColumnName, KijiFreshenerRecord> records,
        final ImmutableMap<KijiColumnName, Freshener> oldFresheners) throws IOException {
    final Map<KijiColumnName, Freshener> fresheners = Maps.newHashMap();
    for (Map.Entry<KijiColumnName, KijiFreshenerRecord> entry : records.entrySet()) {
        if (!oldFresheners.containsKey(entry.getKey())) {
            // If there is not already a Freshener for this record, make one.

            final KijiFreshenerRecord record = entry.getValue();

            // Create the FreshenerSetupContext
            final InternalFreshenerContext context = InternalFreshenerContext.create(entry.getKey(),
                    record.getParameters());

            // Instantiate the policy and score function.
            final KijiFreshnessPolicy policy = ScoringUtils.policyForName(record.getFreshnessPolicyClass());
            final ScoreFunction<?> scoreFunction = ScoringUtils
                    .scoreFunctionForName(record.getScoreFunctionClass());

            // Create the KVStoreReaderFactory from the required stores of the score function and
            // policy, and add the factory to the Freshener context.
            final KeyValueStoreReaderFactory factory = ScoringUtils.createKVStoreReaderFactory(context,
                    scoreFunction, policy);
            context.setKeyValueStoreReaderFactory(factory);

            // Setup the policy and score function.
            policy.setup(context);
            scoreFunction.setup(context);

            // Build the Freshener from initialized components.
            final Freshener freshener = new Freshener(policy, scoreFunction, factory, entry.getKey(),
                    entry.getValue().getParameters());
            LOG.debug("{} loading new Freshener: {}", readerUID, freshener);
            fresheners.put(entry.getKey(), freshener);
        } else {
            // If there is already a Freshener for this key, save it.
            final Freshener oldFreshener = oldFresheners.get(entry.getKey());
            LOG.debug("{} preserving old Freshener: {}", readerUID, oldFreshener);
            fresheners.put(entry.getKey(), oldFreshener);
        }
    }

    return ImmutableMap.copyOf(fresheners);
}

From source file:bots.mctsbot.client.common.gamestate.modifiers.NewDealState.java

public NewDealState(NewDealEvent newDealEvent, GameState previousGame) {
    this.previousGame = previousGame;
    this.event = newDealEvent;
    this.tableConfiguration = previousGame.getTableConfiguration();
    this.seatMap = previousGame.getSeatMap();

    ImmutableMap.Builder<PlayerId, PlayerState> playerStateBuilder = ImmutableMap.builder();

    for (final SeatedPlayer player : newDealEvent.getPlayers()) {
        if (player.isSittingIn()) {
            AbstractPlayerState playerState = new AbstractPlayerState() {

                @Override//w ww. j a  v a  2s. c o m
                public String getName() {
                    return player.getName();
                }

                public int getBet() {
                    return 0;
                }

                @Override
                public int getTotalInvestment() {
                    return 0;
                }

                public Hand getCards() {
                    return new Hand();
                }

                public int getStack() {
                    return player.getStackValue();
                }

                public boolean hasFolded() {
                    return false;
                }

                public PlayerId getPlayerId() {
                    return player.getId();
                }

                public SeatId getSeatId() {
                    return player.getSeatId();
                }

                @Override
                public boolean hasChecked() {
                    return false;
                }

                @Override
                public boolean hasBeenDealt() {
                    return true;
                }

                @Override
                public List<Integer> getBetProgression() {
                    return new ArrayList<Integer>();
                }

            };
            playerStateBuilder.put(player.getId(), playerState);
        }
    }
    //also add players that are not being dealt a card.
    ImmutableMap<PlayerId, PlayerState> playerStatesInEvent = playerStateBuilder.build();
    for (PlayerState p : previousGame.getAllSeatedPlayers()) {
        if (!playerStatesInEvent.containsKey(p.getPlayerId())) {
            playerStateBuilder.put(p.getPlayerId(), new ForwardingPlayerState(p) {

                @Override
                public boolean hasBeenDealt() {
                    return false;
                }

            });
        }
    }
    playerStates = playerStateBuilder.build();
}