com.google.common.collect.ImmutableListMultimap Java Examples

The following examples show how to use com.google.common.collect.ImmutableListMultimap. 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 File: EclipseHack.java    From RetroFacebook with Apache License 2.0 6 votes vote down vote up
@Override public ImmutableList<String> determinePropertyOrder() throws IOException {
  Reader sourceReader;
  try {
    sourceReader = readerProvider.call();
  } catch (Exception e) {
    return ImmutableList.of();
  }
  try {
    String packageName = TypeSimplifier.packageNameOf(type);
    String className = type.getQualifiedName().toString();
    AbstractMethodExtractor extractor = new AbstractMethodExtractor();
    JavaTokenizer tokenizer = new JavaTokenizer(sourceReader);
    ImmutableListMultimap<String, String> methodOrders =
        extractor.abstractMethods(tokenizer, packageName);
    return methodOrders.get(className);
  } finally {
    sourceReader.close();
  }
}
 
Example #2
Source File: AWSSigningRequestInterceptor.java    From aws-signing-request-interceptor with MIT License 6 votes vote down vote up
private Multimap<String, String> params(String query) {
    final ImmutableListMultimap.Builder<String, String> queryParams = ImmutableListMultimap.builder();

    if (! Strings.isNullOrEmpty(query)) {
        for (String pair : SPLITTER.split(query)) {
            final int index = pair.indexOf('=');
            if (index > 0) {
                final String key = pair.substring(0, index);
                final String value = pair.substring(index + 1);
                queryParams.put(key, value);
            } else {
                queryParams.put(pair, "");
            }
        }
    }

    return queryParams.build();
}
 
Example #3
Source File: GitHubApiTransportImpl.java    From copybara with Apache License 2.0 6 votes vote down vote up
private HttpRequestFactory getHttpRequestFactory(
    @Nullable UserPassword userPassword, ImmutableListMultimap<String, String> headers) {
  return httpTransport.createRequestFactory(
      request -> {
        request.setConnectTimeout((int) Duration.ofMinutes(1).toMillis());
        request.setReadTimeout((int) Duration.ofMinutes(1).toMillis());
        HttpHeaders httpHeaders = new HttpHeaders();
        if (userPassword != null) {
          httpHeaders.setBasicAuthentication(userPassword.getUsername(),
              userPassword.getPassword_BeCareful());
        }
        for (Map.Entry<String, Collection<String>> header : headers.asMap().entrySet()) {
          httpHeaders.put(header.getKey(), header.getValue());
        }
        request.setHeaders(httpHeaders);
        request.setParser(new JsonObjectParser(JSON_FACTORY));
      });
}
 
Example #4
Source File: Rule.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void addLabelOutput(
    Attribute attribute,
    Label label,
    EventHandler eventHandler,
    ImmutableList.Builder<OutputFile> outputFilesBuilder,
    ImmutableListMultimap.Builder<String, OutputFile> outputFileMapBuilder,
    boolean performChecks)
    throws LabelSyntaxException {
  if (performChecks) {
    if (!label.getPackageIdentifier().equals(pkg.getPackageIdentifier())) {
      throw new IllegalStateException("Label for attribute " + attribute
          + " should refer to '" + pkg.getName()
          + "' but instead refers to '" + label.getPackageFragment()
          + "' (label '" + label.getName() + "')");
    }
    if (label.getName().equals(".")) {
      throw new LabelSyntaxException("output file name can't be equal '.'");
    }
  }
  OutputFile outputFile = addOutputFile(label, eventHandler, outputFilesBuilder);
  outputFileMapBuilder.put(attribute.getName(), outputFile);
}
 
Example #5
Source File: CassandraSchedulerTest.java    From cassandra-mesos-deprecated with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceOffers_canHandleOffersWithMixedRoles() throws InvalidProtocolBufferException {
    cleanState("someOtherRole");
    Protos.Offer offer = createOffer(slaves[0]);

    scheduler.resourceOffers(driver, newArrayList(offer));

    Collection<Protos.TaskInfo> launchedTasks = driver.launchTasks()._2;
    assertThat(launchedTasks).isNotEmpty();
    Protos.TaskInfo launchedTask = launchedTasks.iterator().next();
    List<Protos.Resource> resources = launchedTask.getResourcesList();
    ImmutableListMultimap<String, Protos.Resource> resourceMap = FluentIterable.from(resources)
            .index(resourceByName());

    Protos.Resource cpus = resourceMap.get("cpus").get(0);
    assertThat(cpus.getRole()).isEqualTo("*");
    assertThat(cpus.getScalar().getValue()).isEqualTo(0.1);

    Protos.Resource mem = resourceMap.get("mem").get(0);
    assertThat(mem.getRole()).isEqualTo("*");
    assertThat(mem.getScalar().getValue()).isEqualTo(32.0);
}
 
Example #6
Source File: EclipseHack.java    From RetroFacebook with Apache License 2.0 6 votes vote down vote up
@Override public ImmutableList<String> determinePropertyOrder() throws IOException {
  Reader sourceReader;
  try {
    sourceReader = readerProvider.call();
  } catch (Exception e) {
    return ImmutableList.of();
  }
  try {
    String packageName = TypeSimplifier.packageNameOf(type);
    String className = type.getQualifiedName().toString();
    AbstractMethodExtractor extractor = new AbstractMethodExtractor();
    JavaTokenizer tokenizer = new JavaTokenizer(sourceReader);
    ImmutableListMultimap<String, String> methodOrders =
        extractor.abstractMethods(tokenizer, packageName);
    return methodOrders.get(className);
  } finally {
    sourceReader.close();
  }
}
 
Example #7
Source File: ClassPathResultTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormatDependencyPaths_threePathsForA() {
  ImmutableListMultimap<ClassPathEntry, DependencyPath> tree =
      ImmutableListMultimap.of(
          jarA, dependencyPath_A, jarA, dependencyPath_B_A, jarA, dependencyPath_A_B_A);

  ClassPathResult classPathResult = new ClassPathResult(tree, ImmutableSet.of());

  String actual = classPathResult.formatDependencyPaths(ImmutableList.of(jarA));

  assertEquals(
      "com.google:a:1 is at:\n"
          + "  com.google:a:1 (compile)\n"
          + "  and 2 other dependency paths.\n",
      actual);
}
 
Example #8
Source File: Manifest.java    From buck with Apache License 2.0 6 votes vote down vote up
private boolean hashesMatch(
    FileHashLoader fileHashLoader,
    SourcePathResolverAdapter resolver,
    ImmutableListMultimap<String, SourcePath> universe,
    int[] hashIndices)
    throws IOException {
  for (int hashIndex : hashIndices) {
    Pair<Integer, HashCode> hashEntry = hashes.get(hashIndex);
    String input = inputs.get(hashEntry.getFirst());
    ImmutableList<SourcePath> candidates = universe.get(input);
    if (candidates.isEmpty()) {
      return false;
    }
    HashCode onDiskHeaderHash;
    try {
      onDiskHeaderHash = hashSourcePathGroup(fileHashLoader, resolver, candidates);
    } catch (NoSuchFileException e) {
      return false;
    }
    HashCode inputHash = hashEntry.getSecond();
    if (!inputHash.equals(onDiskHeaderHash)) {
      return false;
    }
  }
  return true;
}
 
Example #9
Source File: GitRepository.java    From copybara with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve a reference
 *
 * @throws CannotResolveRevisionException if it cannot resolve the reference
 */
GitRevision resolveReferenceWithContext(String reference, @Nullable String contextRef,
    String url)
    throws RepoException, CannotResolveRevisionException {
  // Nothing needs to be resolved, since it is a complete SHA-1. But we
  // check that the reference exists.
  if (GitRevision.COMPLETE_SHA1_PATTERN.matcher(reference).matches()) {
    if (checkSha1Exists(reference)) {
      return new GitRevision(this, reference);
    }
    throw new CannotResolveRevisionException(
        "Cannot find '" + reference + "' object in the repository");
  }
  return new GitRevision(this, parseRef(reference), /*reviewReference=*/null, contextRef,
      ImmutableListMultimap.of(), url);
}
 
Example #10
Source File: GitHubDestinationTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
private void process(Writer<GitRevision> writer, DummyRevision ref)
    throws ValidationException, RepoException, IOException {
  TransformResult result = TransformResults.of(workdir, ref);

  Changes changes = new Changes(
      ImmutableList.of(
          new Change<>(ref, new Author("foo", "[email protected]"), "message",
              ZonedDateTime.now(ZoneOffset.UTC), ImmutableListMultimap.of("my_label", "12345")),
          new Change<>(ref, new Author("foo", "[email protected]"), "message",
              ZonedDateTime.now(ZoneOffset.UTC), ImmutableListMultimap.of("my_label", "6789"))),
      ImmutableList.of());
  result = result.withChanges(changes);
  ImmutableList<DestinationEffect> destinationResult =
      writer.write(result, destinationFiles, console);
  assertThat(destinationResult).hasSize(1);
  assertThat(destinationResult.get(0).getErrors()).isEmpty();
  assertThat(destinationResult.get(0).getType()).isEqualTo(Type.CREATED);
  assertThat(destinationResult.get(0).getDestinationRef().getType()).isEqualTo("commit");
  assertThat(destinationResult.get(0).getDestinationRef().getId()).matches("[0-9a-f]{40}");
}
 
Example #11
Source File: NettyServerStreamTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void writeHeadersShouldSendHeaders() throws Exception {
  Metadata headers = new Metadata();
  ListMultimap<CharSequence, CharSequence> expectedHeaders =
      ImmutableListMultimap.copyOf(Utils.convertServerHeaders(headers));

  stream().writeHeaders(headers);

  ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap =
      ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
  verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true));
  SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue();
  assertThat(sendHeaders.stream()).isSameAs(stream.transportState());
  assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers()))
      .containsExactlyEntriesIn(expectedHeaders);
  assertThat(sendHeaders.endOfStream()).isFalse();
}
 
Example #12
Source File: RecordsProcessCallDestination.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Override
public void visitChangesWithAnyLabel(Revision start, ImmutableCollection<String> labels,
    ChangesLabelVisitor visitor) throws RepoException, ValidationException {

  for (ProcessedChange processedChange : Lists.reverse(processed)) {

    VisitResult result =
        visitor.visit(
            new Change<>(
                processedChange.getOriginRef(),
                processedChange.getAuthor(),
                processedChange.getChangesSummary(),
                processedChange.getTimestamp(),
                ImmutableListMultimap.of()),
            ImmutableMap.copyOf(labels
                .stream()
                .collect(Collectors.toMap(
                        Function.identity(), e -> processedChange.getOriginRef().asString()))));
    if (result == VisitResult.TERMINATE) {
      return;
    }
  }

}
 
Example #13
Source File: TestMergeIntersect.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotFlattening()
{
    tester().assertThat(new MergeIntersect())
            .on(p -> {
                Symbol a = p.symbol("a");
                Symbol b = p.symbol("b");
                Symbol c = p.symbol("c");
                return p.intersect(
                        ImmutableListMultimap.<Symbol, Symbol>builder()
                                .put(c, a)
                                .put(c, b)
                                .build(),
                        ImmutableList.of(p.values(1, a), p.values(1, b)));
            })
            .doesNotFire();
}
 
Example #14
Source File: MediaType.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Parses a media type from its string representation.
 *
 * @throws IllegalArgumentException if the input is not parsable
 */
public static MediaType parse(String input) {
  checkNotNull(input);
  Tokenizer tokenizer = new Tokenizer(input);
  try {
    String type = tokenizer.consumeToken(TOKEN_MATCHER);
    tokenizer.consumeCharacter('/');
    String subtype = tokenizer.consumeToken(TOKEN_MATCHER);
    ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder();
    while (tokenizer.hasMore()) {
      tokenizer.consumeCharacter(';');
      tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
      String attribute = tokenizer.consumeToken(TOKEN_MATCHER);
      tokenizer.consumeCharacter('=');
      final String value;
      if ('"' == tokenizer.previewChar()) {
        tokenizer.consumeCharacter('"');
        StringBuilder valueBuilder = new StringBuilder();
        while ('"' != tokenizer.previewChar()) {
          if ('\\' == tokenizer.previewChar()) {
            tokenizer.consumeCharacter('\\');
            valueBuilder.append(tokenizer.consumeCharacter(ascii()));
          } else {
            valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER));
          }
        }
        value = valueBuilder.toString();
        tokenizer.consumeCharacter('"');
      } else {
        value = tokenizer.consumeToken(TOKEN_MATCHER);
      }
      parameters.put(attribute, value);
    }
    return create(type, subtype, parameters.build());
  } catch (IllegalStateException e) {
    throw new IllegalArgumentException("Could not parse '" + input + "'", e);
  }
}
 
Example #15
Source File: ExopackageInstaller.java    From buck with Apache License 2.0 5 votes vote down vote up
private void deleteFiles(ImmutableSortedSet<Path> filesToDelete) {
  filesToDelete.stream()
      .collect(
          ImmutableListMultimap.toImmutableListMultimap(
              path -> dataRoot.resolve(path).getParent(), path -> path.getFileName().toString()))
      .asMap()
      .forEach(
          (dir, files) -> {
            device.rmFiles(dir.toString(), files);
          });
}
 
Example #16
Source File: ConsoleEventMonitorTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
private Change<DummyRevision> newChange(String revision) {
  return new Change<>(
      new DummyRevision(revision),
      new Author("Foo", "Bar"),
      "Lorem Ipsum",
      ZonedDateTime.now(ZoneId.systemDefault()),
      ImmutableListMultimap.of());
}
 
Example #17
Source File: DocService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private ServiceSpecification addExamples(ServiceSpecification spec) {
    return new ServiceSpecification(
            spec.services().stream()
                .map(this::addServiceExamples)
                .collect(toImmutableList()),
            spec.enums(), spec.structs(), spec.exceptions(),
            Iterables.concat(spec.exampleHttpHeaders(),
                             exampleHttpHeaders.getOrDefault("", ImmutableListMultimap.of()).get("")));
}
 
Example #18
Source File: CxxDescriptionEnhancer.java    From buck with Apache License 2.0 5 votes vote down vote up
private static ImmutableListMultimap<CxxSource.Type, Arg> createCompilerFlagsForCxxBinary(
    BuildTarget target,
    CellPathResolver cellRoots,
    ActionGraphBuilder graphBuilder,
    CxxLinkOptions linkOptions,
    CxxPlatform cxxPlatform,
    ImmutableList<StringWithMacros> compilerFlags,
    ImmutableMap<Type, ImmutableList<StringWithMacros>> langCompilerFlags,
    PatternMatchedCollection<ImmutableList<StringWithMacros>> platformCompilerFlags,
    ImmutableMap<Type, PatternMatchedCollection<ImmutableList<StringWithMacros>>>
        langPlatformCompilerFlags) {
  StringWithMacrosConverter macrosConverter =
      getStringWithMacrosArgsConverter(target, cellRoots, graphBuilder, cxxPlatform);
  ImmutableListMultimap.Builder<CxxSource.Type, Arg> allCompilerFlagsBuilder =
      ImmutableListMultimap.builder();
  allCompilerFlagsBuilder.putAll(
      Multimaps.transformValues(
          CxxFlags.getLanguageFlagsWithMacros(
              compilerFlags,
              platformCompilerFlags,
              langCompilerFlags,
              langPlatformCompilerFlags,
              cxxPlatform),
          macrosConverter::convert));
  if (linkOptions.getThinLto()) {
    allCompilerFlagsBuilder.putAll(CxxFlags.toLanguageFlags(StringArg.from("-flto=thin")));
  } else if (linkOptions.getFatLto()) {
    allCompilerFlagsBuilder.putAll(CxxFlags.toLanguageFlags(StringArg.from("-flto")));
  }

  return allCompilerFlagsBuilder.build();
}
 
Example #19
Source File: ListMultimapPropertiesTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testMutate() {
  ListMultimapPropertyType value = new ListMultimapPropertyType.Builder()
      .putNumbers(1, "one")
      .putNumbers(1, "uno")
      .putNumbers(2, "two")
      .putNumbers(2, "dos")
      .mutateNumbers(numbers -> numbers.entries().forEach(entry -> entry.setValue(
          entry.getValue().toUpperCase() + " (" + entry.getKey() + ")")))
      .build();
  assertEquals(ImmutableListMultimap.of(1, "ONE (1)", 1, "UNO (1)", 2, "TWO (2)", 2, "DOS (2)"),
      value.getNumbers());
}
 
Example #20
Source File: HowToCollectToCustomTypesTest.java    From mug with Apache License 2.0 5 votes vote down vote up
@Test public void how_to_collect_to_immutableListMultimap() {
  BiStream<String, Integer> biStream = BiStream.of("one", 1, "two", 2);
  ImmutableListMultimap<String, Integer> map =
      biStream.collect(new BiCollector<String, Integer, ImmutableListMultimap<String, Integer>>() {
        @Override
        public <E> Collector<E, ?, ImmutableListMultimap<String, Integer>> splitting(Function<E, String> toKey, Function<E, Integer> toValue) {
          return ImmutableListMultimap.toImmutableListMultimap(toKey,toValue);
        }
      });
  assertThat(map).containsExactly("one", 1, "two", 2);
}
 
Example #21
Source File: QlikAppMessageBodyGenerator.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(DatasetConfig dataset, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
    throws IOException, WebApplicationException {

  List<ViewFieldType> viewFieldTypes = ViewFieldsHelper.getViewFields(dataset);

  ImmutableListMultimap<QlikFieldType, ViewFieldType> mapping = FluentIterable.from(viewFieldTypes).index(FIELD_TO_QLIKTYPE);

  DatasetPath datasetPath = new DatasetPath(dataset.getFullPathList());

  // qlik doesn't like certain characters as an identifier, so lets remove them
  String sanitizedDatasetName = dataset.getName().replaceAll("["+ Pattern.quote("/!@ *-=+{}<>,~")+"]+", "_");

  try (PrintWriter pw = new PrintWriter(entityStream)) {
    pw.println("SET DirectIdentifierQuoteChar='" + QUOTE + "';");
    pw.println();
    pw.println("LIB CONNECT TO 'Dremio';");
    pw.println();
    // Create a resident load so that data can be referenced later
    pw.format("%s: DIRECT QUERY\n", sanitizedDatasetName);
    for(Map.Entry<QlikFieldType, Collection<ViewFieldType>> entry: mapping.asMap().entrySet()) {
      writeFields(pw, entry.getKey().name(), entry.getValue());
    }

    /* Qlik supports paths with more than 2 components ("foo"."bar"."baz"."boo"), but each individual path segment
     * must be quoted to work with Dremio.  SqlUtils.quoteIdentifier will only quote when needed, so we do another
     * pass to ensure they are quoted. */
    final List<String> quotedPathComponents = Lists.newArrayList();
    for (final String component : dataset.getFullPathList()) {
      String quoted = SqlUtils.quoteIdentifier(component);
      if (!quoted.startsWith(String.valueOf(SqlUtils.QUOTE)) || !quoted.endsWith(String.valueOf(SqlUtils.QUOTE))) {
        quoted = quoteString(quoted);
      }
      quotedPathComponents.add(quoted);
    }

    pw.format("  FROM %1$s;\n", Joiner.on('.').join(quotedPathComponents));
  }
}
 
Example #22
Source File: MapStreamTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void toListMultimap() {
  Map<String, Integer> map = ImmutableMap.of("a", 1, "aa", 2, "b", 10, "bb", 20, "c", 1);
  ListMultimap<String, Integer> expected = ImmutableListMultimap.of("a", 1, "a", 2, "b", 10, "b", 20, "c", 1);
  ListMultimap<String, Integer> result = MapStream.of(map).mapKeys(s -> s.substring(0, 1)).toListMultimap();
  assertThat(result).isEqualTo(expected);
}
 
Example #23
Source File: CycleDetectingLock.java    From businessworks with Apache License 2.0 5 votes vote down vote up
/**
 * Algorithm to detect a potential lock cycle.
 *
 * For lock's thread owner check which lock is it trying to take.
 * Repeat recursively. When current thread is found a potential cycle is detected.
 *
 * @see CycleDetectingLock#lockOrDetectPotentialLocksCycle()
 */
private ListMultimap<Long, ID> detectPotentialLocksCycle() {
  final long currentThreadId = Thread.currentThread().getId();
  if (lockOwnerThreadId == null || lockOwnerThreadId == currentThreadId) {
    // if nobody owns this lock, lock cycle is impossible
    // if a current thread owns this lock, we let Guice to handle it
    return ImmutableListMultimap.of();
  }

  ListMultimap<Long, ID> potentialLocksCycle = Multimaps.newListMultimap(
      new LinkedHashMap<Long, Collection<ID>>(),
      new Supplier<List<ID>>() {
        @Override
        public List<ID> get() {
          return Lists.newArrayList();
        }
      });
  // lock that is a part of a potential locks cycle, starts with current lock
  ReentrantCycleDetectingLock lockOwnerWaitingOn = this;
  // try to find a dependency path between lock's owner thread and a current thread
  while (lockOwnerWaitingOn != null && lockOwnerWaitingOn.lockOwnerThreadId != null) {
    Long threadOwnerThreadWaits = lockOwnerWaitingOn.lockOwnerThreadId;
    // in case locks cycle exists lock we're waiting for is part of it
    potentialLocksCycle.putAll(threadOwnerThreadWaits,
        getAllLockIdsAfter(threadOwnerThreadWaits, lockOwnerWaitingOn));

    if (threadOwnerThreadWaits == currentThreadId) {
      // owner thread depends on current thread, cycle detected
      return potentialLocksCycle;
    }
    // going for the next thread we wait on indirectly
    lockOwnerWaitingOn = lockThreadIsWaitingOn.get(threadOwnerThreadWaits);
  }
  // no dependency path from an owner thread to a current thread
  return ImmutableListMultimap.of();
}
 
Example #24
Source File: ExtensionPool.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private static ImmutableListMultimap<String, DescriptorProtos.SourceCodeInfo.Location>
    buildLocationMap(FileDescriptorProto file) {
  return Multimaps.<String, DescriptorProtos.SourceCodeInfo.Location>index(
      file.getSourceCodeInfo().getLocationList(),
      new Function<DescriptorProtos.SourceCodeInfo.Location, String>() {
        @Override
        public String apply(DescriptorProtos.SourceCodeInfo.Location location) {
          return DOT_JOINER.join(location.getPathList());
        }
      });
}
 
Example #25
Source File: ResourcesZip.java    From bazel with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ImmutableListMultimap<String, String> parseToolAttributes() throws IOException {
  return ToolAttributes.parseFrom(
          Files.readAllBytes(attributes), ExtensionRegistry.getEmptyRegistry())
      .getAttributesMap()
      .entrySet()
      .stream()
      .collect(
          ImmutableListMultimap.flatteningToImmutableListMultimap(
              Entry::getKey, e -> e.getValue().getValuesList().stream()));
}
 
Example #26
Source File: RdsInstanceTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsUp() {
  // Instance should be considered up unless status is unavailable
  assertTrue(
      new RdsInstance(
              "id",
              "az",
              "vpc",
              false,
              "available",
              ImmutableListMultimap.of(),
              ImmutableList.of())
          .isUp());
  assertTrue(
      new RdsInstance(
              "id",
              "az",
              "vpc",
              false,
              "backing-up",
              ImmutableListMultimap.of(),
              ImmutableList.of())
          .isUp());
  assertFalse(
      new RdsInstance(
              "id", "az", "vpc", false, "stopped", ImmutableListMultimap.of(), ImmutableList.of())
          .isUp());
}
 
Example #27
Source File: LinkageCheckTask.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private void recordDependencyPaths(
    ImmutableListMultimap.Builder<String, String> output,
    ArrayDeque<ResolvedComponentResult> stack,
    ImmutableSet<String> targetCoordinates) {
  ResolvedComponentResult item = stack.getLast();
  ModuleVersionIdentifier identifier = item.getModuleVersion();
  String coordinates =
      String.format(
          "%s:%s:%s", identifier.getGroup(), identifier.getName(), identifier.getVersion());
  if (targetCoordinates.contains(coordinates)) {
    String dependencyPath =
        stack.stream().map(this::formatComponentResult).collect(Collectors.joining(" / "));
    output.put(coordinates, dependencyPath);
  }

  for (DependencyResult dependencyResult : item.getDependencies()) {
    if (dependencyResult instanceof ResolvedDependencyResult) {
      ResolvedDependencyResult resolvedDependencyResult =
          (ResolvedDependencyResult) dependencyResult;
      ResolvedComponentResult child = resolvedDependencyResult.getSelected();
      stack.add(child);
      recordDependencyPaths(output, stack, targetCoordinates);
    } else if (dependencyResult instanceof UnresolvedDependencyResult) {
      UnresolvedDependencyResult unresolvedResult = (UnresolvedDependencyResult) dependencyResult;
      getLogger()
          .error(
              "Could not resolve dependency: "
                  + unresolvedResult.getAttempted().getDisplayName());
    } else {
      throw new IllegalStateException("Unexpected dependency result type: " + dependencyResult);
    }
  }

  stack.removeLast();
}
 
Example #28
Source File: InstallMultiApksCommand.java    From bundletool with Apache License 2.0 5 votes vote down vote up
public void execute() throws TimeoutException, IOException {
  validateInput();

  AdbServer adbServer = getAdbServer();
  adbServer.init(getAdbPath());

  try (TempDirectory tempDirectory = new TempDirectory()) {
    DeviceAnalyzer deviceAnalyzer = new DeviceAnalyzer(adbServer);
    DeviceSpec deviceSpec = deviceAnalyzer.getDeviceSpec(getDeviceId());
    Device device = deviceAnalyzer.getAndValidateDevice(getDeviceId());

    MultiPackagesInstaller installer =
        new MultiPackagesInstaller(device, getEnableRollback(), getNoCommitMode());

    Path aapt2Dir = tempDirectory.getPath().resolve("aapt2");
    Files.createDirectory(aapt2Dir);
    Supplier<Aapt2Command> aapt2CommandSupplier =
        Suppliers.memoize(() -> getOrExtractAapt2Command(aapt2Dir));

    ImmutableMap<String, InstalledPackageInfo> existingPackages =
        getPackagesInstalledOnDevice(device);

    ImmutableListMultimap<String, InstallableApk> apkToInstallByPackage =
        getActualApksPaths(tempDirectory).stream()
            .flatMap(
                apksArchivePath ->
                    stream(
                        apksWithPackageName(apksArchivePath, deviceSpec, aapt2CommandSupplier)))
            .filter(apk -> shouldInstall(apk, existingPackages))
            .flatMap(apks -> extractApkListFromApks(deviceSpec, apks, tempDirectory).stream())
            .collect(toImmutableListMultimap(InstallableApk::getPackageName, identity()));

    if (apkToInstallByPackage.isEmpty()) {
      logger.warning("No packages found to install! Exiting...");
      return;
    }
    installer.install(apkToInstallByPackage);
  }
}
 
Example #29
Source File: PropertySetTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_combinedWith() {
  PropertySet base = PropertySet.of(ImmutableListMultimap.of("a", "x", "a", "y", "c", "z"));
  PropertySet other = PropertySet.of(ImmutableListMultimap.of("a", "aa", "b", "bb", "d", "dd"));
  PropertySet expected = PropertySet.of(ImmutableListMultimap.of("a", "x", "a", "y", "c", "z", "b", "bb", "d", "dd"));
  assertThat(base.combinedWith(other)).isEqualTo(expected);
}
 
Example #30
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 5 votes vote down vote up
public ImmutableListMultimap construct(int entries) {
  ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder();
  for (int i = 0; i < entries; i++) {
    builder.put(newEntry(), newEntry());
  }
  return builder.build();
}