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

The following examples show how to use com.google.common.collect.Iterables#get() . 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: UsageResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void assertUsage(Iterable<UsageStatistic> usages, String appId, String id, List<Status> states, Calendar pre, Calendar post, boolean allowGaps) throws Exception {
    String errMsg = "usages="+usages;
    Calendar now = new GregorianCalendar();
    Calendar lowerBound = pre;
    Calendar strictStart = null;
    
    assertEquals(Iterables.size(usages), states.size(), errMsg);
    for (int i = 0; i < Iterables.size(usages); i++) {
        UsageStatistic usage = Iterables.get(usages, i);
        Calendar usageStart = Time.parseCalendar(usage.getStart());
        Calendar usageEnd = Time.parseCalendar(usage.getEnd());
        assertEquals(usage.getId(), id, errMsg);
        assertEquals(usage.getApplicationId(), appId, errMsg);
        assertEquals(usage.getStatus(), states.get(i), errMsg);
        assertCalendarOrders(usages, lowerBound, usageStart, post);
        assertCalendarOrders(usages, usageEnd, now);
        if (strictStart != null) {
            assertEquals(usageStart, strictStart, errMsg);
        }
        if (!allowGaps) {
            strictStart = usageEnd;
        }
        lowerBound = usageEnd;
    }
}
 
Example 2
Source File: EmptySoftwareProcessYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithAppAndEntityLocations() throws Exception {
    Entity app = createAndStartApplication(
            "services:",
            "- type: "+EmptySoftwareProcess.class.getName(),
            "  location:",
            "    localhost:(name=localhost on entity):",
            "      sshToolClass: "+RecordingSshTool.class.getName(),
            "location: byon:(hosts=\"127.0.0.1\", name=loopback on app)");
    waitForApplicationTasks(app);
    Dumper.dumpInfo(app);
    
    Location appLocation = Iterables.getOnlyElement(app.getLocations());
    Assert.assertEquals(appLocation.getDisplayName(), "loopback on app");
    
    Entity entity = Iterables.getOnlyElement(app.getChildren());
    Assert.assertEquals(entity.getLocations().size(), 2);
    Location provisioningLoc = Iterables.get(entity.getLocations(), 0);
    Location machineLoc = Iterables.get(entity.getLocations(), 1);
    
    Assert.assertEquals(provisioningLoc.getDisplayName(), "localhost on entity");
    Assert.assertTrue(machineLoc instanceof SshMachineLocation, "wrong location: "+machineLoc);
    // TODO this, below, probably should be 'localhost on entity', see #1377
    Assert.assertEquals(machineLoc.getParent().getDisplayName(), "localhost on entity");
}
 
Example 3
Source File: CandidateBuilderTest.java    From metanome-algorithms with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
	CandidateBuilder builder = new CandidateBuilder(0.0, new SimpleMinimizer());
	when(latticeMD.getRhs()).thenReturn(new MDSiteImpl(4).set(0, 0.6).set(1, 0.7));
	when(latticeMD.getLhs()).thenReturn(Mockito.mock(MDSite.class));
	when(latticeMD.getMaxGenThresholds(new int[]{0, 1})).thenReturn(new double[]{0.0, 0.5});
	Collection<Candidate> candidates = builder
		.toCandidates(Collections.singletonList(latticeMD));
	assertThat(candidates).hasSize(1);
	Candidate candidate = Iterables.get(candidates, 0);
	assertThat(candidate.getRhs()).hasSize(2);
	assertThat(candidate.getRhs())
		.contains(Rhs.builder().rhsAttr(0).threshold(0.6).lowerBound(0.0).build());
	assertThat(candidate.getRhs())
		.contains(Rhs.builder().rhsAttr(1).threshold(0.7).lowerBound(0.5).build());
	assertThat(candidate.getLatticeMd()).isEqualTo(latticeMD);
}
 
Example 4
Source File: NetflowV9CodecAggregatorTest.java    From graylog-plugin-netflow with Apache License 2.0 6 votes vote down vote up
@Test
public void decodeMessagesSuccessfullyDecodesNetFlowV5() throws Exception {
    final Collection<Message> messages = decodeResult(aggregateRawPacket("netflow-data/netflow-v5-1.dat"));
    assertThat(messages)
            .isNotNull()
            .hasSize(2);
    final Message message = Iterables.get(messages, 0);
    assertThat(message).isNotNull();

    assertThat(message.getMessage()).isEqualTo("NetFlowV5 [10.0.2.2]:54435 <> [10.0.2.15]:22 proto:6 pkts:5 bytes:230");
    assertThat(message.getTimestamp()).isEqualTo(DateTime.parse("2015-05-02T18:38:08.280Z"));
    assertThat(message.getSource()).isEqualTo(source.getAddress().getHostAddress());
    assertThat(message.getFields())
            .containsEntry("nf_src_address", "10.0.2.2")
            .containsEntry("nf_dst_address", "10.0.2.15")
            .containsEntry("nf_proto_name", "TCP")
            .containsEntry("nf_src_as", 0)
            .containsEntry("nf_dst_as", 0)
            .containsEntry("nf_snmp_input", 0)
            .containsEntry("nf_snmp_output", 0);
}
 
Example 5
Source File: MongoDBShardedDeploymentIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration")
private void testReadAndWriteDifferentRouters() {
    MongoDBShardedDeployment deployment = makeAndStartDeployment();
    EntityAsserts.assertAttributeEqualsEventually(deployment, Startable.SERVICE_UP, true);
    MongoDBRouter router1 = (MongoDBRouter) Iterables.get(deployment.getRouterCluster().getMembers(), 0);
    MongoDBRouter router2 = (MongoDBRouter) Iterables.get(deployment.getRouterCluster().getMembers(), 1);
    EntityAsserts.assertAttributeEqualsEventually(router1, Startable.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(router2, Startable.SERVICE_UP, true);
    
    String documentId = MongoDBTestHelper.insert(router1, "meaning-of-life", 42);
    DBObject docOut = MongoDBTestHelper.getById(router2, documentId);
    Assert.assertEquals(docOut.get("meaning-of-life"), 42);
    
    for (Entity entity : Iterables.filter(app.getManagementContext().getEntityManager().getEntitiesInApplication(app), AbstractMongoDBServer.class)) {
        EntityAsserts.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, true);
    }
}
 
Example 6
Source File: IterablesExample.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Get element at specified position
 */
@Test
public void get_iterable_element_by_index () {
	
	String baconIpsum = "Bacon ipsum dolor sit "
			+ "amet tri-tip rump shoulder "
			+ "kielbasa strip steak";
	
	Iterable<String> chars = Splitter.on(CharMatcher.WHITESPACE)
			.split(baconIpsum);
	
	String elementAtPos5 = Iterables.get(chars, 5);
	
	assertEquals("tri-tip", elementAtPos5);
}
 
Example 7
Source File: LanguageServiceTest.java    From spoofax with Apache License 2.0 5 votes vote down vote up
/**
 * Add an implementation with a lower version number, assert that the other implementation stays active.
 */
@Test public void activeLowerVersion() throws Exception {
    final String id = "org.metaborg.lang.entity";
    final LanguageVersion version1 = version(0, 1, 0);
    final LanguageVersion version2 = version(0, 0, 1);
    final LanguageIdentifier identifier1 = new LanguageIdentifier(groupId, id, version1);
    final LanguageIdentifier identifier2 = new LanguageIdentifier(groupId, id, version2);
    final FileObject location1 = createDir("ram:///Entity1/");
    final FileObject location2 = createDir("ram:///Entity2/");
    final String name = "Entity";

    final ILanguageComponent component1 = language(identifier1, location1, name);
    final ILanguageImpl impl1 = Iterables.get(component1.contributesTo(), 0);
    final ILanguage lang = impl1.belongsTo();

    assertSame(component1, languageService.getComponent(location1.getName()));
    assertSame(impl1, languageService.getImpl(identifier1));
    assertSame(impl1, lang.activeImpl());
    assertSame(lang, languageService.getLanguage(name));

    final ILanguageComponent component2 = language(identifier2, location2, name);
    final ILanguageImpl impl2 = Iterables.get(component2.contributesTo(), 0);

    // Language 1 with higher version number stays active.
    assertSame(component1, languageService.getComponent(location1.getName()));
    assertSame(component2, languageService.getComponent(location2.getName()));
    assertSame(impl1, languageService.getImpl(identifier1));
    assertSame(impl2, languageService.getImpl(identifier2));
    assertSame(impl1, lang.activeImpl());
    assertSame(lang, languageService.getLanguage(name));
    assertSize(1, impl1.components());
    assertSize(1, impl2.components());
    assertSize(2, lang.impls());
    assertSize(2, languageService.getAllComponents());
    assertSize(2, languageService.getAllImpls());
    assertSize(1, languageService.getAllLanguages());
}
 
Example 8
Source File: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPluggableRemovalStrategyCanBeSetAfterConstruction() throws Exception {
    final List<Entity> removedEntities = Lists.newArrayList();

    Function<Collection<Entity>, Entity> removalStrategy = new Function<Collection<Entity>, Entity>() {
        @Override public Entity apply(Collection<Entity> contenders) {
            Entity choice = Iterables.get(contenders, random.nextInt(contenders.size()));
            removedEntities.add(choice);
            return choice;
        }
    };
    
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("memberSpec", EntitySpec.create(TestEntity.class))
            .configure("initialSize", 10));

    cluster.start(ImmutableList.of(loc));
    Set<?> origMembers = ImmutableSet.copyOf(cluster.getMembers());

    cluster.setRemovalStrategy(removalStrategy);

    for (int i = 10; i >= 0; i--) {
        cluster.resize(i);
        assertEquals(cluster.getAttribute(Changeable.GROUP_SIZE), (Integer)i);
        assertEquals(removedEntities.size(), 10-i);
        assertEquals(ImmutableSet.copyOf(Iterables.concat(cluster.getMembers(), removedEntities)), origMembers);
    }
}
 
Example 9
Source File: LabelAllocator.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Selects an identifier from a given set of values using
 * the random selection algorithm.
 *
 * @param values the values to select from
 * @return the selected identifier if values are present, null otherwise
 */
@Override
public Identifier<?> select(Set<Identifier<?>> values) {
    if (!values.isEmpty()) {
        int size = values.size();
        int index = RandomUtils.nextInt(size);
        return Iterables.get(values, index);
    }
    return null;
}
 
Example 10
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoSupportsCustomizedBanner() throws Exception {
    String origBanner = Main.banner;
    String origBannerFirstLine = Iterables.get(Splitter.on("\n").split(Main.DEFAULT_BANNER), 0);
    try {
        String customBanner = "My Custom Banner";
        Main.banner = customBanner;
        List<String> stdoutLines = runCommand(ImmutableList.of("info"), "");
        
        assertTrue(stdoutLines.contains(customBanner), "out="+stdoutLines);
        assertFalse(stdoutLines.contains(origBannerFirstLine), "out="+stdoutLines);
    } finally {
        Main.banner = origBanner;
    }
}
 
Example 11
Source File: AggregatorYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSum() throws Exception {
    Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.children:",
            "    - type: " + TestEntity.class.getName(),
            "    - type: " + TestEntity.class.getName(),
            "  brooklyn.enrichers:",
            "    - type: " + Aggregator.class.getName(),
            "      brooklyn.config:",
            "        "+Aggregator.SOURCE_SENSOR.getName()+": myVal",
            "        "+Aggregator.TARGET_SENSOR.getName()+": myResult",
            "        "+Aggregator.TRANSFORMATION_UNTYPED.getName()+": sum");
    Entity child1 = Iterables.get(app.getChildren(), 0);
    Entity child2 = Iterables.get(app.getChildren(), 1);
    
    child1.sensors().set(myVal, 1d);
    EntityAsserts.assertAttributeEqualsEventually(app, myResult, 1d);
    
    child2.sensors().set(myVal, 2d);
    EntityAsserts.assertAttributeEqualsEventually(app, myResult, 3d);
    
    child1.sensors().set(myVal, 3d);
    EntityAsserts.assertAttributeEqualsEventually(app, myResult, 5d);
    
    child2.sensors().set(myVal, null);
    EntityAsserts.assertAttributeEqualsEventually(app, myResult, 3d);
}
 
Example 12
Source File: CountByGeoHash.java    From amazon-kinesis-analytics-taxi-consumer with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Tuple tuple, TimeWindow timeWindow, Iterable<TripGeoHash> iterable, Collector<PickupCount> collector) throws Exception {
  long count = Iterables.size(iterable);
  String position = Iterables.get(iterable, 0).geoHash;

  collector.collect(new PickupCount(position, count, timeWindow.getEnd()));
}
 
Example 13
Source File: JcloudsUtil.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Map<Integer, Integer> dockerPortMappingsFor(JcloudsLocation docker, String containerId) {
    ComputeServiceContext context = null;
    try {
        Properties properties = new Properties();
        properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, Boolean.toString(true));
        properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, Boolean.toString(true));
        context = ContextBuilder.newBuilder("docker")
                .endpoint(docker.getEndpoint())
                .credentials(docker.getIdentity(), docker.getCredential())
                .overrides(properties)
                .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()))
                .build(ComputeServiceContext.class);
        DockerApi api = context.unwrapApi(DockerApi.class);
        Container container = api.getContainerApi().inspectContainer(containerId);
        Map<Integer, Integer> portMappings = Maps.newLinkedHashMap();
        Map<String, List<Map<String, String>>> ports = container.networkSettings().ports();
        if (ports == null) ports = ImmutableMap.<String, List<Map<String,String>>>of();

        LOG.debug("Docker will forward these ports {}", ports);
        for (Map.Entry<String, List<Map<String, String>>> entrySet : ports.entrySet()) {
            String containerPort = Iterables.get(Splitter.on("/").split(entrySet.getKey()), 0);
            String hostPort = Iterables.getOnlyElement(Iterables.transform(entrySet.getValue(),
                    new Function<Map<String, String>, String>() {
                        @Override
                        public String apply(Map<String, String> hostIpAndPort) {
                            return hostIpAndPort.get("HostPort");
                        }
                    }));
            portMappings.put(Integer.parseInt(containerPort), Integer.parseInt(hostPort));
        }
        return portMappings;
    } finally {
        if (context != null) {
            context.close();
        }
    }
}
 
Example 14
Source File: FixedListMachineProvisioningLocationRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRebindPreservesConfig() throws Exception {
    newApp = rebind();
    FixedListMachineProvisioningLocation<SshMachineLocation> newLoc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(newApp.getLocations(), 0);
    
    assertEquals(newLoc.getId(), origLoc.getId());
    assertEquals(newLoc.getDisplayName(), origLoc.getDisplayName());
    assertEquals(newLoc.getHostGeoInfo(), origLoc.getHostGeoInfo());
    assertEquals(newLoc.getConfig(LocationConfigKeys.USER), origLoc.getConfig(LocationConfigKeys.USER));
    assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_PASSPHRASE));
    assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_FILE));
    assertEquals(newLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_DATA), origLoc.getConfig(LocationConfigKeys.PRIVATE_KEY_DATA));
}
 
Example 15
Source File: PostgreSQLProviderTest.java    From binnavi with Apache License 2.0 4 votes vote down vote up
@Test
public void testInstructionFunctionSetGlobalReplacement1()
    throws CouldntSaveDataException,
    CouldntLoadDataException,
    LoadCancelledException,
    CPartialLoadException,
    MaybeNullException {
  final INaviModule module = getProvider().loadModules().get(0);
  module.load();
  final INaviFunction function =
      module.getContent().getFunctionContainer().getFunction("sub_1004565");
  final INaviView view = module.getContent().getViewContainer().getView(function);
  view.load();
  final IInstruction instruction =
      Iterables.get(view.getContent().getBasicBlocks().get(0).getInstructions(), 4);

  final INaviOperandTreeNode node = (INaviOperandTreeNode) instruction
      .getOperands()
      .get(1)
      .getRootNode()
      .getChildren()
      .get(0)
      .getChildren()
      .get(0)
      .getChildren()
      .get(0);

  getProvider().setGlobalReplacement(node, "replacement");

  view.close();

  final INaviModule module2 = getProvider().loadModules().get(0);
  module2.load();
  final INaviFunction function2 =
      module2.getContent().getFunctionContainer().getFunction("sub_1004565");
  final INaviView view2 = module2.getContent().getViewContainer().getView(function2);
  view2.load();
  final IInstruction instruction2 =
      Iterables.get(view2.getContent().getBasicBlocks().get(0).getInstructions(), 4);

  instruction2
      .getOperands()
      .get(1)
      .getRootNode()
      .getChildren()
      .get(0)
      .getChildren()
      .get(0)
      .getChildren()
      .get(0);
}
 
Example 16
Source File: LanguageServiceTest.java    From spoofax with Apache License 2.0 4 votes vote down vote up
/**
 * Add multiple different language implementations, assert correctness of the language service.
 */
@Test public void languageServiceCorrectness() throws Exception {
    final String id1 = "org.metaborg.lang.entity1";
    final String id2 = "org.metaborg.lang.entity2";
    final String id3 = "org.metaborg.lang.entity3";
    final LanguageVersion version = version(0, 0, 1);
    final LanguageIdentifier identifier1 = new LanguageIdentifier(groupId, id1, version);
    final LanguageIdentifier identifier2 = new LanguageIdentifier(groupId, id2, version);
    final LanguageIdentifier identifier3 = new LanguageIdentifier(groupId, id3, version);
    final FileObject location1 = createDir("ram:///Entity1");
    final FileObject location2 = createDir("ram:///Entity2");
    final FileObject location3 = createDir("ram:///Entity3");
    final String name1 = "Entity1";
    final String name2 = "Entity2";
    final String name3 = "Entity3";

    final ILanguageComponent component1 = language(identifier1, location1, name1);
    final ILanguageImpl impl1 = Iterables.get(component1.contributesTo(), 0);
    final ILanguage lang1 = impl1.belongsTo();
    final ILanguageComponent component2 = language(identifier2, location2, name2);
    final ILanguageImpl impl2 = Iterables.get(component2.contributesTo(), 0);
    final ILanguage lang2 = impl2.belongsTo();
    final ILanguageComponent component3 = language(identifier3, location3, name3);
    final ILanguageImpl impl3 = Iterables.get(component3.contributesTo(), 0);
    final ILanguage lang3 = impl3.belongsTo();

    assertEquals(component1, languageService.getComponent(location1.getName()));
    assertSame(component1, languageService.getComponent(location1.getName()));
    assertEquals(component2, languageService.getComponent(location2.getName()));
    assertSame(component2, languageService.getComponent(location2.getName()));
    assertEquals(component3, languageService.getComponent(location3.getName()));
    assertSame(component3, languageService.getComponent(location3.getName()));
    assertEquals(impl1, languageService.getImpl(identifier1));
    assertSame(impl1, languageService.getImpl(identifier1));
    assertEquals(impl2, languageService.getImpl(identifier2));
    assertSame(impl2, languageService.getImpl(identifier2));
    assertEquals(impl3, languageService.getImpl(identifier3));
    assertSame(impl3, languageService.getImpl(identifier3));
    assertEquals(impl1, lang1.activeImpl());
    assertSame(impl1, lang1.activeImpl());
    assertEquals(impl2, lang2.activeImpl());
    assertSame(impl2, lang2.activeImpl());
    assertEquals(impl3, lang3.activeImpl());
    assertSame(impl3, lang3.activeImpl());
    assertEquals(lang1, languageService.getLanguage(name1));
    assertSame(lang1, languageService.getLanguage(name1));
    assertEquals(lang2, languageService.getLanguage(name2));
    assertSame(lang2, languageService.getLanguage(name2));
    assertEquals(lang3, languageService.getLanguage(name3));
    assertSame(lang3, languageService.getLanguage(name3));
    assertSize(1, impl1.components());
    assertSize(1, impl2.components());
    assertSize(1, impl3.components());
    assertSize(1, lang1.impls());
    assertSize(1, lang2.impls());
    assertSize(1, lang3.impls());
    assertSize(3, languageService.getAllComponents());
    assertSize(3, languageService.getAllImpls());
    assertSize(3, languageService.getAllLanguages());
}
 
Example 17
Source File: InvalidListPruningDebugTest.java    From phoenix-tephra with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdleRegions() throws Exception {
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  try (PrintWriter out = new PrintWriter(outputStream)) {
    // Get the list of regions that have the lowest prune upper bounds for the latest record time
    Long latestRecordTime = compactedRegions.asMap().lastKey();
    SortedSet<InvalidListPruningDebugTool.RegionPruneInfoPretty> latestExpected =
      ImmutableSortedSet.copyOf(pruneUpperBoundAndStringComparator(), compactedRegions.get(latestRecordTime));
    pruningDebug.execute(new String[]{"idle-regions", "-1"}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with explicit time
    outputStream.reset();
    pruningDebug.execute(new String[]{"idle-regions", "-1", String.valueOf(latestRecordTime)}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with relative time
    outputStream.reset();
    pruningDebug.execute(new String[]{"idle-regions", "-1", "now-2s"}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with reduced number of regions
    outputStream.reset();
    int limit = 2;
    pruningDebug.execute(new String[]{"idle-regions", String.valueOf(limit), String.valueOf(latestRecordTime)}, out);
    out.flush();
    Assert.assertEquals(GSON.toJson(subset(latestExpected, 0, limit)), readOutputStream(outputStream));

    // For a different time, this time only live regions that are compacted are returned
    outputStream.reset();
    Long secondLastRecordTime = Iterables.get(compactedRegions.keySet(), 1);
    Set<String> compactedRegionsTime =
      Sets.newTreeSet(Iterables.transform(compactedRegions.get(secondLastRecordTime), PRUNE_INFO_TO_STRING));
    Set<String> compactedRegionsLatest =
      Sets.newTreeSet(Iterables.transform(compactedRegions.get(latestRecordTime), PRUNE_INFO_TO_STRING));
    Set<String> liveExpected = new TreeSet<>(Sets.intersection(compactedRegionsTime, compactedRegionsLatest));
    pruningDebug.execute(new String[]{"idle-regions", "-1", String.valueOf(latestRecordTime - 1)}, out);
    out.flush();
    List<RegionPruneInfo> actual = GSON.fromJson(readOutputStream(outputStream), PRUNE_INFO_LIST_TYPE);
    Assert.assertEquals(liveExpected, Sets.newTreeSet(Iterables.transform(actual, PRUNE_INFO_TO_STRING)));
  }
}
 
Example 18
Source File: Entropy.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
default <T> T randomElement(Iterable<T> iterable) {
    return Iterables.get(iterable, randomInt(Range.closedOpen(0, Iterables.size(iterable))));
}
 
Example 19
Source File: InvalidListPruningDebugTest.java    From phoenix-tephra with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdleRegions() throws Exception {
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  try (PrintWriter out = new PrintWriter(outputStream)) {
    // Get the list of regions that have the lowest prune upper bounds for the latest record time
    Long latestRecordTime = compactedRegions.asMap().lastKey();
    SortedSet<InvalidListPruningDebugTool.RegionPruneInfoPretty> latestExpected =
      ImmutableSortedSet.copyOf(pruneUpperBoundAndStringComparator(), compactedRegions.get(latestRecordTime));
    pruningDebug.execute(new String[]{"idle-regions", "-1"}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with explicit time
    outputStream.reset();
    pruningDebug.execute(new String[]{"idle-regions", "-1", String.valueOf(latestRecordTime)}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with relative time
    outputStream.reset();
    pruningDebug.execute(new String[]{"idle-regions", "-1", "now-2s"}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with reduced number of regions
    outputStream.reset();
    int limit = 2;
    pruningDebug.execute(new String[]{"idle-regions", String.valueOf(limit), String.valueOf(latestRecordTime)}, out);
    out.flush();
    Assert.assertEquals(GSON.toJson(subset(latestExpected, 0, limit)), readOutputStream(outputStream));

    // For a different time, this time only live regions that are compacted are returned
    outputStream.reset();
    Long secondLastRecordTime = Iterables.get(compactedRegions.keySet(), 1);
    Set<String> compactedRegionsTime =
      Sets.newTreeSet(Iterables.transform(compactedRegions.get(secondLastRecordTime), PRUNE_INFO_TO_STRING));
    Set<String> compactedRegionsLatest =
      Sets.newTreeSet(Iterables.transform(compactedRegions.get(latestRecordTime), PRUNE_INFO_TO_STRING));
    Set<String> liveExpected = new TreeSet<>(Sets.intersection(compactedRegionsTime, compactedRegionsLatest));
    pruningDebug.execute(new String[]{"idle-regions", "-1", String.valueOf(latestRecordTime - 1)}, out);
    out.flush();
    List<RegionPruneInfo> actual = GSON.fromJson(readOutputStream(outputStream), PRUNE_INFO_LIST_TYPE);
    Assert.assertEquals(liveExpected, Sets.newTreeSet(Iterables.transform(actual, PRUNE_INFO_TO_STRING)));
  }
}
 
Example 20
Source File: SpoofaxLanguageTest.java    From spoofax with Apache License 2.0 3 votes vote down vote up
/**
 * The 'res://' filesystem redirects to resources inside the tests' JAR file or class file location, which are copied
 * to the class file location from src/test/resources by Maven. The binary files of the Entity language are located
 * in the resources to test language discovery.
 */
@Test public void discoverLanguage() throws Exception {
    final FileObject location = resourceService.resolve("res://languages");

    final Iterable<ILanguageComponent> languages = languageDiscoveryService.discover(languageDiscoveryService.request(location));

    assertEquals(1, Iterables.size(languages));

    final ILanguageComponent component = Iterables.get(languages, 0);
    final ILanguageImpl impl = Iterables.get(component.contributesTo(), 0);
    final ILanguage language = impl.belongsTo();

    assertEquals("Entity", language.name());
    assertEquals(resourceService.resolve("res://languages/Entity"), component.location());

    final IdentificationFacet identificationFacet = impl.facet(IdentificationFacet.class);

    assertTrue(identificationFacet.identify(resourceService.resolve("ram:///Entity/test.ent")));

    final SyntaxFacet syntaxFacet = impl.facet(SyntaxFacet.class);

    assertEquals(resourceService.resolve("res://languages/Entity/target/metaborg/sdf.tbl"), syntaxFacet.parseTable);

    assertIterableEquals(syntaxFacet.startSymbols, "Start");

    final DynamicClassLoadingFacet dynamicClassLoadingFacet = impl.facet(DynamicClassLoadingFacet.class);
    final StrategoRuntimeFacet strategoRuntimeFacet = impl.facet(StrategoRuntimeFacet.class);

    assertIterableEquals(strategoRuntimeFacet.ctreeFiles, resourceService.resolve("res://languages/Entity/target/metaborg/stratego.ctree"));
    assertIterableEquals(dynamicClassLoadingFacet.jarFiles, resourceService.resolve("res://languages/Entity/target/metaborg/stratego.jar"));

    final AnalysisFacet analysisFacet = impl.facet(AnalysisFacet.class);

    assertEquals("editor-analyze", analysisFacet.strategyName);
}