Java Code Examples for org.apache.brooklyn.util.exceptions.Exceptions#getFirstThrowableOfType()

The following examples show how to use org.apache.brooklyn.util.exceptions.Exceptions#getFirstThrowableOfType() . 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: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceMemberFailsIfCantProvisionReplacement() throws Exception {
    final int failNum = 2;
    final AtomicInteger counter = new AtomicInteger(0);
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("memberSpec", EntitySpec.create(FailingEntity.class)
                    .configure(FailingEntity.FAIL_ON_START_CONDITION, new Predicate<FailingEntity>() {
                        @Override public boolean apply(FailingEntity input) {
                            return counter.incrementAndGet() == failNum;
                        }})));

    cluster.start(ImmutableList.of(loc));
    Entity member = Iterables.get(cluster.getMembers(), 0);

    try {
        cluster.replaceMember(member.getId());
        fail();
    } catch (Exception e) {
        if (!e.toString().contains("failed to grow")) throw e;
        if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) != null) throw e;
    }
    assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
}
 
Example 2
Source File: TestHttpCallTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration")
public void testMaxAttempts() {
    app.addChild(EntitySpec.create(TestHttpCall.class)
            .configure(TestHttpCall.TARGET_URL, server.getUrl() + "/201")
            .configure(TestHttpCall.TIMEOUT, Duration.minutes(1))
            .configure(TestHttpCall.MAX_ATTEMPTS, 1)
            .configure(TestSensor.ASSERTIONS, newAssertion("isEqualTo", "Wrong")));
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        app.start(ImmutableList.of(loc));
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        AssertionError ae = Exceptions.getFirstThrowableOfType(e, AssertionError.class);
        if (ae == null || !ae.toString().contains("body expected isEqualTo Wrong")) {
            throw e;
        }
    }
    Duration duration = Duration.of(stopwatch);
    assertTrue(duration.isShorterThan(Asserts.DEFAULT_LONG_TIMEOUT), "duration="+duration);
}
 
Example 3
Source File: SshjToolIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration"})
public void testAsyncExecTimesOut() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    boolean origFeatureEnablement = BrooklynFeatureEnablement.enable(BrooklynFeatureEnablement.FEATURE_SSH_ASYNC_EXEC);
    try {
        tool.execScript(
            ImmutableMap.of(SshjTool.PROP_EXEC_ASYNC.getName(), true, SshjTool.PROP_EXEC_TIMEOUT.getName(), Duration.millis(1)), 
            ImmutableList.of("sleep 60"), 
            ImmutableMap.<String,String>of());
        fail();
    } catch (Exception e) {
        TimeoutException te = Exceptions.getFirstThrowableOfType(e, TimeoutException.class);
        if (te == null) throw e;
    } finally {
        BrooklynFeatureEnablement.setEnablement(BrooklynFeatureEnablement.FEATURE_SSH_ASYNC_EXEC, origFeatureEnablement);
    }
    
    long seconds = stopwatch.elapsed(TimeUnit.SECONDS);
    assertTrue(seconds < 30, "exec took "+seconds+" seconds");
}
 
Example 4
Source File: LoaderDispatcher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void propagateIfCauseNotClassNotFound(IllegalStateException e) {
    // TODO loadClass() should not throw IllegalStateException; should throw ClassNotFoundException without wrapping.
    ClassNotFoundException cnfe = Exceptions.getFirstThrowableOfType(e, ClassNotFoundException.class);
    NoClassDefFoundError ncdfe = Exceptions.getFirstThrowableOfType(e, NoClassDefFoundError.class);
    if (cnfe == null && ncdfe == null) {
        throw e;
    } else {
        if (ncdfe != null) {
            log.debug("Class loading failure", ncdfe);
        } else if (cnfe != null) {
            BundleException bundleException = Exceptions.getFirstThrowableOfType(cnfe, BundleException.class);
            // wiring problem
            if (bundleException != null) {
                log.debug("Class loading failure", cnfe);
            }
        }
        // ignore, try next way of loading
    }
}
 
Example 5
Source File: TestSensorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void assertStartFails(final TestApplication app, final Class<? extends Throwable> clazz, Duration execTimeout) throws Exception {
    Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                app.start(locs);
                Asserts.shouldHaveFailedPreviously();
            } catch (final PropagatedRuntimeException pre) {
                final Throwable throwable = Exceptions.getFirstThrowableOfType(pre, clazz);
                if (throwable == null) {
                    throw pre;
                }
            }
        }
    };

    if (execTimeout == null) {
        task.run();
    } else {
        Asserts.assertReturnsEventually(task, execTimeout);
    }

    Entity entity = Iterables.find(Entities.descendantsWithoutSelf(app), Predicates.instanceOf(TestSensor.class));
    assertTestSensorFails((TestSensor) entity);
}
 
Example 6
Source File: SshToolAbstractIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration"})
public void testSshKeyWithPrivateKeyData() throws Exception {
    final SshTool localtool = newTool(ImmutableMap.<String,Object>builder()
            .put(SshTool.PROP_HOST.getName(), "localhost")
            .put(SshTool.PROP_PRIVATE_KEY_DATA.getName(), new String(Files.toByteArray(new File(Os.tidyPath(SSH_DEFAULT_KEYFILE))), StandardCharsets.UTF_8))
            .build());
    localtool.connect();

    assertEquals(localtool.execScript(MutableMap.<String,Object>of(), ImmutableList.of("date")), 0);

    // Also needs the negative test to prove that we're really using an ssh-key with a passphrase
    try {
        final SshTool localtool2 = newTool(ImmutableMap.<String,Object>builder()
                .put(SshTool.PROP_HOST.getName(), "localhost")
                .put(SshTool.PROP_PRIVATE_KEY_DATA.getName(), "invalid data")
                .build());
        localtool2.connect();
        localtool2.execScript(MutableMap.<String,Object>of(), ImmutableList.of("date"));
        // Notice that executing a command may succeed for SshCliToolIntegrationTest.testSshKeyWithPrivateKeyData if you already have valid keys loaded in the ssh-agent
        fail();
    } catch (Exception e) {
        SshException se = Exceptions.getFirstThrowableOfType(e, SshException.class);
        if (se == null) throw e;
    }
}
 
Example 7
Source File: TestEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void assertStartFails(final TestApplication app, final Class<? extends Throwable> clazz, Duration execTimeout) throws Exception {
    Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                app.start(locs);
                Asserts.shouldHaveFailedPreviously();
            } catch (final PropagatedRuntimeException pre) {
                final Throwable throwable = Exceptions.getFirstThrowableOfType(pre, clazz);
                if (throwable == null) {
                    throw pre;
                }
            }
        }
    };

    if (execTimeout == null) {
        task.run();
    } else {
        Asserts.assertReturnsEventually(task, execTimeout);
    }

    Entity entity = Iterables.find(Entities.descendantsWithoutSelf(app), Predicates.instanceOf(TestEffector.class));
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, false);
}
 
Example 8
Source File: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceMemberThrowsIfMemberIdDoesNotResolve() throws Exception {
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("initialSize", 1)
            .configure("memberSpec", EntitySpec.create(TestEntity.class)));

    cluster.start(ImmutableList.of(loc));
    Entity member = Iterables.get(cluster.getMembers(), 0);

    try {
        cluster.replaceMember("wrong.id");
        fail();
    } catch (Exception e) {
        if (Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class) == null) throw e;
        if (!Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class).getMessage().contains("entity wrong.id cannot be resolved")) throw e;
    }

    assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.of(member));
}
 
Example 9
Source File: TargetableTestComponentTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testTargetEntityByIdNotFound() {
    app.addChild(EntitySpec.create(TestSensor.class)
            .configure(TestSensor.TARGET_ID, "myTargetId")
            .configure(TestSensor.SENSOR_NAME, STRING_SENSOR.getName())
            .configure(TestSensor.ASSERTIONS, ImmutableList.of(ImmutableMap.of("equals", "myval"))));

    try {
        app.start(ImmutableList.<Location>of());
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        NoSuchElementException e2 = Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class);
        if (e2 == null) throw e;
        Asserts.expectedFailureContains(e2, "No entity matching id myTargetId");
    }
}
 
Example 10
Source File: OwnedChildrenDeprecatedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentingOneselfForbidden() {
    Entity e = mgmt.getEntityManager().createEntity(EntitySpec.create(TestEntity.class));
    try {
        e.setParent(e);
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception ex) {
        Exception cause = Exceptions.getFirstThrowableOfType(ex, IllegalStateException.class);
        if (cause == null || !cause.toString().contains("cannot own itself")) {
            throw ex;
        }
    }
    
    assertNull(e.getParent());
    assertEquals(e.getChildren(), ImmutableList.of());
}
 
Example 11
Source File: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplaceMemberRemovesAndThowsIfFailToStopOld() throws Exception {
    final int failNum = 1;
    final AtomicInteger counter = new AtomicInteger(0);
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("initialSize", 1)
            .configure("memberSpec", EntitySpec.create(FailingEntity.class)
                    .configure(FailingEntity.FAIL_ON_STOP_CONDITION, new Predicate<FailingEntity>() {
                        @Override public boolean apply(FailingEntity input) {
                            return counter.incrementAndGet() == failNum;
                        }})));

    cluster.start(ImmutableList.of(loc));
    Entity member = Iterables.get(cluster.getMembers(), 0);

    try {
        cluster.replaceMember(member.getId());
        fail();
    } catch (Exception e) {
        if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
        boolean found = false;
        for (Throwable t : Throwables.getCausalChain(e)) {
            if (t.toString().contains("Simulating entity stop failure")) {
                found = true;
                break;
            }
        }
        if (!found) throw e;
    }
    assertFalse(Entities.isManaged(member));
    assertEquals(cluster.getMembers().size(), 1);
}
 
Example 12
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Predicate<? super Throwable> getQuarantineFilter() {
    Predicate<? super Throwable> result = getConfig(QUARANTINE_FILTER);
    if (result != null) {
        return result;
    } else {
        return new Predicate<Throwable>() {
            @Override public boolean apply(Throwable input) {
                return Exceptions.getFirstThrowableOfType(input, NoMachinesAvailableException.class) == null;
            }
        };
    }
}
 
Example 13
Source File: LocationSetFromFlagTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailsFastOnInvalidCoercion() {
    try {
        newLocation(MutableMap.of("int1", "thisisnotanint"));
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        if (Exceptions.getFirstThrowableOfType(e, IllegalArgumentException.class) == null) {
            throw e;
        }
    }
}
 
Example 14
Source File: BalanceableWorkerPoolTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultResizeFailsIfContainerGroupNotResizable() throws Exception {
    try {
        pool.resize(1);
        fail();
    } catch (Exception e) {
        if (Exceptions.getFirstThrowableOfType(e, UnsupportedOperationException.class) == null) throw e;
    }
}
 
Example 15
Source File: OwnedChildrenDeprecatedTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetParentWhenDiffersFromParentSetInConstructor() {
    Entity e = new AbstractEntity(app) {};
    Entity e2 = new AbstractEntity() {};
    try {
        e.setParent(e2);
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception ex) {
        Exception uoe = Exceptions.getFirstThrowableOfType(ex, UnsupportedOperationException.class);
        if (uoe == null || !uoe.toString().contains("Cannot change parent")) {
            throw ex;
        }
    }
}
 
Example 16
Source File: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitialQuorumSizeDefaultsToInitialSize() throws Exception {
    final int failNum = 1;
    final AtomicInteger counter = new AtomicInteger(0);
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("initialSize", 2)
            .configure("memberSpec", EntitySpec.create(FailingEntity.class)
                    .configure(FailingEntity.FAIL_ON_START_CONDITION, new Predicate<FailingEntity>() {
                        @Override public boolean apply(FailingEntity input) {
                            return counter.incrementAndGet() == failNum;
                        }})));

    try {
        cluster.start(ImmutableList.of(loc));
    } catch (Exception e) {
        IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
        if (unwrapped != null && unwrapped.getMessage().contains("failed to get to initial size")) {
            // success
        } else {
            throw e; // fail
        }
    }
    
    // note that children include quarantine group; and quarantined nodes
    assertEquals(cluster.getCurrentSize(), (Integer)1);
    assertEquals(cluster.getMembers().size(), 1);
    for (Entity member : cluster.getMembers()) {
        assertFalse(((FailingEntity)member).getConfig(FailingEntity.FAIL_ON_START));
    }
}
 
Example 17
Source File: MapListAndOtherStructuredConfigKeyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigKeyStringWontStoreAndRetrieveMaps() throws Exception {
    Map<String, String> v1 = ImmutableMap.of("a", "1", "b", "bb");
    //it only allows strings
    try {
        entity.config().set((ConfigKey)TestEntity.CONF_MAP_THING.subKey("akey"), v1);
        fail();
    } catch (Exception e) {
        ClassCastException cce = Exceptions.getFirstThrowableOfType(e, ClassCastException.class);
        if (cce == null) throw e;
        if (!cce.getMessage().contains("Cannot coerce type")) throw e;
    }
}
 
Example 18
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnricherSpecThrowsOnPropagatesAndPropagatesAllSet() throws Exception {
    try {
        app.enrichers().add(EnricherSpec.create(Propagator.class)
                .configure(MutableMap.builder()
                        .put(Propagator.PRODUCER, entity)
                        .put(Propagator.PROPAGATING, ImmutableList.of(TestEntity.NAME))
                        .put(Propagator.PROPAGATING_ALL, true)
                        .build()));
    } catch (Exception e) {
        IllegalStateException ise = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
        if (ise == null) throw e;
    }
}
 
Example 19
Source File: JcloudsGceHardwareProfilesStubbedLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups={"Live", "Live-sanity"})
public void testJcloudsCreateWithHardwareIdShortFormWithNoRegion() throws Exception {
    replaceJcloudsLocation(GCE_PROVIDER);
    
    try {
        obtainMachine(ImmutableMap.of(JcloudsLocation.HARDWARE_ID, N1_STANDARD_1_HARDWARE_ID));
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        NoSuchElementException nsee = Exceptions.getFirstThrowableOfType(e, NoSuchElementException.class);
        if (nsee == null || !nsee.toString().contains("hardwareId("+N1_STANDARD_1_HARDWARE_ID+") not found")) {
            throw e;
        }
    }
}
 
Example 20
Source File: DynamicFabricTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicFabricDoesNotAcceptUnstartableChildren() throws Exception {
    DynamicFabric fabric = app.createAndManageChild(EntitySpec.create(DynamicFabric.class)
            .configure("memberSpec", EntitySpec.create(BasicEntity.class)));

    try {
        fabric.start(ImmutableList.of(loc1));
        assertEquals(fabric.getChildren().size(), 1);
    } catch (Exception e) {
        IllegalStateException unwrapped = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
        if (unwrapped == null || !unwrapped.toString().contains("is not Startable")) {
            throw e;
        }
    }
}