Java Code Examples for com.google.common.collect.ImmutableMap#get()

The following examples show how to use com.google.common.collect.ImmutableMap#get() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: turbine   File: ModelFactory.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source Project: buck   File: Pom.java    License: Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 3
Source Project: copybara   File: MainArguments.java    License: Apache License 2.0 6 votes vote down vote up
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())));
}
 
Example 4
@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"));
}
 
Example 5
@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)));
}
 
Example 6
/**
 * 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;
  }
}
 
Example 7
@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());
}
 
Example 8
@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());
}
 
Example 9
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();
}
 
Example 10
Source Project: intellij   File: ContentEntryEditor.java    License: Apache License 2.0 5 votes vote down vote up
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());
  }
}
 
Example 11
Source Project: buck   File: ExecutableFinder.java    License: Apache License 2.0 5 votes vote down vote up
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("");
}
 
Example 12
@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);
}
 
Example 13
Source Project: bazel   File: XmlResourceValues.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
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);
  }
}
 
Example 15
@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));
}
 
Example 16
Source Project: intellij   File: DependencyFinder.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 17
Source Project: nomulus   File: PremiumListUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 18
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);
			}
		}
	}
}
 
Example 19
@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);
}
 
Example 20
@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);
}