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

The following examples show how to use com.google.common.collect.Iterables#find() . 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: xian   File: CreateBuilderImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to find the znode that matches the given path and protected id
 *
 * @param children    a list of candidates znodes
 * @param path        the path
 * @param protectedId the protected id
 * @return the absolute path of the znode or <code>null</code> if it is not found
 */
static String findNode(final List<String> children, final String path, final String protectedId)
{
    final String protectedPrefix = getProtectedPrefix(protectedId);
    String foundNode = Iterables.find
        (
            children,
            new Predicate<String>()
            {
                @Override
                public boolean apply(String node)
                {
                    return node.startsWith(protectedPrefix);
                }
            },
            null
        );
    if ( foundNode != null )
    {
        foundNode = ZKPaths.makePath(path, foundNode);
    }
    return foundNode;
}
 
Example 2
/**
 * Returns the file {@link IFile} based on its {@link URI}.
 *
 * @param uri
 *          the URI of the resource for which an IFile is to be returned
 * @param mapper
 *          class returning e.g. set of storages {@link IStorage} matching given URI; injected by concrete BuilderParticipant
 * @return the file associated with given URI
 */
public static IFile findFileStorage(final URI uri, final IStorage2UriMapper mapper) {
  Iterable<Pair<IStorage, IProject>> storages = mapper.getStorages(uri);
  try {
    Pair<IStorage, IProject> fileStorage = Iterables.find(storages, new Predicate<Pair<IStorage, IProject>>() {
      @Override
      public boolean apply(final Pair<IStorage, IProject> input) {
        IStorage storage = input.getFirst();
        if (storage instanceof IFile) {
          return true;
        }
        return false;
      }
    });

    return (IFile) fileStorage.getFirst();
  } catch (NoSuchElementException e) {
    LOGGER.debug("Cannot find file storage for " + uri); //$NON-NLS-1$
    return null;
  }
}
 
Example 3
@Test(dependsOnMethods = "testDeployApplication")
public void testGetApplicationOnFire() {
    Application app = Iterables.find(manager.getApplications(), EntityPredicates.displayNameEqualTo(simpleSpec.getName()));
    Lifecycle origState = app.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    
    ApplicationSummary summary = client().path("/applications/"+app.getId())
            .get(ApplicationSummary.class);
    assertEquals(summary.getStatus(), Status.RUNNING);

    app.sensors().set(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    try {
        ApplicationSummary summary2 = client().path("/applications/"+app.getId())
                .get(ApplicationSummary.class);
        log.info("Application: " + summary2);
        assertEquals(summary2.getStatus(), Status.ERROR);
        
    } finally {
        app.sensors().set(Attributes.SERVICE_STATE_ACTUAL, origState);
    }
}
 
Example 4
@Test
public void testExecutionManagerPerformance() throws Exception {
    // Was fixed at 1000 tasks, but was running out of virtual memory due to excessive thread creation
    // on machines which were not able to execute the threads quickly.
    final int NUM_TASKS = Math.min(500 * Runtime.getRuntime().availableProcessors(), 1000);
    final int NUM_TIMES = 10;
    final int MAX_ACCEPTABLE_TIME = 7500; // saw 5601ms on buildhive
    
    long tWarmup = execTasksAndWaitForDone(NUM_TASKS, ImmutableList.of("A"));
    
    List<Long> times = Lists.newArrayList();
    for (int i = 1; i <= NUM_TIMES; i++) {
        times.add(execTasksAndWaitForDone(NUM_TASKS, ImmutableList.of("A")));
    }
    
    Long toobig = Iterables.find(
            times, 
            new Predicate<Long>() {
                @Override
                public boolean apply(Long input) {
                    return input > MAX_ACCEPTABLE_TIME;
                }},
            null);
    assertNull(toobig, "warmup="+tWarmup+"; times="+times);
}
 
Example 5
@Test
public void find_elements_in_lists_with_guava () {

	List <Integer> numbers = Lists.newArrayList(
			new Integer(1), 
			new Integer(2), 
			new Integer(3));
	
	Integer value = Iterables.find(numbers, new Predicate<Integer> () {
		public boolean apply(Integer number) {
			return number == 3 ;
		}
	});

	assertEquals(new Integer(3), value);
}
 
Example 6
@Test
public void testWithDslConfigReferenceParentDefault() throws Exception {
    Entity app = runTest(catalogYamlWithDslReferenceParentDefault, appVersionedId);
    
    TestEntity newEntity = (TestEntity) Iterables.find(app.getChildren(), EntityPredicates.displayNameEqualTo("targetEntity"));
    ServiceFailureDetector newEnricher = assertHasEnricher(newEntity, ServiceFailureDetector.class);
    assertEnricherConfigMatchesDsl(newEnricher);
}
 
Example 7
@Test
public void testExtendsRuntimeParentMultipleLevels() throws Exception {
    addCatalogItems(
            "brooklyn.catalog:",
            "  itemType: entity",
            "  items:",
            "  - id: TestEntity-with-conf",
            "    item:",
            "      type: org.apache.brooklyn.core.test.entity.TestEntity",
            "      brooklyn.parameters:",
            "      - name: map.type-merged",
            "        type: java.util.Map",
            "        inheritance.runtime: deep_merge");

    String yaml = Joiner.on("\n").join(
            "location: localhost-stub",
            "services:",
            "- type: "+BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    map.type-merged:",
            "      mykey1: myval1",
            "  brooklyn.children:",
            "  - type: "+BasicApplication.class.getName(),
            "    brooklyn.config:",
            "      map.type-merged:",
            "        mykey2: myval2",
            "    brooklyn.children:",
            "    - type: TestEntity-with-conf",
            "      brooklyn.config:",
            "        map.type-merged:",
            "          mykey3: myval3");

    Entity app = createStartWaitAndLogApplication(yaml);
    Entity entity = Iterables.find(Entities.descendantsAndSelf(app), Predicates.instanceOf(TestEntity.class));

    assertEquals(entity.config().get(entity.getEntityType().getConfigKey("map.type-merged")), 
            ImmutableMap.<String, Object>of("mykey1", "myval1", "mykey2", "myval2", "mykey3", "myval3"));
}
 
Example 8
@Test
public void testServiceReplacerWorksAfterRebind() throws Exception {
    Location origLoc = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class));
    DynamicCluster origCluster = origApp.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
            .configure(DynamicCluster.INITIAL_SIZE, 3));
    origApp.start(ImmutableList.<Location>of(origLoc));

    origCluster.policies().add(PolicySpec.create(ServiceReplacer.class)
            .configure(ServiceReplacer.FAILURE_SENSOR_TO_MONITOR, HASensors.ENTITY_FAILED));

    // rebind
    TestApplication newApp = rebind();
    final DynamicCluster newCluster = (DynamicCluster) Iterables.find(newApp.getChildren(), Predicates.instanceOf(DynamicCluster.class));

    // stimulate the policy
    final Set<Entity> initialMembers = ImmutableSet.copyOf(newCluster.getMembers());
    final TestEntity e1 = (TestEntity) Iterables.get(initialMembers, 1);
    
    newApp.getManagementContext().getSubscriptionManager().subscribe(e1, HASensors.ENTITY_FAILED, eventListener);
    newApp.getManagementContext().getSubscriptionManager().subscribe(e1, HASensors.ENTITY_RECOVERED, eventListener);
    
    e1.sensors().emit(HASensors.ENTITY_FAILED, new FailureDescriptor(e1, "simulate failure"));
    
    // Expect e1 to be replaced
    Asserts.succeedsEventually(new Runnable() {
        @Override public void run() {
            Set<Entity> newMembers = Sets.difference(ImmutableSet.copyOf(newCluster.getMembers()), initialMembers);
            Set<Entity> removedMembers = Sets.difference(initialMembers, ImmutableSet.copyOf(newCluster.getMembers()));
            assertEquals(removedMembers, ImmutableSet.of(e1));
            assertEquals(newMembers.size(), 1);
            assertEquals(((TestEntity)Iterables.getOnlyElement(newMembers)).getCallHistory(), ImmutableList.of("start"));
            
            // TODO e1 not reporting "start" after rebind because callHistory is a field rather than an attribute, so was not persisted
            Asserts.assertEqualsIgnoringOrder(e1.getCallHistory(), ImmutableList.of("stop"));
            assertFalse(Entities.isManaged(e1));
        }});
}
 
Example 9
/**
 * Gets the file with given file name.
 *
 * @param fileName
 *          the file name
 * @return the file
 */
private IFile getFile(final String fileName) {
  return Iterables.find(files, new Predicate<IFile>() {
    @Override
    public boolean apply(final IFile input) {
      return getFileName(fileName).equals(input.getName());
    }
  });
}
 
Example 10
@Test
public void testRestoresEntityDependentConfigUncompleted() throws Exception {
    origApp.createAndManageChild(EntitySpec.create(MyEntity.class)
            .configure("myconfig", DependentConfiguration.attributeWhenReady(origApp, TestApplication.MY_ATTRIBUTE)));
    
    newApp = rebind();
    MyEntity newE = (MyEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(MyEntity.class));

    // because Task is not persisted; should log a warning above
    newApp.sensors().set(TestApplication.MY_ATTRIBUTE, "myval");
    assertEquals(newE.getConfig(MyEntity.MY_CONFIG), null);
}
 
Example 11
/**
 * Get the thread entry id for a given TID and time
 *
 * @param tid
 *            queried TID
 * @param time
 *            queried time stamp
 * @return the id for the desired thread or -1 if it does not exist
 */
private long findEntry(int tid, long time) {
    /*
     * FIXME TreeMultimap values are Navigable Sets sorted by start time, find the
     * values using floor and the relevant anonymous class if ever the iteration
     * below slows down.
     */
    ThreadEntryModel.Builder entry = Iterables.find(fTidToEntry.get(tid),
            cfe -> cfe.getStartTime() <= time && time <= cfe.getEndTime(), null);
    return entry != null ? entry.getId() : fTraceId;
}
 
Example 12
@Test
public void testDslInServiceReplacerPolicy() throws Exception {
    RecordingRebindExceptionHandler exceptionHandler = new RecordingRebindExceptionHandler(RecordingRebindExceptionHandler.builder()
            .strict());
    
    Entity app = createAndStartApplication(
            "services:",
            "- type: "+DynamicCluster.class.getName(),
            "  brooklyn.config:",
            "    initialSize: 0",
            "  brooklyn.policies:",
            "  - type: "+ServiceReplacer.class.getName(),
            "    brooklyn.config:",
            "      failureSensorToMonitor: $brooklyn:sensor(\"ha.entityFailed\")");
    waitForApplicationTasks(app);
    DynamicCluster cluster = (DynamicCluster) Iterables.getOnlyElement(app.getChildren());
    ServiceReplacer policy = (ServiceReplacer) Iterables.find(cluster.policies(), Predicates.instanceOf(ServiceReplacer.class));
    Sensor<?> sensor = policy.config().get(ServiceReplacer.FAILURE_SENSOR_TO_MONITOR);
    assertEquals(sensor.getName(), "ha.entityFailed");
    
    rebind(RebindOptions.create().exceptionHandler(exceptionHandler));
    
    Entity newApp = mgmt().getEntityManager().getEntity(app.getId());
    DynamicCluster newCluster = (DynamicCluster) Iterables.getOnlyElement(newApp.getChildren());
    ServiceReplacer newPolicy = (ServiceReplacer) Iterables.find(newCluster.policies(), Predicates.instanceOf(ServiceReplacer.class));
    
    Sensor<?> newSensor2 = ((EntityInternal)newCluster).getExecutionContext().submit("get-policy-config", new Callable<Sensor<?>>() {
        public Sensor<?> call() {
            return newPolicy.config().get(ServiceReplacer.FAILURE_SENSOR_TO_MONITOR);
        }})
        .get();
    assertEquals(newSensor2.getName(), "ha.entityFailed");
}
 
Example 13
@Test
public void testFailureGeneratingMementoStillPersistsOtherEntities() throws Exception {
    MyEntity origE = origApp.createAndManageChild(EntitySpec.create(MyEntity.class));
    MyEntity origFailingE = origApp.createAndManageChild(EntitySpec.create(MyEntity.class)
            .impl(MyEntityFailingImpl.class)
            .configure(MyEntityFailingImpl.FAIL_ON_GENERATE_MEMENTO, true));
    
    newApp = rebind(RebindOptions.create().defaultExceptionHandler());
    MyEntity newE = (MyEntity) Iterables.find(newApp.getChildren(), EntityPredicates.idEqualTo(origE.getId()));
    Optional<Entity> newFailingE = Iterables.tryFind(newApp.getChildren(), EntityPredicates.idEqualTo(origFailingE.getId()));
    
    // Expect origFailingE to never have been persisted, but origE to have worked
    assertNotNull(newE);
    assertFalse(newFailingE.isPresent(), "newFailedE="+newFailingE);
}
 
Example 14
@Test
public void testBrooklynIdentityFunction() throws Exception {
    Iterable<? extends Entity> testEntities = setupAndCheckTestEntityInBasicYamlWith();
    Entity entityOne = Iterables.find(testEntities, EntityPredicates.displayNameEqualTo("Test Entity One"));
    Entity entityTwo = Iterables.find(testEntities, EntityPredicates.displayNameEqualTo("Test Entity Two"));

    Assert.assertNotNull(entityOne, "Test entity one should be present");
    Assert.assertNotNull(entityTwo, "Test entity two should be present");

    Assert.assertEquals(entityOne.config().get(TEST_ENTITY_ONE_ID), entityOne.getId(), "Entity one IDs should match");
    Assert.assertEquals(entityOne.config().get(TEST_ENTITY_TWO_ID), entityTwo.getId(), "Entity two IDs should match");
}
 
Example 15
@Nullable
public static AndroidArtifact instrumentTestArtifact(Iterable<AndroidArtifact> artifacts) {
    return artifacts == null
            ? null
            : Iterables.find(
                    artifacts,
                    new Predicate<AndroidArtifact>() {
                @Override
                public boolean apply(AndroidArtifact a) {
                    return AndroidProject.ARTIFACT_ANDROID_TEST.equals(a.getName());
                }
            },
                    null);
}
 
Example 16
@Override
public Token<?> evaluate(CharacterScanner charScanner) {
	int charScanned = charScanner.read();
	if (this.wordDetector.isWordStart((char) charScanned)) {
		StringBuilder resultText = new StringBuilder();
		do {
			resultText.append((char) charScanned);
			charScanned = charScanner.read();
		} while (this.isWordPart(charScanned));
		charScanner.unread();

		WordMatcher matcher = Iterables.find(this.wordMatchers, new WordMatcherSelector(resultText.toString()), null);

		TokenContent content = null;
		if (matcher != null) {
			content = matcher.getTokenContent();
		}
		if (content != null || this.defaultTokenContent != null) {
			content = content != null ? content : this.defaultTokenContent;
			return new SimpleToken<TokenContent>(charScanner.getMark(), resultText.toString(), content);
		}
		for (int i = 1; i < resultText.length(); i++) {
			charScanner.unread();
		}
	}
	charScanner.unread();
	return SimpleToken.UNDEFINED_TOKEN;
}
 
Example 17
@Test(groups = {"Integration","Broken"})
public void testRebindsToRunningCluster() throws Exception {
    DynamicWebAppCluster origCluster = app().createAndManageChild(EntitySpec.create(DynamicWebAppCluster.class)
            .configure("memberSpec", EntitySpec.create(JBoss7Server.class).configure("war", getTestWar()))
            .configure("initialSize", 1));
    
    app().start(ImmutableList.of(localhostProvisioningLocation));
    JBoss7Server origJboss = (JBoss7Server) Iterables.find(origCluster.getChildren(), Predicates.instanceOf(JBoss7Server.class));
    String jbossUrl = origJboss.getAttribute(JBoss7Server.ROOT_URL);
    
    assertHttpStatusCodeEventuallyEquals(jbossUrl, 200);
    WebAppMonitor monitor = newWebAppMonitor(jbossUrl);
    
    // Rebind
    rebind();
    DynamicWebAppCluster newCluster = (DynamicWebAppCluster) Iterables.find(app().getChildren(), Predicates.instanceOf(DynamicWebAppCluster.class));

    assertHttpStatusCodeEquals(jbossUrl, 200);

    // Confirm the cluster is usable: we can scale-up
    assertEquals(newCluster.getCurrentSize(), (Integer)1);
    newCluster.resize(2);

    Iterable<Entity> newJbosses = Iterables.filter(newCluster.getChildren(), Predicates.instanceOf(JBoss7Server.class));
    assertEquals(Iterables.size(newJbosses), 2);
    for (Entity j : newJbosses) {
        assertHttpStatusCodeEventuallyEquals(j.getAttribute(JBoss7Server.ROOT_URL), 200);
    }

    // Ensure while doing all of this the original jboss server remained reachable
    assertEquals(monitor.getFailures(), 0);
    
    // Ensure cluster is usable: we can scale back to stop the original jboss server
    newCluster.resize(0);
    
    assertUrlUnreachableEventually(jbossUrl);
}
 
Example 18
Source Project: exhibitor   File: UsState.java    License: Apache License 2.0 4 votes vote down vote up
public static ServerSpec findUs(Exhibitor exhibitor, List<ServerSpec> specs)
{
    return Iterables.find(specs, ServerList.isUs(exhibitor.getThisJVMHostname()), null);
}
 
Example 19
@Test
public void testSshCommandSensorWithEffectorInEnv() throws Exception {
    RecordingSshTool.setCustomResponse(".*myCommand.*", new RecordingSshTool.CustomResponse(0, "myResponse", null));
    
    createStartWaitAndLogApplication(
        "location:",
        "  localhost:",
        "    sshToolClass: "+RecordingSshTool.class.getName(),
        "services:",
        "- type: " + VanillaSoftwareProcess.class.getName(),
        "  brooklyn.config:",
        "    onbox.base.dir.skipResolution: true",
        "  brooklyn.initializers:",
        "  - type: org.apache.brooklyn.core.sensor.ssh.SshCommandSensor",
        "    brooklyn.config:",
        "      name: mySensor",
        "      command: myCommand",
        "      executionDir: '/path/to/myexecutiondir'",
        "      shell.env:",
        "        MY_ENV: myEnvVal",
        "      period: 10ms",
        "      onlyIfServiceUp: false");

    StartableApplication newApp = rebind();
    VanillaSoftwareProcess newEntity = (VanillaSoftwareProcess) Iterables.getOnlyElement(newApp.getChildren());
    SshFeed newFeed = (SshFeed) Iterables.find(((EntityInternal)newEntity).feeds().getFeeds(), Predicates.instanceOf(SshFeed.class));
    
    // Clear history of commands, and the sensor, so can confirm it gets re-set by the ssh feed
    RecordingSshTool.clearCmdHistory();
    newEntity.sensors().set(Sensors.newStringSensor("mySensor"), null);
    
    // Assert sensor is set, and command is executed as expected
    EntityAsserts.assertAttributeEqualsEventually(newEntity, Sensors.newStringSensor("mySensor"), "myResponse");
    ExecCmd cmd = Asserts.succeedsEventually(() -> RecordingSshTool.getLastExecCmd());
    
    assertTrue(cmd.commands.toString().contains("myCommand"), "cmds="+cmd.commands);
    assertEquals(cmd.env.get("MY_ENV"), "myEnvVal", "env="+cmd.env);
    assertTrue(cmd.commands.toString().contains("/path/to/myexecutiondir"), "cmds="+cmd.commands);
    
    // Confirm feed's memento is 'clean' - no anonymous inner classes
    BrooklynMementoRawData rawMemento = loadMementoRawData();
    String rawFeedMemento = rawMemento.getFeeds().get(newFeed.getId());
    assertFalse(rawFeedMemento.contains("$1"), rawFeedMemento);
    assertFalse(rawFeedMemento.contains("$2"), rawFeedMemento);
    assertFalse(rawFeedMemento.contains("$3"), rawFeedMemento);
}
 
Example 20
Source Project: buck   File: DefaultJavaLibraryTest.java    License: Apache License 2.0 4 votes vote down vote up
public JavacStep getJavacStep(Iterable<Step> steps) {
  Step step = Iterables.find(steps, command -> command instanceof JavacStep);
  assertNotNull("Expected a JavacStep in the steplist.", step);
  return (JavacStep) step;
}