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:google.registry.tools.server.ListObjectsAction.java

/**
 * Returns the set of fields to return, aliased or not according to --full_field_names, and
 * with duplicates eliminated but the ordering otherwise preserved.
 *///from   w w  w  .  j  a  v a2s . c om
private ImmutableSet<String> getFieldsToUse(ImmutableSet<T> objects) {
    // Get the list of fields from the received parameter.
    List<String> fieldsToUse;
    if ((fields == null) || !fields.isPresent()) {
        fieldsToUse = new ArrayList<>();
    } else {
        fieldsToUse = Splitter.on(',').splitToList(fields.get());
        // Check whether any field name is the wildcard; if so, use all fields.
        if (fieldsToUse.contains("*")) {
            fieldsToUse = getAllAvailableFields(objects);
        }
    }
    // Handle aliases according to the state of the fullFieldNames parameter.
    final ImmutableMap<String, String> nameMapping = ((fullFieldNames != null) && fullFieldNames.isPresent()
            && fullFieldNames.get()) ? getFieldAliases() : getFieldAliases().inverse();
    return ImmutableSet.copyOf(Iterables.transform(Iterables.concat(getPrimaryKeyFields(), fieldsToUse),
            new Function<String, String>() {
                @Override
                public String apply(String field) {
                    // Rename fields that are in the map according to the map, and leave the others as is.
                    return nameMapping.containsKey(field) ? nameMapping.get(field) : field;
                }
            }));
}

From source file:google.registry.flows.domain.DomainCheckFlow.java

@Override
public EppResponse run() throws EppException {
    extensionManager.register(FeeCheckCommandExtension.class, LaunchCheckExtension.class);
    customLogic.beforeValidation();/*from   w w w  . j ava2 s.  c o  m*/
    extensionManager.validate();
    validateClientIsLoggedIn(clientId);
    List<String> targetIds = ((Check) resourceCommand).getTargetIds();
    verifyTargetIdCount(targetIds, maxChecks);
    DateTime now = clock.nowUtc();
    ImmutableMap.Builder<String, InternetDomainName> domains = new ImmutableMap.Builder<>();
    // Only check that the registrar has access to a TLD the first time it is encountered
    Set<String> seenTlds = new HashSet<>();
    for (String targetId : ImmutableSet.copyOf(targetIds)) {
        InternetDomainName domainName = validateDomainName(targetId);
        validateDomainNameWithIdnTables(domainName);
        // This validation is moderately expensive, so cache the results.
        domains.put(targetId, domainName);
        String tld = domainName.parent().toString();
        if (seenTlds.add(tld)) {
            checkAllowedAccessToTld(clientId, tld);
            if (!isSuperuser) {
                verifyNotInPredelegation(Registry.get(tld), now);
            }
        }
    }
    ImmutableMap<String, InternetDomainName> domainNames = domains.build();
    customLogic.afterValidation(
            DomainCheckFlowCustomLogic.AfterValidationParameters.newBuilder().setDomainNames(domainNames)
                    // TODO: Use as of date from fee extension v0.12 instead of now, if specificed.
                    .setAsOfDate(now).build());
    Set<String> existingIds = checkResourcesExist(DomainResource.class, targetIds, now);
    ImmutableList.Builder<DomainCheck> checks = new ImmutableList.Builder<>();
    for (String targetId : targetIds) {
        String message = getMessageForCheck(domainNames.get(targetId), existingIds, now);
        checks.add(DomainCheck.create(message == null, targetId, message));
    }
    BeforeResponseReturnData responseData = customLogic
            .beforeResponse(BeforeResponseParameters.newBuilder().setDomainChecks(checks.build())
                    .setResponseExtensions(getResponseExtensions(domainNames, now)).setAsOfDate(now).build());
    return responseBuilder.setResData(DomainCheckData.create(responseData.domainChecks()))
            .setExtensions(responseData.responseExtensions()).build();
}

From source file:dagger.internal.codegen.ComponentHierarchyValidator.java

private void validateSubcomponentMethods(ValidationReport.Builder<?> report,
        ComponentDescriptor componentDescriptor,
        ImmutableMap<TypeElement, TypeElement> existingModuleToOwners) {
    for (Map.Entry<ComponentMethodDescriptor, ComponentDescriptor> subcomponentEntry : componentDescriptor
            .subcomponentsByFactoryMethod().entrySet()) {
        ComponentMethodDescriptor subcomponentMethodDescriptor = subcomponentEntry.getKey();
        ComponentDescriptor subcomponentDescriptor = subcomponentEntry.getValue();
        // validate the way that we create subcomponents
        for (VariableElement factoryMethodParameter : subcomponentMethodDescriptor.methodElement()
                .getParameters()) {//w w w. j a v  a2 s. c  om
            TypeElement moduleType = MoreTypes.asTypeElement(factoryMethodParameter.asType());
            TypeElement originatingComponent = existingModuleToOwners.get(moduleType);
            if (originatingComponent != null) {
                /* Factory method tries to pass a module that is already present in the parent.
                 * This is an error. */
                report.addError(String.format(
                        "%s is present in %s. A subcomponent cannot use an instance of a "
                                + "module that differs from its parent.",
                        moduleType.getSimpleName(), originatingComponent.getQualifiedName()),
                        factoryMethodParameter);
            }
        }
        validateSubcomponentMethods(report, subcomponentDescriptor,
                new ImmutableMap.Builder<TypeElement, TypeElement>().putAll(existingModuleToOwners)
                        .putAll(Maps.toMap(
                                Sets.difference(subcomponentDescriptor.transitiveModuleTypes(),
                                        existingModuleToOwners.keySet()),
                                constant(subcomponentDescriptor.componentDefinitionType())))
                        .build());
    }
}

From source file:com.facebook.buck.jvm.java.intellij.IjModuleFactory.java

private Set<Path> findConfiguredGeneratedSourcePaths(TargetNode<?, ?> targetNode) {
    ImmutableMap<String, String> depToGeneratedSourcesMap = projectConfig.getDepToGeneratedSourcesMap();
    BuildTarget buildTarget = targetNode.getBuildTarget();

    Set<Path> generatedSourcePaths = null;

    for (BuildTarget dependencyTarget : targetNode.getDeps()) {
        String buildTargetName = dependencyTarget.toString();
        String generatedSourceWithPattern = depToGeneratedSourcesMap.get(buildTargetName);
        if (generatedSourceWithPattern != null) {
            String generatedSource = generatedSourceWithPattern.replaceAll("%name%",
                    buildTarget.getShortNameAndFlavorPostfix());
            Path generatedSourcePath = BuildTargets.getGenPath(projectFilesystem, buildTarget, generatedSource);

            if (generatedSourcePaths == null) {
                generatedSourcePaths = new HashSet<>();
            }/*from   w  w  w  .  j  av a 2  s  .c om*/

            generatedSourcePaths.add(generatedSourcePath);
        }
    }

    return generatedSourcePaths;
}

From source file:com.google.api.codegen.transformer.StaticLangApiMethodTransformer.java

private List<PathTemplateCheckView> generatePathTemplateChecks(MethodContext context,
        Iterable<FieldConfig> fieldConfigs) {
    List<PathTemplateCheckView> pathTemplateChecks = new ArrayList<>();
    if (!context.getFeatureConfig().enableStringFormatFunctions()) {
        return pathTemplateChecks;
    }/*w  w  w .ja  va2  s. c  om*/
    for (FieldConfig fieldConfig : fieldConfigs) {
        if (!fieldConfig.useValidation()) {
            // Don't generate a path template check if fieldConfig is not configured to use validation.
            continue;
        }
        FieldModel field = fieldConfig.getField();
        ImmutableMap<String, String> fieldNamePatterns = context.getMethodConfig().getFieldNamePatterns();
        String entityName = fieldNamePatterns.get(field.getSimpleName());
        if (entityName != null) {
            SingleResourceNameConfig resourceNameConfig = context.getSingleResourceNameConfig(entityName);
            if (resourceNameConfig == null) {
                String methodName = context.getMethodModel().getSimpleName();
                throw new IllegalStateException("No collection config with id '" + entityName
                        + "' required by configuration for method '" + methodName + "'");
            }
            PathTemplateCheckView.Builder check = PathTemplateCheckView.newBuilder();
            check.pathTemplateName(
                    context.getNamer().getPathTemplateName(context.getInterfaceConfig(), resourceNameConfig));
            check.paramName(context.getNamer().getVariableName(field));
            check.allowEmptyString(shouldAllowEmpty(context, field));
            check.validationMessageContext(context.getNamer().getApiMethodName(context.getMethodModel(),
                    context.getMethodConfig().getVisibility()));
            pathTemplateChecks.add(check.build());
        }
    }
    return pathTemplateChecks;
}

From source file:com.facebook.buck.config.AbstractCellConfig.java

/**
 * Translates the 'cell name'->override map into a 'Path'->override map.
 * @param pathMapping a map containing paths to all of the cells we want to query.
 * @return 'Path'->override map/*from  www  .  j a  va2s . co m*/
 */
public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<RelativeCellName, Path> pathMapping)
        throws MalformedOverridesException {

    ImmutableSet<RelativeCellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet())
            .filter(Predicates.not(ALL_CELLS_OVERRIDE::equals)).toSet();
    ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder();
    for (RelativeCellName cellWithOverride : relativeNamesOfCellsWithOverrides) {
        if (!pathMapping.containsKey(cellWithOverride)) {
            throw new MalformedOverridesException(
                    String.format("Trying to override settings for unknown cell %s", cellWithOverride));
        }
        pathsWithOverrides.add(pathMapping.get(cellWithOverride));
    }

    ImmutableMultimap<Path, RelativeCellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(),
            Functions.forMap(pathMapping));

    for (Path pathWithOverrides : pathsWithOverrides.build()) {
        ImmutableCollection<RelativeCellName> namesForPath = pathToRelativeName.get(pathWithOverrides);
        if (namesForPath.size() > 1) {
            throw new MalformedOverridesException(
                    String.format("Configuration override is ambiguous: cell rooted at %s is reachable "
                            + "as [%s]. Please override the config by placing a .buckconfig.local file in the "
                            + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath)));
        }
    }

    Map<Path, RawConfig> overridesByPath = new HashMap<>();
    for (Map.Entry<RelativeCellName, Path> entry : pathMapping.entrySet()) {
        RelativeCellName cellRelativeName = entry.getKey();
        Path cellPath = entry.getValue();
        RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath);
        RawConfig config = getForCell(cellRelativeName);
        if (configFromOtherRelativeName != null) {
            Preconditions.checkState(configFromOtherRelativeName.equals(config),
                    "Attempting to create cell %s at %s with conflicting overrides [%s] vs [%s].",
                    cellRelativeName, cellPath, configFromOtherRelativeName, config);
        } else {
            overridesByPath.put(cellPath, config);
        }
    }

    return ImmutableMap.copyOf(overridesByPath);
}

From source file:org.elasticsearch.action.bench.BenchmarkService.java

private final boolean isBenchmarkNode(DiscoveryNode node) {
    ImmutableMap<String, String> attributes = node.getAttributes();
    if (attributes.containsKey("bench")) {
        String bench = attributes.get("bench");
        return Boolean.parseBoolean(bench);
    }//from   w  w  w .ja va2  s  . com
    return false;
}

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

private void addSourcePathToSourcesBuildPhase(SourcePath sourcePath, PBXGroup sourcesGroup,
        PBXSourcesBuildPhase sourcesBuildPhase, ImmutableMap<SourcePath, String> sourceFlags) {
    PBXFileReference fileReference = sourcesGroup
            .getOrCreateFileReferenceBySourceTreePath(new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                    pathRelativizer.outputDirToRootRelative(sourcePathResolver.getPath(sourcePath))));
    PBXBuildFile buildFile = new PBXBuildFile(fileReference);
    sourcesBuildPhase.getFiles().add(buildFile);
    String customFlags = sourceFlags.get(sourcePath);
    if (customFlags != null) {
        NSDictionary settings = new NSDictionary();
        settings.put("COMPILER_FLAGS", customFlags);
        buildFile.setSettings(Optional.of(settings));
    }//  w  w  w.ja  v  a 2  s  .co m
    LOG.verbose("Added source path %s to group %s, flags %s, PBXFileReference %s", sourcePath,
            sourcesGroup.getName(), customFlags, fileReference);
}

From source file:com.facebook.buck.cli.ExopackageInstaller.java

private void installSecondaryDexFiles(Set<String> hashesToInstall, ImmutableMap<String, String> hashToBasename)
        throws Exception {
    try (TraceEventLogger ignored1 = TraceEventLogger.start(eventBus, "install_secondary_dexes")) {
        device.createForward(AGENT_PORT, AGENT_PORT);
        try {//from w w  w  .  ja  v a 2 s  .  co m
            for (String hash : hashesToInstall) {
                String basename = hashToBasename.get(hash);
                try (TraceEventLogger ignored2 = TraceEventLogger.start(eventBus, "install_secondary_dex",
                        ImmutableMap.of("basename", basename))) {
                    installSecondaryDex(device, AGENT_PORT, hash,
                            exopackageInfo.dexDirectory.resolve(basename));
                }
            }
            try (TraceEventLogger ignored2 = TraceEventLogger.start(eventBus,
                    "install_secondary_dex_metadata")) {

                // This is a bit gross.  It was a late addition.  Ideally, we could eliminate this, but
                // it wouldn't be terrible if we don't.  We store the dexed jars on the device
                // with the full SHA-1 hashes in their names.  This is the format that the loader uses
                // internally, so ideally we would just load them in place.  However, the code currently
                // expects to be able to copy the jars from a directory that matches the name in the
                // metadata file, like "secondary-1.dex.jar".  We don't want to give up putting the
                // hashes in the file names (because we use that to skip re-uploads), so just hack
                // the metadata file to have hash-like names.
                try (NamedTemporaryFile temp = new NamedTemporaryFile("metadata", "tmp")) {
                    com.google.common.io.Files.write(com.google.common.io.Files
                            .toString(exopackageInfo.metadata.toFile(), Charsets.UTF_8)
                            .replaceAll("secondary-(\\d+)\\.dex\\.jar (\\p{XDigit}{40}) ",
                                    "secondary-$2.dex.jar $2 "),
                            temp.get().toFile(), Charsets.UTF_8);

                    installFile(device, AGENT_PORT, "metadata.txt", temp.get());
                }
            }
        } finally {
            device.removeForward(AGENT_PORT, AGENT_PORT);
        }
    }
}

From source file:omero.cmd.fs.OriginalMetadataRequestI.java

/**
 * Read the given INI-style file and populate the maps with the properties from the corresponding sections.
 * @param file the file to read//from  ww  w .java2s .com
 * @param global the map in which to put the global metadata properties
 * @param series the map in which to put the series metadata properties
 */
protected void parseOriginalMetadataTxt(File file) {
    final Pattern section = Pattern.compile("\\s*\\[\\s*(.+?)\\s*\\]\\s*");
    rsp.globalMetadata = new TreeMap<String, RType>();
    rsp.seriesMetadata = new TreeMap<String, RType>();
    final ImmutableMap<String, Map<String, RType>> sections = ImmutableMap.of("GlobalMetadata",
            rsp.globalMetadata, "SeriesMetadata", rsp.seriesMetadata);
    Map<String, RType> currentSection = null;
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        while (true) {
            String line;
            line = in.readLine();
            if (line == null) {
                break;
            }
            Matcher matcher;
            if ((matcher = section.matcher(line)).matches()) {
                currentSection = sections.get(matcher.group(1));
            } else if (currentSection != null) {
                final Entry<String, String> keyValue = splitOnEquals(line);
                if (keyValue != null) {
                    currentSection.put(keyValue.getKey(), omero.rtypes.rstring(keyValue.getValue()));
                }
            }
        }
    } catch (IOException e) {
        if (helper != null) {
            helper.cancel(new ERR(), e, "reader-failure", "original-metadata", file.getPath());
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}