com.google.common.collect.ImmutableMap#get ( )源码实例Demo

下面列出了com.google.common.collect.ImmutableMap#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: turbine   文件: ModelFactory.java
TyVarInfo getTyVarInfo(TyVarSymbol tyVar) {
  Symbol owner = tyVar.owner();
  Verify.verifyNotNull(owner); // TODO(cushon): capture variables
  ImmutableMap<TyVarSymbol, TyVarInfo> tyParams;
  switch (owner.symKind()) {
    case METHOD:
      tyParams = getMethodInfo((MethodSymbol) owner).tyParams();
      break;
    case CLASS:
      tyParams = getSymbol((ClassSymbol) owner).typeParameterTypes();
      break;
    default:
      throw new AssertionError(owner.symKind());
  }
  return tyParams.get(tyVar);
}
 
源代码2 项目: buck   文件: Pom.java
private void updateModel(Artifact mavenCoordinates, Iterable<Artifact> deps) {
  model.setGroupId(mavenCoordinates.getGroupId());
  model.setArtifactId(mavenCoordinates.getArtifactId());
  model.setVersion(mavenCoordinates.getVersion());
  if (Strings.isNullOrEmpty(model.getName())) {
    model.setName(mavenCoordinates.getArtifactId()); // better than nothing
  }

  // Dependencies
  ImmutableMap<DepKey, Dependency> depIndex =
      Maps.uniqueIndex(getModel().getDependencies(), DepKey::new);
  for (Artifact artifactDep : deps) {
    DepKey key = new DepKey(artifactDep);
    Dependency dependency = depIndex.get(key);
    if (dependency == null) {
      dependency = key.createDependency();
      getModel().addDependency(dependency);
    }
    updateDependency(dependency, artifactDep);
  }
}
 
源代码3 项目: copybara   文件: MainArguments.java
CommandWithArgs parseCommand(ImmutableMap<String, ? extends CopybaraCmd> commands,
    CopybaraCmd defaultCmd) throws CommandLineException {
  if (unnamed.isEmpty()) {
    return new CommandWithArgs(defaultCmd, ImmutableList.of());
  }
  String firstArg = unnamed.get(0);
  // Default command might take a config file as param.
  if (firstArg.endsWith(COPYBARA_SKYLARK_CONFIG_FILENAME)) {
    return new CommandWithArgs(defaultCmd, ImmutableList.copyOf(unnamed));
  }

  if (!commands.containsKey(firstArg.toLowerCase())) {
    throw new CommandLineException(
        String.format("Invalid subcommand '%s'. Available commands: %s", firstArg,
            new TreeSet<>(commands.keySet())));
  }
  return new CommandWithArgs(commands.get(firstArg.toLowerCase()),
      ImmutableList.copyOf(unnamed.subList(1, unnamed.size())));
}
 
源代码4 项目: buck   文件: CxxPlatformBuildConfigurationTest.java
@Test
public void testResultHasOtherCxxFlagsTakenFromPlatformCxxflagsAndMergedWithAppendSettings() {
  LinkedHashMap<String, String> appendSettings = new LinkedHashMap<String, String>();
  appendSettings.put(CxxPlatformBuildConfiguration.OTHER_CPLUSPLUSFLAGS, "-flag1 -flag2");
  CxxPlatform platform =
      CxxPlatform.builder()
          .from(DEFAULT_PLATFORM)
          .setCxxflags(StringArg.from(ImmutableList.of("-Wno-warning", "-someflag", "-g")))
          .build();
  ImmutableMap<String, ImmutableMap<String, String>> buildConfigs =
      CxxPlatformBuildConfiguration.getDefaultBuildConfigurations(
          platform, appendSettings, DEFAULT_PATH_RESOLVER);
  ImmutableMap<String, String> settings =
      buildConfigs.get(BuildConfiguration.DEBUG_BUILD_CONFIGURATION_NAME);
  assertThat(
      settings.get(CxxPlatformBuildConfiguration.OTHER_CPLUSPLUSFLAGS),
      Matchers.equalTo("-flag1 -flag2 -Wno-warning -someflag -g"));
}
 
源代码5 项目: buck   文件: CxxPlatformBuildConfigurationTest.java
@Test
public void testResultHasCxxLibraryValueTakenFromAppendSettingsIfPresent() {
  LinkedHashMap<String, String> appendSettings = new LinkedHashMap<String, String>();
  appendSettings.put(CxxPlatformBuildConfiguration.CLANG_CXX_LIBRARY, "value");

  CxxPlatform platform =
      CxxPlatform.builder()
          .from(DEFAULT_PLATFORM)
          .setCxxflags(StringArg.from(ImmutableList.of("-stdlib=cxxflagsvalue")))
          .build();
  ImmutableMap<String, ImmutableMap<String, String>> buildConfigs =
      CxxPlatformBuildConfiguration.getDefaultBuildConfigurations(
          platform, appendSettings, DEFAULT_PATH_RESOLVER);
  ImmutableMap<String, String> settings =
      buildConfigs.get(BuildConfiguration.DEBUG_BUILD_CONFIGURATION_NAME);
  assertThat(
      settings.get(CxxPlatformBuildConfiguration.CLANG_CXX_LIBRARY),
      Matchers.equalTo(appendSettings.get(CxxPlatformBuildConfiguration.CLANG_CXX_LIBRARY)));
}
 
源代码6 项目: morf   文件: DataValueLookupMetadataRegistry.java
/**
 * Given an existing (interned) metadata descriptor, appends the given column and
 * returns the interned result.
 *
 * <p>Used when adding a new value to an existing {@link DataValueLookupBuilderImpl}.</p>
 *
 * <p>This call pattern means we can avoid constructing the combined {@link DataValueLookupMetadata}
 * simply to find that there is already an interned instance and throw it away. If the
 * metadata is already interned, the caller only needs to provide their current
 * metadata and the column name to add.</p>
 *
 * @param appendTo The metadata prior to appending the column.
 * @param columnName The column name to append.
 * @return The interned result.
 */
static DataValueLookupMetadata appendAndIntern(DataValueLookupMetadata appendTo, CaseInsensitiveString columnName) {

  ImmutableMap<CaseInsensitiveString, DataValueLookupMetadata> old = appendTo.getChildren();
  DataValueLookupMetadata result = old.get(columnName);
  if (result != null) {
    return result;
  }

  synchronized (appendTo) {

    ImmutableMap<CaseInsensitiveString, DataValueLookupMetadata> current = appendTo.getChildren();
    if (old != current) {
      result = current.get(columnName);
      if (result != null) {
        return result;
      }
    }

    result = new DataValueLookupMetadata(ImmutableList.<CaseInsensitiveString>builderWithExpectedSize(appendTo.getColumnNames().size() + 1)
        .addAll(appendTo.getColumnNames())
        .add(columnName)
        .build());

    appendTo.setChildren(
        builderPlusOneEntry(current)
            .putAll(current)
            .put(columnName, result)
            .build());

    return result;
  }
}
 
源代码7 项目: buck   文件: CxxPlatformBuildConfigurationTest.java
@Test
public void testResultHasNoArchSetToAllowAutomaticDeviceSwitchInXcode() {
  CxxPlatform platform =
      CxxPlatform.builder()
          .from(DEFAULT_PLATFORM)
          .setCxxflags(StringArg.from(ImmutableList.of("-arch", "x86-64")))
          .build();
  ImmutableMap<String, ImmutableMap<String, String>> buildConfigs =
      CxxPlatformBuildConfiguration.getDefaultBuildConfigurations(
          platform, new LinkedHashMap<>(), DEFAULT_PATH_RESOLVER);
  ImmutableMap<String, String> settings =
      buildConfigs.get(BuildConfiguration.DEBUG_BUILD_CONFIGURATION_NAME);
  assertThat(settings.get(CxxPlatformBuildConfiguration.ARCHS), Matchers.nullValue());
}
 
源代码8 项目: bundletool   文件: SplitApksGeneratorTest.java
@Test
public void simpleMultipleModules() throws Exception {

  ImmutableList<BundleModule> bundleModule =
      ImmutableList.of(
          new BundleModuleBuilder("base")
              .addFile("assets/leftover.txt")
              .setManifest(androidManifest("com.test.app"))
              .build(),
          new BundleModuleBuilder("test")
              .addFile("assets/test.txt")
              .setManifest(androidManifest("com.test.app"))
              .build());

  ImmutableList<ModuleSplit> moduleSplits =
      new SplitApksGenerator(
              bundleModule, BUNDLETOOL_VERSION, ApkGenerationConfiguration.getDefaultInstance())
          .generateSplits();

  assertThat(moduleSplits).hasSize(2);
  ImmutableMap<String, ModuleSplit> moduleSplitMap =
      Maps.uniqueIndex(moduleSplits, split -> split.getModuleName().getName());

  ModuleSplit baseModule = moduleSplitMap.get("base");
  assertThat(baseModule.getSplitType()).isEqualTo(SplitType.SPLIT);
  assertThat(extractPaths(baseModule.getEntries())).containsExactly("assets/leftover.txt");
  assertThat(baseModule.getVariantTargeting()).isEqualTo(lPlusVariantTargeting());

  ModuleSplit testModule = moduleSplitMap.get("test");
  assertThat(testModule.getSplitType()).isEqualTo(SplitType.SPLIT);
  assertThat(extractPaths(testModule.getEntries())).containsExactly("assets/test.txt");
  assertThat(testModule.getVariantTargeting()).isEqualTo(lPlusVariantTargeting());
}
 
源代码9 项目: javaide   文件: SvgLeafNode.java
private String getAttributeValues(ImmutableMap<String, String> presentationMap) {
    StringBuilder sb = new StringBuilder("/>\n");
    for (String key : mVdAttributesMap.keySet()) {
        String vectorDrawableAttr = presentationMap.get(key);
        String svgValue = mVdAttributesMap.get(key);
        String vdValue = svgValue.trim();
        // There are several cases we need to convert from SVG format to
        // VectorDrawable format. Like "none", "3px" or "rgb(255, 0, 0)"
        if ("none".equals(vdValue)) {
            vdValue = "#00000000";
        } else if (vdValue.endsWith("px")){
            vdValue = vdValue.substring(0, vdValue.length() - 2);
        } else if (vdValue.startsWith("rgb")) {
            vdValue = vdValue.substring(3, vdValue.length());
            vdValue = convertRGBToHex(vdValue);
            if (vdValue == null) {
                getTree().logErrorLine("Unsupported Color format " + vdValue, getDocumentNode(),
                                       SvgTree.SvgLogLevel.ERROR);
            }
        }
        String attr = "\n        " + vectorDrawableAttr + "=\"" +
                      vdValue + "\"";
        sb.insert(0, attr);

    }
    return sb.toString();
}
 
源代码10 项目: intellij   文件: ContentEntryEditor.java
private static void walkFileSystem(
    WorkspaceRoot workspaceRoot,
    SourceTestConfig testConfig,
    Collection<WorkspacePath> excludedDirectories,
    ContentEntry contentEntry,
    SourceFolderProvider provider,
    ImmutableMap<File, SourceFolder> sourceFolders,
    @Nullable SourceFolder parent,
    WorkspacePath workspacePath,
    DirectoryStructure directoryStructure) {
  if (excludedDirectories.contains(workspacePath)) {
    return;
  }
  File file = workspaceRoot.fileForPath(workspacePath);
  boolean isTest = testConfig.isTestSource(workspacePath.relativePath());
  SourceFolder current = sourceFolders.get(new File(file.getPath()));
  SourceFolder currentOrParent = current != null ? current : parent;
  if (currentOrParent != null && isTest != currentOrParent.isTestSource()) {
    currentOrParent =
        provider.setSourceFolderForLocation(contentEntry, currentOrParent, file, isTest);
    if (current != null) {
      contentEntry.removeSourceFolder(current);
    }
  }
  for (Map.Entry<WorkspacePath, DirectoryStructure> child :
      directoryStructure.directories.entrySet()) {
    walkFileSystem(
        workspaceRoot,
        testConfig,
        excludedDirectories,
        contentEntry,
        provider,
        sourceFolders,
        currentOrParent,
        child.getKey(),
        child.getValue());
  }
}
 
源代码11 项目: buck   文件: ExecutableFinder.java
private ImmutableSet<String> getExecutableSuffixes(ImmutableMap<String, String> env) {
  if (platform == Platform.WINDOWS) {
    String pathext = env.get("PATHEXT");
    if (pathext == null) {
      return DEFAULT_WINDOWS_EXTENSIONS;
    }
    return ImmutableSet.<String>builder()
        .addAll(Splitter.on(";").omitEmptyStrings().split(pathext))
        .build();
  }
  return ImmutableSet.of("");
}
 
@Test
public void test_map_contains_metric_registry() {

    final ImmutableMap<String, Object> dependenciesMap = pluginServicesDependencies.getDependenciesMap(
            new IsolatedPluginClassloader(new URL[]{}, this.getClass().getClassLoader()));

    final Object o = dependenciesMap.get(MetricRegistry.class.getCanonicalName());

    assertNotNull(o);
    assertTrue(o instanceof MetricRegistry);
}
 
源代码13 项目: bazel   文件: XmlResourceValues.java
static XmlResourceValue parsePublic(
    XMLEventReader eventReader, StartElement start, Namespaces.Collector namespacesCollector)
    throws XMLStreamException {
  namespacesCollector.collectFrom(start);
  // The tag should be unary.
  if (!isEndTag(eventReader.peek(), start.getName())) {
    throw new XMLStreamException(
        String.format("<public> tag should be unary %s", start), start.getLocation());
  }
  // The tag should have a valid type attribute, and optionally an id attribute.
  ImmutableMap<String, String> attributes = ImmutableMap.copyOf(parseTagAttributes(start));
  String typeAttr = attributes.get(SdkConstants.ATTR_TYPE);
  ResourceType type;
  if (typeAttr != null) {
    type = ResourceType.getEnum(typeAttr);
    if (type == null || type == ResourceType.PUBLIC) {
      throw new XMLStreamException(
          String.format("<public> tag has invalid type attribute %s", start),
          start.getLocation());
    }
  } else {
    throw new XMLStreamException(
        String.format("<public> tag missing type attribute %s", start), start.getLocation());
  }
  String idValueAttr = attributes.get(SdkConstants.ATTR_ID);
  Optional<Integer> id = Optional.absent();
  if (idValueAttr != null) {
    try {
      id = Optional.of(Integer.decode(idValueAttr));
    } catch (NumberFormatException e) {
      throw new XMLStreamException(
          String.format("<public> has invalid id number %s", start), start.getLocation());
    }
  }
  if (attributes.size() > 2) {
    throw new XMLStreamException(
        String.format("<public> has unexpected attributes %s", start), start.getLocation());
  }
  return PublicXmlResourceValue.create(type, id);
}
 
源代码14 项目: google-cloud-eclipse   文件: CloudLibraries.java
private static void resolveTransitiveDependencies(ImmutableMap<String, Library> map) {
  for (Library library : map.values()) {
    List<String> directDependencies = library.getLibraryDependencies();
    List<String> transitiveDependencies = Lists.newArrayList(directDependencies);
    for (String id : directDependencies) {
      Library dependency = map.get(id);
      for (String dependencyId : dependency.getLibraryDependencies()) {
        if (!transitiveDependencies.contains(dependencyId)) {
          transitiveDependencies.add(dependencyId);
        }
      }
    }
    library.setLibraryDependencies(transitiveDependencies);
  }
}
 
@Test
public void addingDepToTargetChangesHashOfDependingTargetOnly() throws Exception {
  tempDir.newFolder("foo");

  Path testFooBuckFile = tempDir.newFile("foo/BUCK");
  Files.write(
      testFooBuckFile,
      ("java_library(name = 'lib', deps = [], visibility=['PUBLIC'])\n"
              + "java_library(name = 'lib2', deps = [], visibility=['PUBLIC'])\n")
          .getBytes(UTF_8));

  BuildTarget fooLibTarget = BuildTargetFactory.newInstance("//foo", "lib");
  BuildTarget fooLib2Target = BuildTargetFactory.newInstance("//foo", "lib2");
  ImmutableMap<BuildTarget, HashCode> hashes =
      buildTargetGraphAndGetHashCodes(parser, fooLibTarget, fooLib2Target);
  HashCode libKey = hashes.get(fooLibTarget);
  HashCode lib2Key = hashes.get(fooLib2Target);

  parser = TestParserFactory.create(executor.get(), cell, knownRuleTypesProvider);
  Files.write(
      testFooBuckFile,
      ("java_library(name = 'lib', deps = [], visibility=['PUBLIC'])\njava_library("
              + "name = 'lib2', deps = [':lib'], visibility=['PUBLIC'])\n")
          .getBytes(UTF_8));

  hashes = buildTargetGraphAndGetHashCodes(parser, fooLibTarget, fooLib2Target);

  assertEquals(libKey, hashes.get(fooLibTarget));
  assertNotEquals(lib2Key, hashes.get(fooLib2Target));
}
 
源代码16 项目: intellij   文件: DependencyFinder.java
@Nullable
private static TargetInfo createTargetInfo(
    Dependency dependency, ImmutableMap<TargetKey, TargetIdeInfo> targetMap) {
  TargetKey key = dependency.getTargetKey();
  TargetIdeInfo ideInfo = targetMap.get(key);
  return ideInfo != null ? ideInfo.toTargetInfo() : null;
}
 
源代码17 项目: nomulus   文件: PremiumListUtilsTest.java
@Test
public void testSave_simple() {
  PremiumList pl =
      savePremiumListAndEntries(
          new PremiumList.Builder().setName("tld2").build(),
          ImmutableList.of("lol , USD 999 # yupper rooni "));
  createTld("tld");
  persistResource(Registry.get("tld").asBuilder().setPremiumList(pl).build());
  assertThat(getPremiumPrice("lol", Registry.get("tld"))).hasValue(Money.parse("USD 999"));
  assertThat(getPremiumPrice("lol ", Registry.get("tld"))).isEmpty();
  ImmutableMap<String, PremiumListEntry> entries =
      loadPremiumListEntries(PremiumList.getUncached("tld2").get());
  assertThat(entries.keySet()).containsExactly("lol");
  assertThat(entries).doesNotContainKey("lol ");
  PremiumListEntry entry = entries.get("lol");
  assertThat(entry.comment).isEqualTo("yupper rooni");
  assertThat(entry.price).isEqualTo(Money.parse("USD 999"));
  assertThat(entry.label).isEqualTo("lol");
  assertThat(premiumListChecks)
      .hasValueForLabels(1, "tld", "tld2", UNCACHED_POSITIVE.toString())
      .and()
      .hasValueForLabels(1, "tld", "tld2", BLOOM_FILTER_NEGATIVE.toString())
      .and()
      .hasNoOtherValues();
  assertThat(premiumListProcessingTime)
      .hasAnyValueForLabels("tld", "tld2", UNCACHED_POSITIVE.toString())
      .and()
      .hasAnyValueForLabels("tld", "tld2", BLOOM_FILTER_NEGATIVE.toString())
      .and()
      .hasNoOtherValues();
}
 
private void produceInTrx()
{
	final Properties ctx = Env.getCtx();
	final I_C_Order order = ordersRepo.getById(orderId);

	final ImmutableMap<OrderLineId, I_C_OrderLine> existingOrderLines = Maps.uniqueIndex(
			ordersRepo.retrieveOrderLines(orderId, I_C_OrderLine.class),
			orderLineRecord -> OrderLineId.ofRepoId(orderLineRecord.getC_OrderLine_ID()));

	for (final ProductsProposalRow row : rows)
	{
		final I_C_OrderLine existingOrderLine = row.getExistingOrderLineId() != null
				? existingOrderLines.get(row.getExistingOrderLineId())
				: null;
		if (existingOrderLine == null)
		{
			if (row.isQtySet())
			{
				OrderFastInput.addOrderLine(ctx, order, orderLine -> updateOrderLine(order, orderLine, row));
			}
			else
			{
				// if qty is not set, don't create the row
			}
		}
		else
		{
			if (row.isQtySet())
			{
				updateOrderLine(order, existingOrderLine, row);
				ordersRepo.save(existingOrderLine);
			}
			else
			{
				ordersRepo.delete(existingOrderLine);
			}
		}
	}
}
 
@Test
public void test_map_contains_will_publish_builder() {

    final ImmutableMap<String, Supplier<Object>> dependenciesMap = pluginBuilderDependencies.getDependenciesMap(new IsolatedPluginClassloader(new URL[]{}, this.getClass().getClassLoader()));

    final Supplier<Object> o = dependenciesMap.get(WillPublishBuilder.class.getCanonicalName());

    assertNotNull(o);
    assertTrue(o.get() instanceof WillPublishBuilder);
}
 
@Test
public void test_services_contains_security_registry() throws Exception {

    final Class<? extends ExtensionMain> pluginMainClass = createAndLoadPlugin();

    final ImmutableMap<String, Object> map = getServicesMap(pluginMainClass);

    final String securityRegistryKey = SecurityRegistry.class.getCanonicalName();
    assertTrue(map.containsKey(securityRegistryKey));

    final Object objectFromMap = map.get(securityRegistryKey);
    assertSame(securityRegistry, objectFromMap);
}