com.google.common.collect.ImmutableMultimap Java Examples

The following examples show how to use com.google.common.collect.ImmutableMultimap. 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: ReadDnsQueueActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_corruptTaskTldMismatch_published() {
  // TODO(mcilwain): what's the correct action to take in this case?
  dnsQueue.addDomainRefreshTask("domain.com");
  dnsQueue.addDomainRefreshTask("domain.example");
  QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
      .add(
          TaskOptions.Builder.withDefaults()
              .method(Method.PULL)
              .param(DNS_TARGET_TYPE_PARAM, TargetType.DOMAIN.toString())
              .param(DNS_TARGET_NAME_PARAM, "domain.wrongtld")
              .param(DNS_TARGET_CREATE_TIME_PARAM, "3000-01-01TZ")
              .param(PARAM_TLD, "net"));

  run();

  assertNoTasksEnqueued(DNS_PULL_QUEUE_NAME);
  assertTldsEnqueuedInPushQueue(
      ImmutableMultimap.of("com", "comWriter", "example", "exampleWriter", "net", "netWriter"));
}
 
Example #2
Source File: StatementAnalyzer.java    From presto with Apache License 2.0 6 votes vote down vote up
private Multimap<QualifiedName, Expression> extractNamedOutputExpressions(Select node)
{
    // Compute aliased output terms so we can resolve order by expressions against them first
    ImmutableMultimap.Builder<QualifiedName, Expression> assignments = ImmutableMultimap.builder();
    for (SelectItem item : node.getSelectItems()) {
        if (item instanceof SingleColumn) {
            SingleColumn column = (SingleColumn) item;
            Optional<Identifier> alias = column.getAlias();
            if (alias.isPresent()) {
                assignments.put(QualifiedName.of(alias.get().getValue()), column.getExpression()); // TODO: need to know if alias was quoted
            }
            else if (column.getExpression() instanceof Identifier) {
                assignments.put(QualifiedName.of(((Identifier) column.getExpression()).getValue()), column.getExpression());
            }
        }
    }

    return assignments.build();
}
 
Example #3
Source File: GuavaAppTest.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@Before
public void startServer() {
	stream = simpleReact.ofAsync(
			() -> server = new MicroserverApp(GuavaAppTest.class,
					() -> "guava-app")).then(server -> server.start());

	entity = ImmutableGuavaEntity.builder().value("value")
			.list(ImmutableList.of("hello", "world"))
			.mapOfSets(ImmutableMap.of("key1", ImmutableSet.of(1, 2, 3)))
			.multiMap(ImmutableMultimap.of("1", 2, "1", 2, "2", 4)).build();

	JacksonUtil.convertFromJson(JacksonUtil.serializeToJson(entity),
			ImmutableGuavaEntity.class);

	present = Jdk8Entity.builder().name(Optional.of("test")).build();

	JacksonUtil.convertFromJson(JacksonUtil.serializeToJson(present),
			Optional.class);
	absent = Jdk8Entity.builder().name(Optional.empty()).build();
}
 
Example #4
Source File: ParseWarningAnswererTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testAggregateRow() {
  Row row =
      getAggregateRow(
          new ParseWarningTriplet("dup", "[configuration]", null),
          ImmutableMultimap.of("f1", 3, "f1", 4, "f2", 23),
          createMetadata(new ParseWarningQuestion(true)).toColumnMap());

  Row expected =
      Row.of(
          COL_FILELINES,
          ImmutableList.of(
              new FileLines("f1", ImmutableSortedSet.of(3, 4)),
              new FileLines("f2", ImmutableSortedSet.of(23))),
          COL_TEXT,
          "dup",
          COL_PARSER_CONTEXT,
          "[configuration]",
          COL_COMMENT,
          "(not provided)");

  assertThat(row, equalTo(expected));
}
 
Example #5
Source File: ReadDnsQueueActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_corruptTaskWrongType_discarded() {
  dnsQueue.addDomainRefreshTask("domain.com");
  dnsQueue.addDomainRefreshTask("domain.example");
  QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
      .add(
          TaskOptions.Builder.withDefaults()
              .method(Method.PULL)
              .param(DNS_TARGET_TYPE_PARAM, "Wrong type")
              .param(DNS_TARGET_NAME_PARAM, "domain.net")
              .param(PARAM_TLD, "net"));

  run();

  // The corrupt task isn't in the pull queue, but also isn't in the push queue
  assertNoTasksEnqueued(DNS_PULL_QUEUE_NAME);
  assertTldsEnqueuedInPushQueue(
      ImmutableMultimap.of("com", "comWriter", "example", "exampleWriter"));
}
 
Example #6
Source File: DedupMigrationTask.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
    boolean oldEnabled = _dedupEnabled.get();
    boolean newEnabled = oldEnabled;

    for (String value : parameters.get("dedup")) {
        newEnabled = Boolean.parseBoolean(value);
        _dedupEnabled.set(newEnabled);
    }

    out.printf("dedup-enabled: %s%n", newEnabled);

    Collection<String> migrations = parameters.get("migrate");
    if (!migrations.isEmpty()) {
        if (newEnabled) {
            out.println("Ignoring migrations since Databus dedup is still enabled.");
        } else {
            if (oldEnabled) {
                out.println("Sleeping 15 seconds to allow in-flight requests to complete.");
                out.flush();
                Thread.sleep(Duration.seconds(15).toMilliseconds());
            }
            migrate(migrations, out);
        }
    }
}
 
Example #7
Source File: ParallelVisitorTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private RecordingParallelVisitor(
    ImmutableMultimap<String, String> successors,
    RecordingCallback recordingCallback,
    int visitBatchSize,
    int processResultsBatchSize) {
  super(
      recordingCallback,
      SampleException.class,
      visitBatchSize,
      processResultsBatchSize,
      MIN_PENDING_TASKS,
      BATCH_CALLBACK_SIZE,
      Executors.newFixedThreadPool(3),
      VisitTaskStatusCallback.NULL_INSTANCE);
  this.successorMap = successors;
}
 
Example #8
Source File: TestLocalDynamicFilterConsumer.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testNone()
        throws ExecutionException, InterruptedException
{
    LocalDynamicFilterConsumer filter = new LocalDynamicFilterConsumer(
            ImmutableMultimap.of(new DynamicFilterId("123"), new Symbol("a")),
            ImmutableMap.of(new DynamicFilterId("123"), 0),
            ImmutableMap.of(new DynamicFilterId("123"), INTEGER),
            1);
    assertEquals(filter.getBuildChannels(), ImmutableMap.of(new DynamicFilterId("123"), 0));
    Consumer<TupleDomain<DynamicFilterId>> consumer = filter.getTupleDomainConsumer();
    ListenableFuture<Map<Symbol, Domain>> result = filter.getNodeLocalDynamicFilterForSymbols();

    assertFalse(result.isDone());
    consumer.accept(TupleDomain.none());

    assertEquals(result.get(), ImmutableMap.of(
            new Symbol("a"), Domain.none(INTEGER)));
}
 
Example #9
Source File: UserCreationTaskTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test(expected = UserCreationException.class)
public void executeRethrowsTheExceptionsOfTheLocalUserCreator() throws Exception {
  doThrow(new UserCreationException("")).when(localUserCreator).create(ArgumentMatchers.any());
  ImmutableMultimap<String, String> immutableMultimap = ImmutableMultimap.<String, String>builder()
    .put(UserInfoKeys.USER_PID, PID)
    .put(UserInfoKeys.USER_NAME, USER_NAME)
    .put(UserInfoKeys.PASSWORD, PWD)
    .put(UserInfoKeys.GIVEN_NAME, GIVEN_NAME)
    .put(UserInfoKeys.SURNAME, SURNAME)
    .put(UserInfoKeys.EMAIL_ADDRESS, EMAIL)
    .put(UserInfoKeys.ORGANIZATION, ORGANIZATION)
    .put(UserInfoKeys.VRE_ID, VRE_ID)
    .put(UserInfoKeys.VRE_ROLE, VRE_ROLE)
    .build();

  instance.execute(immutableMultimap, mock(PrintWriter.class));
}
 
Example #10
Source File: BaseImmutableMultimapJsonDeserializer.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * Build the {@link ImmutableMultimap} using the given builder.
 *
 * @param reader {@link JsonReader} used to read the JSON input
 * @param ctx Context for the full deserialization process
 * @param params Parameters for this deserialization
 * @param builder {@link ImmutableMultimap.Builder} used to collect the entries
 */
protected void buildMultimap( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params,
                              ImmutableMultimap.Builder<K, V> builder ) {
    reader.beginObject();
    while ( JsonToken.END_OBJECT != reader.peek() ) {
        String name = reader.nextName();
        K key = keyDeserializer.deserialize( name, ctx );
        reader.beginArray();
        while ( JsonToken.END_ARRAY != reader.peek() ) {
            V value = valueDeserializer.deserialize( reader, ctx, params );
            builder.put( key, value );
        }
        reader.endArray();
    }
    reader.endObject();
}
 
Example #11
Source File: MessageIdMapperTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void deletesShouldUpdateMessageCount() throws Exception {
    saveMessages();

    SimpleMailboxMessage copiedMessage = SimpleMailboxMessage.copy(benwaWorkMailbox.getMailboxId(), message1);
    copiedMessage.setUid(mapperProvider.generateMessageUid());
    copiedMessage.setModSeq(mapperProvider.generateModSeq(benwaWorkMailbox));
    sut.copyInMailbox(copiedMessage, benwaWorkMailbox);

    sut.delete(
        ImmutableMultimap.<MessageId, MailboxId>builder()
            .put(message1.getMessageId(), benwaWorkMailbox.getMailboxId())
            .put(message2.getMessageId(), benwaInboxMailbox.getMailboxId())
            .build());

    assertThat(messageMapper.countMessagesInMailbox(benwaInboxMailbox))
        .isEqualTo(2);
}
 
Example #12
Source File: UserCreationTaskTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void executeDoesNotImportIfKeysAreMissing() throws Exception {
  // Missing USER_PID key
  ImmutableMultimap<String, String> immutableMultimap = ImmutableMultimap.<String, String>builder()
    .put(UserInfoKeys.USER_NAME, USER_NAME)
    .put(UserInfoKeys.PASSWORD, PWD)
    .put(UserInfoKeys.GIVEN_NAME, GIVEN_NAME)
    .put(UserInfoKeys.SURNAME, SURNAME)
    .put(UserInfoKeys.EMAIL_ADDRESS, EMAIL)
    .put(UserInfoKeys.ORGANIZATION, ORGANIZATION)
    .put(UserInfoKeys.VRE_ID, VRE_ID)
    .put(UserInfoKeys.VRE_ROLE, VRE_ROLE)
    .build();

  instance.execute(immutableMultimap, printWriter);

  verifyZeroInteractions(localUserCreator);
  verify(printWriter).write(argThat(containsString(UserInfoKeys.USER_PID)));
}
 
Example #13
Source File: ClasspathCache.java    From glowroot with Apache License 2.0 6 votes vote down vote up
synchronized void updateCache() {
    Multimap<String, Location> newClassNameLocations = HashMultimap.create();
    for (ClassLoader loader : getKnownClassLoaders()) {
        updateCache(loader, newClassNameLocations);
    }
    updateCacheWithClasspathClasses(newClassNameLocations);
    updateCacheWithBootstrapClasses(newClassNameLocations);
    if (!newClassNameLocations.isEmpty()) {
        // multimap that sorts keys and de-dups values while maintains value ordering
        SetMultimap<String, Location> newMap =
                MultimapBuilder.treeKeys().linkedHashSetValues().build();
        newMap.putAll(classNameLocations);
        newMap.putAll(newClassNameLocations);
        classNameLocations = ImmutableMultimap.copyOf(newMap);
    }
}
 
Example #14
Source File: ApkMatcher.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private Predicate<String> getModuleNameMatcher(Variant variant, Version bundleVersion) {
  if (requestedModuleNames.isPresent()) {
    ImmutableMultimap<String, String> moduleDependenciesMap = buildAdjacencyMap(variant);

    HashSet<String> dependencyModules = new HashSet<>(requestedModuleNames.get());
    for (String requestedModuleName : requestedModuleNames.get()) {
      addModuleDependencies(requestedModuleName, moduleDependenciesMap, dependencyModules);
    }

    if (matchInstant) {
      return dependencyModules::contains;
    } else {
      return Predicates.or(
          buildModulesDeliveredInstallTime(variant, bundleVersion)::contains,
          dependencyModules::contains);
    }
  } else {
    if (matchInstant) {
      // For instant matching, by default all instant modules are matched.
      return Predicates.alwaysTrue();
    } else {
      // For conventional matching, only install-time modules are matched.
      return buildModulesDeliveredInstallTime(variant, bundleVersion)::contains;
    }
  }
}
 
Example #15
Source File: SetNumInstancesCommandTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void test_noNonLiveVersions_succeeds() throws Exception {
  command.appengine =
      new AppEngineAdminApiHelper.Builder()
          .setAppId(projectId)
          .setManualScalingVersionsMap(
              ImmutableMultimap.of(
                  "default", "version1", "default", "version2", "default", "version3"))
          .setLiveVersionsMap(
              ImmutableMultimap.of(
                  "default", "version1", "default", "version2", "default", "version3"))
          .build()
          .getAppengine();

  runCommand("--non_live_versions=true", "--services=DEFAULT", "--num_instances=10");
  verify(appEngineServiceUtils, times(0)).setNumInstances("default", "version1", 10L);
  verify(appEngineServiceUtils, times(0)).setNumInstances("default", "version2", 10L);
  verify(appEngineServiceUtils, times(0)).setNumInstances("default", "version3", 10L);
}
 
Example #16
Source File: SetMultimapPropertyTest.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemove_doesNotThrowIfEntryNotPresent() {
  behaviorTester
      .with(new Processor(features))
      .with(dataType)
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putAllItems(%s.of(", ImmutableMultimap.class)
          .addLine("        %s, %s,", key.example(0), value.example(1))
          .addLine("        %s, %s))", key.example(3), value.example(2))
          .addLine("    .removeItems(%s, %s)", key.example(0), value.example(2))
          .addLine("    .build();")
          .addLine("assertThat(value.%s)", convention.get("items"))
          .addLine("    .contains(%s, %s)", key.example(0), value.example(1))
          .addLine("    .and(%s, %s)", key.example(3), value.example(2))
          .addLine("    .andNothingElse()")
          .addLine("    .inOrder();")
          .build())
      .runTest();
}
 
Example #17
Source File: AtomicQueryUnificationIT.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test //only a single unifier exists
public void testUnification_EXACT_BinaryRelationWithTypes_SomeVarsHaveTypes_UnifierMatchesTypes() {
    try (Transaction tx = unificationWithTypesSession.transaction(Transaction.Type.READ)) {
        ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction) tx).reasonerQueryFactory();

        ReasonerAtomicQuery parentQuery = reasonerQueryFactory.atomic(conjunction("{ $x1 isa twoRoleEntity;($x1, $x2) isa binary; };"));
        ReasonerAtomicQuery childQuery = reasonerQueryFactory.atomic(conjunction("{ $y1 isa twoRoleEntity;($y1, $y2) isa binary; };"));

        MultiUnifier unifier = childQuery.getMultiUnifier(parentQuery);
        MultiUnifier correctUnifier = new MultiUnifierImpl(ImmutableMultimap.of(
                new Variable("y1"), new Variable("x1"),
                new Variable("y2"), new Variable("x2")
        ));
        assertEquals(correctUnifier, unifier);
    }
}
 
Example #18
Source File: DefaultFanoutTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnauthorizedFanout() {
    addTable("unauthorized-table");

    OwnedSubscription subscription = new DefaultOwnedSubscription(
            "test", Conditions.intrinsic(Intrinsic.TABLE, Conditions.equal("unauthorized-table")),
            new Date(), Duration.ofDays(1), "owner0");

    EventData event = newEvent("id0", "unauthorized-table", "key0");

    when(_subscriptionsSupplier.get()).thenReturn(ImmutableList.of(subscription));
    DatabusAuthorizer.DatabusAuthorizerByOwner authorizerByOwner = mock(DatabusAuthorizer.DatabusAuthorizerByOwner.class);
    when(authorizerByOwner.canReceiveEventsFromTable("matching-table")).thenReturn(false);
    when(_databusAuthorizer.owner("owner0")).thenReturn(authorizerByOwner);

    _defaultFanout.copyEvents(ImmutableList.of(event));

    // Event is not authorized for owner, should only go to remote fanout
    assertEquals(_eventsSinked,
            ImmutableMultimap.of(_remoteChannel, event.getData()));

}
 
Example #19
Source File: FeatureSelection.java    From bazel with Apache License 2.0 5 votes vote down vote up
FeatureSelection(
    ImmutableSet<String> requestedFeatures,
    ImmutableMap<String, CrosstoolSelectable> selectablesByName,
    ImmutableList<CrosstoolSelectable> selectables,
    ImmutableMultimap<String, CrosstoolSelectable> provides,
    ImmutableMultimap<CrosstoolSelectable, CrosstoolSelectable> implies,
    ImmutableMultimap<CrosstoolSelectable, CrosstoolSelectable> impliedBy,
    ImmutableMultimap<CrosstoolSelectable, ImmutableSet<CrosstoolSelectable>> requires,
    ImmutableMultimap<CrosstoolSelectable, CrosstoolSelectable> requiredBy,
    ImmutableMap<String, ActionConfig> actionConfigsByActionName,
    PathFragment ccToolchainPath) {
  this.requestedFeatures = requestedFeatures;
  ImmutableSet.Builder<CrosstoolSelectable> builder = ImmutableSet.builder();
  for (String name : requestedFeatures) {
    if (selectablesByName.containsKey(name)) {
      builder.add(selectablesByName.get(name));
    }
  }
  this.requestedSelectables = builder.build();
  this.selectables = selectables;
  this.provides = provides;
  this.implies = implies;
  this.impliedBy = impliedBy;
  this.requires = requires;
  this.requiredBy = requiredBy;
  this.actionConfigsByActionName = actionConfigsByActionName;
  this.ccToolchainPath = ccToolchainPath;
}
 
Example #20
Source File: RequesterTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldExpandOnGetWithHeadersAndBody() {
    expectRequestTo("https://api.example.com/123");

    unit.get("/123")
            .headers(ImmutableMultimap.of())
            .body("deadbody")
            .call(pass())
            .join();
}
 
Example #21
Source File: ShadowedPlatformTypeConverterCoverageTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
ClassMemberHeaderClassVisitor(
    ImmutableMultimap.Builder<ClassName, MethodHeaderTypeTrackingLabel> shadowedMethodTypes,
    ImmutableMultimap.Builder<ClassName, FieldTypeTrackingLabel> shadowedFieldTypes,
    Path containingJar) {
  super(Opcodes.ASM7);
  this.shadowedMethodTypes = shadowedMethodTypes;
  this.shadowedFieldTypes = shadowedFieldTypes;
  this.containgJar = containingJar;
}
 
Example #22
Source File: CorefAnnotation.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
private CorefAnnotation(final Symbol docId, final Multimap<Integer, KBPString> idToCASes,
    final Map<KBPString, Integer> CASesToIDs, final Set<KBPString> unannotated) {
  this.docId = checkNotNull(docId);
  this.idToCASes = ImmutableMultimap.copyOf(idToCASes);
  this.CASesToIDs = ImmutableMap.copyOf(CASesToIDs);
  this.unannotated = ImmutableSet.copyOf(unannotated);
  checkConsistency();
}
 
Example #23
Source File: BlazeGoPackage.java    From intellij with Apache License 2.0 5 votes vote down vote up
static ImmutableMultimap<Label, File> getTargetToFileMap(
    Project project, BlazeProjectData projectData) {
  ImmutableMultimap<Label, File> map =
      SyncCache.getInstance(project)
          .get(GO_TARGET_TO_FILE_MAP_KEY, BlazeGoPackage::getUncachedTargetToFileMap);
  if (map == null) {
    logger.error("Unexpected null target to file map from SyncCache.");
    return getUncachedTargetToFileMap(project, projectData);
  }
  return map;
}
 
Example #24
Source File: RequesterTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldAppendQueryParams() {
    server.expect(requestTo("https://api.example.com?foo=bar&foo=baz&bar=null"))
            .andRespond(withSuccess());

    unit.head("https://api.example.com")
            .queryParam("foo", "bar")
            .queryParams(ImmutableMultimap.of(
                    "foo", "baz",
                    "bar", "null"
            ))
            .dispatch(series(),
                    on(SUCCESSFUL).call(pass()))
            .join();
}
 
Example #25
Source File: CloudFilesPublish.java    From jclouds-examples with Apache License 2.0 5 votes vote down vote up
/**
 * This method will create a container in Cloud Files where you can store and
 * retrieve any kind of digital asset.
 */
private void createContainer() {
   System.out.format("Create Container%n");

   Multimap<String, String> enableStaticWebHeaders =
         ImmutableMultimap.of(STATIC_WEB_INDEX, FILENAME + SUFFIX,
                              STATIC_WEB_ERROR, "error.html");

   CreateContainerOptions opts = new CreateContainerOptions().headers(enableStaticWebHeaders);
   cloudFiles.getContainerApi(REGION).create(CONTAINER_PUBLISH, opts);

   System.out.format("  %s%n", CONTAINER_PUBLISH);
}
 
Example #26
Source File: RequesterTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldExpandOnGetWithHeaders() {
    expectRequestTo("https://api.example.com/123");

    unit.get("/123")
            .headers(ImmutableMultimap.of())
            .dispatch(series(),
                    on(SUCCESSFUL).call(pass()))
            .join();
}
 
Example #27
Source File: GerritChange.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch the change from Gerrit
 *
 * @param additionalLabels additional labels to add to the GitRevision labels
 * @return The resolved and fetched SHA-1 of the change.
 */
GitRevision fetch(ImmutableMultimap<String, String> additionalLabels)
    throws RepoException, ValidationException {
  String metaRef = String.format("refs/changes/%02d/%d/meta", change % 100, change);
  repository.fetch(repoUrl, /*prune=*/true, /*force=*/true,
      ImmutableList.of(ref + ":refs/gerrit/" + ref, metaRef + ":refs/gerrit/" + metaRef), false);
  GitRevision gitRevision = repository.resolveReference("refs/gerrit/" + ref);
  GitRevision metaRevision = repository.resolveReference("refs/gerrit/" + metaRef);
  String changeId = getChangeIdFromMeta(repository, metaRevision , metaRef);
  String changeNumber = Integer.toString(change);
  String changeDescription = getDescriptionFromMeta(repository, metaRevision , metaRef);
  return new GitRevision(
      repository,
      gitRevision.getSha1(),
      gerritPatchSetAsReviewReference(patchSet),
      changeNumber,
      ImmutableListMultimap.<String, String>builder()
          .put(GERRIT_CHANGE_NUMBER_LABEL, changeNumber)
          .put(GERRIT_CHANGE_ID_LABEL, changeId)
          .put(GERRIT_CHANGE_DESCRIPTION_LABEL, changeDescription)
          .put(
              DEFAULT_INTEGRATE_LABEL,
              new GerritIntegrateLabel(
                  repository, generalOptions, repoUrl, change, patchSet, changeId)
                  .toString())
          .putAll(additionalLabels)
          .build(),
      repoUrl);
}
 
Example #28
Source File: EntityModelWriterTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testCreateRfdModelMREF() {
  List<Attribute> attributeList = singletonList(attribute);

  when(objectEntity.getEntityType()).thenReturn(entityType);
  when(objectEntity.get("attributeName")).thenReturn(refEntity);
  when(objectEntity.getEntities("attributeName")).thenReturn(singletonList(refEntity));

  when(refEntity.getIdValue()).thenReturn("refID");

  when(entityType.getAtomicAttributes()).thenReturn(attributeList);
  when(attribute.getName()).thenReturn("attributeName");

  when(attribute.getDataType()).thenReturn(AttributeType.MREF);

  LabeledResource tag = new LabeledResource("http://IRI.nl", "labelTag3");
  Multimap<Relation, LabeledResource> tags = ImmutableMultimap.of(Relation.isAssociatedWith, tag);
  when(tagService.getTagsForAttribute(entityType, attribute)).thenReturn(tags);

  Model result =
      writer.createRdfModel("http://molgenis01.gcc.rug.nl/fdp/catolog/test/this", objectEntity);

  assertEquals(1, result.size());
  Iterator results = result.iterator();
  assertEquals(
      "(http://molgenis01.gcc.rug.nl/fdp/catolog/test/this, http://IRI.nl, http://molgenis01.gcc.rug.nl/fdp/catolog/test/this/refID) [null]",
      results.next().toString());
}
 
Example #29
Source File: FakeListeningProcessExecutorTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void processFailureExitCodeNotZero() throws Exception {
  ProcessExecutorParams params = ProcessExecutorParams.ofCommand("false");
  FakeListeningProcessExecutor executor =
      new FakeListeningProcessExecutor(
          ImmutableMultimap.<ProcessExecutorParams, FakeListeningProcessState>builder()
              .putAll(params, FakeListeningProcessState.ofExit(1))
              .build());
  CapturingListener listener = new CapturingListener();
  ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(params, listener);
  int returnCode = executor.waitForProcess(process);
  assertThat(returnCode, not(equalTo(0)));
  assertThat(listener.capturedStdout.toString("UTF-8"), is(emptyString()));
  assertThat(listener.capturedStderr.toString("UTF-8"), is(emptyString()));
}
 
Example #30
Source File: SaxonMorphlineTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testXQueryShakespeareSpeakers() throws Exception {
  morphline = createMorphline("test-morphlines/xquery-shakespeare-speakers");    
  InputStream in = new FileInputStream(new File(RESOURCES_DIR + "/test-documents/othello.xml"));
  Record record = new Record();
  record.put(Fields.ATTACHMENT_BODY, in);
  processAndVerifySuccess(record, 
      ImmutableMultimap.of("name", "OTHELLO", "frequency", "274"),
      ImmutableMultimap.of("name", "IAGO", "frequency", "272"),
      ImmutableMultimap.of("name", "DESDEMONA", "frequency", "165")
      );    
  in.close();
}