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

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.facebook.buck.apple.xcode.ProjectGenerator.java

private void addSourcePathToHeadersBuildPhase(SourcePath headerPath, PBXGroup headersGroup,
        PBXHeadersBuildPhase headersBuildPhase, ImmutableMap<SourcePath, String> sourceFlags) {
    Path path = headerPath.resolve();
    PBXFileReference fileReference = headersGroup.getOrCreateFileReferenceBySourceTreePath(new SourceTreePath(
            PBXReference.SourceTree.SOURCE_ROOT, this.repoRootRelativeToOutputDirectory.resolve(path)));
    PBXBuildFile buildFile = new PBXBuildFile(fileReference);
    NSDictionary settings = new NSDictionary();
    String headerFlags = sourceFlags.get(headerPath);
    if (headerFlags != null) {
        // If we specify nothing, Xcode will use "project" visibility.
        settings.put("ATTRIBUTES",
                new NSArray(new NSString(HeaderVisibility.fromString(headerFlags).toXcodeAttribute())));
        buildFile.setSettings(Optional.of(settings));
    } else {//  www .  j a v  a2  s. c o  m
        buildFile.setSettings(Optional.<NSDictionary>absent());
    }
    headersBuildPhase.getFiles().add(buildFile);
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefRepresentations(Contract savedContract, Contract translatedContract) {
    if (assertBothNull(savedContract.getRepresentations(), translatedContract.getRepresentations())) {
        return;/*from w ww.  j a v a  2 s.co  m*/
    }

    ImmutableMap<String, Representation> savedRepresentations = Maps
            .uniqueIndex(savedContract.getRepresentations(), new Function<Representation, String>() {
                public String apply(Representation representation) {
                    return representation.getName();
                }
            });
    ImmutableMap<String, Representation> translatedRepresentations = Maps
            .uniqueIndex(translatedContract.getRepresentations(), new Function<Representation, String>() {
                public String apply(Representation representation) {
                    return representation.getName();
                }
            });

    assertEquals(savedRepresentations.size(), translatedRepresentations.size());
    for (String key : savedRepresentations.keySet()) {
        Representation savedRepresentation = savedRepresentations.get(key);
        Representation translatedRepresentation = translatedRepresentations.get(key);
        assertNotNull(savedRepresentation);
        assertNotNull(translatedRepresentation);
        assertEquals(savedRepresentation.getDescription(), translatedRepresentation.getDescription());
        assertEquals(savedRepresentation.getExtendedType(), translatedRepresentation.getExtendedType());

        compareStringLists(savedRepresentation.getSections(), translatedRepresentation.getSections());
        compareRwadefProperties(savedRepresentation.getProperties(), translatedRepresentation.getProperties());
    }
}

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

@Override
ImmutableSet<JavaWriter> write(ClassName generatedTypeName, ProductionBinding binding) {
    TypeMirror keyType = binding.productionType().equals(Type.MAP)
            ? Util.getProvidedValueTypeOfMap(MoreTypes.asDeclared(binding.key().type()))
            : binding.key().type();/*w  w  w  .j  a v  a  2  s.  c  o  m*/
    TypeName providedTypeName = TypeNames.forTypeMirror(keyType);
    TypeName futureTypeName = ParameterizedTypeName.create(ClassName.fromClass(ListenableFuture.class),
            providedTypeName);
    JavaWriter writer = JavaWriter.inPackage(generatedTypeName.packageName());

    ClassWriter factoryWriter = writer.addClass(generatedTypeName.simpleName());
    ConstructorWriter constructorWriter = factoryWriter.addConstructor();
    constructorWriter.addModifiers(PUBLIC);

    factoryWriter.addField(binding.bindingTypeElement(), "module").addModifiers(PRIVATE, FINAL);
    constructorWriter.addParameter(binding.bindingTypeElement(), "module");
    constructorWriter.body().addSnippet("assert module != null;").addSnippet("this.module = module;");

    factoryWriter.addField(Executor.class, "executor").addModifiers(PRIVATE, FINAL);
    constructorWriter.addParameter(Executor.class, "executor");
    constructorWriter.body().addSnippet("assert executor != null;").addSnippet("this.executor = executor;");

    factoryWriter.annotate(Generated.class).setValue(ComponentProcessor.class.getName());
    factoryWriter.addModifiers(PUBLIC);
    factoryWriter.addModifiers(FINAL);
    factoryWriter.setSuperType(ParameterizedTypeName.create(AbstractProducer.class, providedTypeName));

    MethodWriter getMethodWriter = factoryWriter.addMethod(futureTypeName, "compute");
    getMethodWriter.annotate(Override.class);
    getMethodWriter.addModifiers(PROTECTED);

    final ImmutableMap<BindingKey, FrameworkField> fields = SourceFiles
            .generateBindingFieldsForDependencies(dependencyRequestMapper, binding.dependencies());

    for (FrameworkField bindingField : fields.values()) {
        TypeName fieldType = bindingField.frameworkType();
        FieldWriter field = factoryWriter.addField(fieldType, bindingField.name());
        field.addModifiers(PRIVATE, FINAL);
        constructorWriter.addParameter(field.type(), field.name());
        constructorWriter.body().addSnippet("assert %s != null;", field.name()).addSnippet("this.%1$s = %1$s;",
                field.name());
    }

    boolean returnsFuture = binding.bindingKind().equals(ProductionBinding.Kind.FUTURE_PRODUCTION);
    ImmutableList<DependencyRequest> asyncDependencies = FluentIterable.from(binding.dependencies())
            .filter(new Predicate<DependencyRequest>() {
                @Override
                public boolean apply(DependencyRequest dependency) {
                    return isAsyncDependency(dependency);
                }
            }).toList();

    for (DependencyRequest dependency : asyncDependencies) {
        ParameterizedTypeName futureType = ParameterizedTypeName
                .create(ClassName.fromClass(ListenableFuture.class), asyncDependencyType(dependency));
        String name = fields.get(dependency.bindingKey()).name();
        Snippet futureAccess = Snippet.format("%s.get()", name);
        getMethodWriter.body().addSnippet("%s %sFuture = %s;", futureType, name,
                dependency.kind().equals(DependencyRequest.Kind.PRODUCED)
                        ? Snippet.format("%s.createFutureProduced(%s)", ClassName.fromClass(Producers.class),
                                futureAccess)
                        : futureAccess);
    }

    if (asyncDependencies.isEmpty()) {
        ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder();
        for (DependencyRequest dependency : binding.dependencies()) {
            parameterSnippets.add(frameworkTypeUsageStatement(
                    Snippet.format(fields.get(dependency.bindingKey()).name()), dependency.kind()));
        }
        final boolean wrapWithFuture = false; // since submitToExecutor will create the future
        Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding, parameterSnippets.build());
        TypeName callableReturnType = returnsFuture ? futureTypeName : providedTypeName;
        Snippet throwsClause = getThrowsClause(binding.thrownTypes());
        Snippet callableSnippet = Snippet.format(
                Joiner.on('\n').join("new %1$s<%2$s>() {", "  @Override public %2$s call() %3$s{",
                        "    return %4$s;", "  }", "}"),
                ClassName.fromClass(Callable.class), callableReturnType, throwsClause, invocationSnippet);
        getMethodWriter.body().addSnippet("%s future = %s.submitToExecutor(%s, executor);",
                ParameterizedTypeName.create(ClassName.fromClass(ListenableFuture.class), callableReturnType),
                ClassName.fromClass(Producers.class), callableSnippet);
        getMethodWriter.body().addSnippet("return %s;",
                returnsFuture ? Snippet.format("%s.dereference(future)", ClassName.fromClass(Futures.class))
                        : "future");
    } else {
        final Snippet futureSnippet;
        final Snippet transformSnippet;
        if (asyncDependencies.size() == 1) {
            DependencyRequest asyncDependency = Iterables.getOnlyElement(asyncDependencies);
            futureSnippet = Snippet.format("%s", fields.get(asyncDependency.bindingKey()).name() + "Future");
            String argName = asyncDependency.requestElement().getSimpleName().toString();
            ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder();
            for (DependencyRequest dependency : binding.dependencies()) {
                // We really want to compare instances here, because asyncDependency is an element in the
                // set binding.dependencies().
                if (dependency == asyncDependency) {
                    parameterSnippets.add(Snippet.format("%s", argName));
                } else {
                    parameterSnippets.add(frameworkTypeUsageStatement(
                            Snippet.format(fields.get(dependency.bindingKey()).name()), dependency.kind()));
                }
            }
            boolean wrapWithFuture = !returnsFuture; // only wrap if we don't already have a future
            Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding,
                    parameterSnippets.build());
            Snippet throwsClause = getThrowsClause(binding.thrownTypes());
            transformSnippet = Snippet.format(
                    Joiner.on('\n').join("new %1$s<%2$s, %3$s>() {",
                            "  @Override public %4$s apply(%2$s %5$s) %6$s{", "    return %7$s;", "  }", "}"),
                    ClassName.fromClass(AsyncFunction.class), asyncDependencyType(asyncDependency),
                    providedTypeName, futureTypeName, argName, throwsClause, invocationSnippet);
        } else {
            futureSnippet = Snippet.format("%s.<%s>allAsList(%s)", ClassName.fromClass(Futures.class),
                    ClassName.fromClass(Object.class), Joiner.on(",").join(FluentIterable
                            .from(asyncDependencies).transform(new Function<DependencyRequest, String>() {
                                @Override
                                public String apply(DependencyRequest dependency) {
                                    return fields.get(dependency.bindingKey()).name() + "Future";
                                }
                            })));
            ImmutableList<Snippet> parameterSnippets = getParameterSnippets(binding, fields, "args");
            boolean wrapWithFuture = !returnsFuture; // only wrap if we don't already have a future
            Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding, parameterSnippets);
            ParameterizedTypeName listOfObject = ParameterizedTypeName.create(ClassName.fromClass(List.class),
                    ClassName.fromClass(Object.class));
            Snippet throwsClause = getThrowsClause(binding.thrownTypes());
            transformSnippet = Snippet.format(
                    Joiner.on('\n').join("new %1$s<%2$s, %3$s>() {",
                            "  @SuppressWarnings(\"unchecked\")  // safe by specification",
                            "  @Override public %4$s apply(%2$s args) %5$s{", "    return %6$s;", "  }", "}"),
                    ClassName.fromClass(AsyncFunction.class), listOfObject, providedTypeName, futureTypeName,
                    throwsClause, invocationSnippet);
        }
        getMethodWriter.body().addSnippet("return %s.%s(%s, %s, executor);", ClassName.fromClass(Futures.class),
                "transform", futureSnippet, transformSnippet);
    }

    // TODO(gak): write a sensible toString
    return ImmutableSet.of(writer);
}

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

private Snippet initializeMapBinding(ClassName componentName,
        ImmutableMap<BindingKey, MemberSelect> memberSelectSnippets,
        ImmutableMap<ContributionBinding, Snippet> multibindingContributionSnippets,
        Set<ProvisionBinding> bindings) {
    Iterator<ProvisionBinding> iterator = bindings.iterator();
    // get type information from first binding in iterator
    ProvisionBinding firstBinding = iterator.next();
    if (isNonProviderMap(firstBinding)) {
        return Snippet.format("%s.create(%s)", ClassName.fromClass(MapFactory.class),
                memberSelectSnippets.get(Iterables.getOnlyElement(firstBinding.dependencies()).bindingKey())
                        .getSnippetFor(componentName));
    } else {//from   w  ww.j  a v a2 s .c  om
        DeclaredType mapType = asDeclared(firstBinding.key().type());
        TypeMirror mapKeyType = Util.getKeyTypeOfMap(mapType);
        TypeMirror mapValueType = Util.getProvidedValueTypeOfMap(mapType); // V of Map<K, Provider<V>>
        StringBuilder snippetFormatBuilder = new StringBuilder("%s.<%s, %s>builder(%d)");
        for (int i = 0; i < bindings.size(); i++) {
            snippetFormatBuilder.append("\n    .put(%s, %s)");
        }
        snippetFormatBuilder.append("\n    .build()");

        List<Object> argsBuilder = Lists.newArrayList();
        argsBuilder.add(ClassName.fromClass(MapProviderFactory.class));
        argsBuilder.add(TypeNames.forTypeMirror(mapKeyType));
        argsBuilder.add(TypeNames.forTypeMirror(mapValueType));
        argsBuilder.add(bindings.size());

        writeEntry(argsBuilder, firstBinding, multibindingContributionSnippets.get(firstBinding));
        while (iterator.hasNext()) {
            ProvisionBinding binding = iterator.next();
            writeEntry(argsBuilder, binding, multibindingContributionSnippets.get(binding));
        }

        return Snippet.format(snippetFormatBuilder.toString(), argsBuilder.toArray(new Object[0]));
    }
}

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

@Override
@VisibleForTesting//from  w  ww . j a  v 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.commoncrawl.mapred.ec2.parser.ParserMapper.java

private static void safeAppendLinksFromFeed(JsonObject feedOrItemObj,
        ImmutableMap<String, String> validLinkTypes, List<FeedLink> feedMetaLinks, List links)
        throws IOException {
    for (Object link : links) {
        com.sun.syndication.feed.atom.Link linkObj = (com.sun.syndication.feed.atom.Link) link;
        if (linkObj.getHref() != null && linkObj.getRel() != null) {

            String canonicalHref = canonicalizeURL(linkObj.getHref());

            if (canonicalHref == null) {
                LOG.error("Failed to Canoniclize Link URL:" + linkObj.getHref());
            } else {
                if (validLinkTypes.keySet().contains(linkObj.getRel())) {
                    JsonObject jsonLink = new JsonObject();
                    FeedLink metaLink = new FeedLink();

                    safeSetString(jsonLink, "type", linkObj.getType());
                    if (linkObj.getType() != null)
                        metaLink.setType(linkObj.getType());
                    safeSetString(jsonLink, "href", canonicalHref);
                    if (linkObj.getHref() != null)
                        metaLink.setHref(canonicalHref);
                    safeSetString(jsonLink, "rel", linkObj.getRel());
                    if (linkObj.getRel() != null)
                        metaLink.setRel(linkObj.getRel());

                    safeSetString(jsonLink, "title", linkObj.getTitle());
                    if (linkObj.getTitle() != null)
                        metaLink.setTitle(linkObj.getTitle());

                    feedMetaLinks.add(metaLink);

                    String linkName = validLinkTypes.get(linkObj.getRel());

                    JsonElement existing = feedOrItemObj.get(linkName);
                    if (existing != null) {
                        JsonArray array = null;
                        if (!existing.isJsonArray()) {
                            array = new JsonArray();
                            array.add(existing);
                            feedOrItemObj.remove(linkName);
                            feedOrItemObj.add(linkName, array);
                        } else {
                            array = existing.getAsJsonArray();
                        }// www. j  a v  a2 s . com
                        array.add(jsonLink);
                    } else {
                        feedOrItemObj.add(linkName, jsonLink);
                    }
                }
            }
        }
    }
}

From source file:edu.mit.streamjit.impl.compiler2.Compiler2.java

/**
 * Restores output index functions from a backup returned from
 * {@link #adjustOutputIndexFunctions(com.google.common.base.Function)}.
 * @param backup the backup to restore/* ww  w .  j av  a  2  s  . c o  m*/
 */
private void restoreOutputIndexFunctions(ImmutableMap<Actor, ImmutableList<IndexFunction>> backup) {
    for (Actor a : actors) {
        ImmutableList<IndexFunction> oldFxns = backup.get(a);
        assert oldFxns != null : "no backup for " + a;
        assert oldFxns.size() == a.outputIndexFunctions().size() : "backup for " + a + " is wrong size";
        Collections.copy(a.outputIndexFunctions(), oldFxns);
    }
}