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

The following examples show how to use org.apache.brooklyn.util.exceptions.Exceptions#propagate() . 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: Streams.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static String getMd5Checksum(InputStream in) {
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw Exceptions.propagate(e);
    }
    DigestInputStream dis = new DigestInputStream(in, md);
    readFullyAndClose(dis);
    byte[] digest = md.digest();
    StringBuilder result = new StringBuilder();
    for (byte b: digest) {
        result.append(Strings.padStart(Integer.toHexString((256+b)%256), 2, '0'));
    }
    return result.toString().toUpperCase();
}
 
Example 2
Source File: CampServer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static Server startServer(ContextHandler context, String summary) {
    // FIXME port hardcoded
    int port = Networking.nextAvailablePort(8080);

    // use a nice name in the thread pool (otherwise this is exactly the same as Server defaults)
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setName("camp-jetty-server-"+port+"-"+threadPool.getName());

    Server server = new Server(threadPool);

    ServerConnector httpConnector = new ServerConnector(server);
    httpConnector.setPort(port);
    server.addConnector(httpConnector);

    server.setHandler(context);

    try {
        server.start();
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    } 
    log.info("CAMP REST server started ("+summary+") on");
    log.info("  http://localhost:"+httpConnector.getLocalPort()+"/");

    return server;
}
 
Example 3
Source File: Tasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean call() {
    ReferenceWithError<Boolean> result;
    Tasks.setBlockingDetails(repeater.getDescription());
    try {
       result = repeater.runKeepingError();
    } finally {
        Tasks.resetBlockingDetails();
    }

    if (Boolean.TRUE.equals(result.getWithoutError()))
        return true;
    if (result.hasError()) 
        throw Exceptions.propagate(result.getError());
    if (requireTrue)
        throw new IllegalStateException("timeout - "+repeater.getDescription());
    return false;
}
 
Example 4
Source File: BrooklynJacksonSerializerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> T checkSerializesAs(Object x, Class<T> type) {
    ManagementContext mgmt = LocalManagementContextForTests.newInstance();
    try {
        ObjectMapper mapper = BrooklynJacksonJsonProvider.newPrivateObjectMapper(mgmt);
        String tS = mapper.writeValueAsString(x);
        log.debug("serialized "+x+" as "+tS);
        Assert.assertTrue(tS.length() < 1000, "Data too long, size "+tS.length()+" for "+x);
        if (type==null) return (T) tS;
        return mapper.readValue(tS, type);
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    } finally {
        Entities.destroyAll(mgmt);
    }
}
 
Example 5
Source File: ParallelTestCaseImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void stop() {
    // Let everyone know we're stopping (so that the GUI shows the correct icon).
    sensors().set(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STOPPING);

    // Get an unsubmitted task for stopping all the children of this entity in parallel.
    final TaskAdaptable<?> taskAdaptable = StartableMethods.stoppingChildren(this);
    logger.trace("{}, TaskAdaptable: {}", this, taskAdaptable);
    try {
        // Submit the task to the ExecutionManager so that they actually get stopped
        // and then wait until all the parallel entities have completed.
        submitTaskAndWait(taskAdaptable);
        
        // Let everyone know we've stopped successfully (changes the icon in the GUI).
        logger.debug("Tasks successfully run. Update state of {} to STOPPED.", this);
        setServiceState(false, Lifecycle.STOPPED);
    } catch (Throwable t) {
        logger.debug("Tasks NOT successfully run. Update state of {} to ON_FIRE.", this);
        setServiceState(false, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(t);
    }
}
 
Example 6
Source File: ParallelTestCaseImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void restart() {
    // Let everyone know we're restarting (so that the GUI shows the correct icon).
    setServiceState(false, Lifecycle.STARTING);

    // Get an unsubmitted task for restarting all the children of this entity in parallel.
    final TaskAdaptable<?> taskAdaptable = StartableMethods.restartingChildren(this);
    logger.trace("{}, TaskAdaptable: {}", this, taskAdaptable);

    try {
        // Submit the task to the ExecutionManager so that they actually get stopped
        // and then wait until all the parallel entities have completed.
        submitTaskAndWait(taskAdaptable);

        // Let everyone know we've started up successfully (changes the icon in the GUI).
        logger.debug("Tasks successfully run. Update state of {} to RUNNING.", this);
        setServiceState(true, Lifecycle.RUNNING);
    } catch (Throwable t) {
        logger.debug("Tasks NOT successfully run. Update state of {} to ON_FIRE.", this);
        setServiceState(false, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(t);
    }
}
 
Example 7
Source File: JcloudsMaxConcurrencyStubbedTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void onStart() {
    synchronized (mutex) {
        int concurrentCallCount = concurrentCalls.incrementAndGet();
        if (concurrentCallCount > maxConcurrentCalls.get()) {
            maxConcurrentCalls.set(concurrentCallCount);
        }
    }
    if (latch != null) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw Exceptions.propagate(e);
        }
    }
}
 
Example 8
Source File: AbstractRestResourceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public String load(String path) {
    try {
        String base = "http://localhost:"+server.getPort();
        String x = path.startsWith(base) ? path : Urls.mergePaths(base, path);
        log.debug("Reading from: "+x);
        String s = Files.streamToString(new URL(x).openStream());
        log.debug("Result from "+x+": "+s);
        return s;
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 9
Source File: LoaderDispatcher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Maybe<Iterable<URL>> tryLoadFrom(ClassLoader classLoader, String name) {
    try {
        return emptyToMaybeNull(classLoader.getResources(name));
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 10
Source File: MachineLifecycleEffectorTasksTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testProvisionLatchObeyed() throws Exception {

    AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");

    BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));

    EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
            .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready)));

    final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of(
            "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext()))));
    
    Time.sleep(ValueResolver.PRETTY_QUICK_WAIT);
    if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.get());
    assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName());

    Asserts.succeedsContinually(new Runnable() {
        @Override
        public void run() {
            if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.getUnchecked());
        }
    });
    try {
        triggerEntity.sensors().set(ready, true);
        task.get(Duration.THIRTY_SECONDS);
    } catch (Throwable t) {
        Exceptions.propagateIfFatal(t);
        if ((t.toString().contains(BailOutJcloudsLocation.ERROR_MESSAGE))) {
            // expected - BailOut location throws - just swallow
        } else {
            Exceptions.propagate(t);
        }
    }
}
 
Example 11
Source File: AwsEc2SessionAwareComputeServiceRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected Supplier<Credentials> makeCredentials(ConfigBag conf) {
    Credentials credentials;
    String identity = null, credential = null, token = null;
    Date expiration = null;
    String provider = getProviderFromConfig(conf);
    String iamRoleName = getIamRoleNameFromConfig(conf);
    if ("aws-ec2".equals(provider)) {
        try {
            String instanceProfileUrl = AWS_SECURITY_CREDENTIAL_URL;
            JsonNode node = new ObjectMapper().readTree(new URL(instanceProfileUrl + "/" + iamRoleName));
            identity = node.path(ACCESS_KEY_ID).asText();
            credential = node.path(SECRET_ACCESS_KEY).asText();
            token = node.path(TOKEN).asText();
            expiration = new SimpleDateFormat(AWS_EXPIRATION_DATE_FORMAT).parse(node.path(EXPIRATION).asText());
        } catch (IOException | ParseException e) {
            Exceptions.propagate(e);
        }
    } else {
        throw new IllegalArgumentException("Provider " + provider + " does not support session credentials");
    }

    identity = checkNotNull(identity, "identity must not be null");
    credential = checkNotNull(credential, "credential must not be null");
    token = checkNotNull(token, "token must not be null");

    credentials = SessionCredentials.builder()
            .accessKeyId(identity)
            .credential(credential)
            .sessionToken(token)
            .expiration(expiration)
            .build();
    return () -> credentials;
}
 
Example 12
Source File: MavenArtifactTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void checkAvailableUrl(String url) throws Exception {
    try {
        InputStream stream = new URL(url).openStream();
        stream.read();
        stream.close();
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 13
Source File: Tomcat8ServerWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
@DataProvider(name = "basicEntities")
public Object[][] basicEntities() {
    TestApplication tomcatApp = newTestApplication();
    Tomcat8Server tomcat = tomcatApp.createAndManageChild(EntitySpec.create(Tomcat8Server.class)
            .configure(Tomcat8Server.HTTP_PORT, PortRanges.fromString(DEFAULT_HTTP_PORT)));


    File keystoreFile;
    try {
        keystoreFile = createTemporaryKeyStore("myname", "mypass");
        keystoreFile.deleteOnExit();
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }

    TestApplication tomcatHttpsApp = newTestApplication();
    Tomcat8Server httpsTomcat = tomcatHttpsApp.createAndManageChild(EntitySpec.create(Tomcat8Server.class)
            .configure(Tomcat8Server.ENABLED_PROTOCOLS, ImmutableSet.of("https"))
            .configure(Tomcat8Server.HTTPS_SSL_CONFIG,
                    new HttpsSslConfig().keyAlias("myname").keystorePassword("mypass").keystoreUrl(keystoreFile.getAbsolutePath())));

    return new JavaWebAppSoftwareProcess[][] {
            new JavaWebAppSoftwareProcess[] { tomcat },
            new JavaWebAppSoftwareProcess[] { httpsTomcat }
    };
}
 
Example 14
Source File: ChefLifecycleEffectorTasks.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
protected void startWithKnifeAsync() {
    // TODO prestart, ports (as above); also, note, some aspects of this are untested as we need a chef server
    
    String primary = getPrimaryCookbook();

    // put all config under brooklyn/cookbook/config
    Navigator<MutableMap<Object, Object>> attrs = Jsonya.newInstancePrimitive().at("brooklyn");
    if (Strings.isNonBlank(primary)) attrs.at(primary);
    attrs.at("config");
    attrs.put( entity().config().getBag().getAllConfig() );
    // and put launch attrs at root
    try {
        attrs.root().put((Map<?,?>)Tasks.resolveDeepValue(entity().getConfig(CHEF_LAUNCH_ATTRIBUTES), Object.class, entity().getExecutionContext()));
    } catch (Exception e) { Exceptions.propagate(e); }

    Collection<? extends String> runList = entity().getConfig(CHEF_LAUNCH_RUN_LIST);
    if (runList==null) runList = entity().getConfig(CHEF_RUN_LIST);
    if (runList==null) {
        if (Strings.isNonBlank(primary)) runList = ImmutableList.of(primary+"::"+"start");
        else throw new IllegalStateException("Require a primary cookbook or a run_list to effect "+"start"+" on "+entity());
    }

    DynamicTasks.queue(
            ChefServerTasks.knifeConvergeTask()
                .knifeNodeName(getNodeName())
                .knifeRunList(Strings.join(runList, ","))
                .knifeAddAttributes((Map) attrs.root().get())
                .knifeRunTwice(entity().getConfig(CHEF_RUN_CONVERGE_TWICE)) );
}
 
Example 15
Source File: EntityConfigUsageTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAttributeWhenReadyConfigBlocksUntilSet() throws Exception {
    final TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    TestEntity entity2 = app.createAndManageChild(EntitySpec.create(TestEntity.class)
            .configure(TestEntity.CONF_NAME, DependentConfiguration.attributeWhenReady(entity, TestEntity.NAME)));
    app.start(locs);
    
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10+EARLY_RETURN_GRACE);
                entity.sensors().set(TestEntity.NAME, "aval");
            } catch (InterruptedException e) {
                throw Exceptions.propagate(e);
            }
        }});
    try {
        long starttime = System.currentTimeMillis();
        t.start();
        assertEquals(entity2.getConfig(TestEntity.CONF_NAME), "aval");
        long endtime = System.currentTimeMillis();
        
        assertTrue((endtime - starttime) > 10, "starttime="+starttime+"; endtime="+endtime);
        
    } finally {
        t.interrupt();
    }
}
 
Example 16
Source File: AbstractSoftwareProcessWinRmDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void copyPreInstallResources() {
    final WithMutexes mutexSupport = getLocation().mutexes();
    String mutexId = "installation lock at host";
    mutexSupport.acquireMutex(mutexId, "pre-installing " + elvis(entity, this));
    try {
        super.copyPreInstallResources();
    } catch (Exception e) {
        LOG.warn("Error copying pre-install resources", e);
        throw Exceptions.propagate(e);
    } finally {
        mutexSupport.releaseMutex(mutexId);
    }
}
 
Example 17
Source File: LoginUserPrivateKeyFileOption.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(TemplateOptions t, ConfigBag props, Object v) {
    if (v != null) {
        String privateKeyFileName = v.toString();
        String privateKey;
        try {
            privateKey = Files.toString(new File(Os.tidyPath(privateKeyFileName)), Charsets.UTF_8);
        } catch (IOException e) {
            LOG.error(privateKeyFileName + "not found", e);
            throw Exceptions.propagate(e);
        }
        t.overrideLoginPrivateKey(privateKey);
    }
}
 
Example 18
Source File: OsgiLauncherImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Configuration getConfiguration(ConfigurationAdmin configAdmin, String brooklynConfigPid) {
    String filter = '(' + Constants.SERVICE_PID + '=' + brooklynConfigPid + ')';
    Configuration[] configs;
    try {
        configs = configAdmin.listConfigurations(filter);
    } catch (InvalidSyntaxException | IOException e) {
        throw Exceptions.propagate(e);
    }
    if (configs != null && configs.length > 0) {
        return configs[0];
    } else {
        return null;
    }
}
 
Example 19
Source File: Aggregator.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void onUpdated() {
    try {
        emit(targetSensor, compute());
    } catch (Throwable t) {
        LOG.warn("Error calculating and setting aggregate for enricher "+this, t);
        throw Exceptions.propagate(t);
    }
}
 
Example 20
Source File: HighAvailabilityManagerImpl.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected void registerPollTask() {
    final Runnable job = new Runnable() {
        private boolean lastFailed;
        
        @Override public void run() {
            try {
                publishAndCheck(false);
                lastFailed = false;
            } catch (Exception e) {
                if (running) {
                    if (lastFailed) {
                        if (LOG.isDebugEnabled()) LOG.debug("Recurring problem in HA-poller: "+e, e);
                    } else {
                        LOG.error("Problem in HA-poller: "+e, e);
                        lastFailed = true;
                    }
                } else {
                    if (LOG.isDebugEnabled()) LOG.debug("Problem in HA-poller, but no longer running: "+e, e);
                }
            } catch (Throwable t) {
                LOG.error("Problem in HA-poller: "+t, t);
                throw Exceptions.propagate(t);
            }
        }
    };
    Callable<Task<?>> taskFactory = new Callable<Task<?>>() {
        @Override public Task<?> call() {
            return Tasks.builder().dynamic(false).body(job).displayName("HA poller task").tag(BrooklynTaskTags.TRANSIENT_TASK_TAG)
                .description("polls HA status to see whether this node should promote").build();
        }
    };
    
    Duration pollPeriod = getPollPeriod();
    LOG.debug("Registering poll task for "+this+", period "+pollPeriod);
    if (pollPeriod.equals(Duration.PRACTICALLY_FOREVER)) {
        // don't schedule - used for tests
        // (scheduling fires off one initial task in the background before the delay, 
        // which affects tests that want to know exactly when publishing happens;
        // TODO would be nice if scheduled task had a "no initial submission" flag )
    } else {
        if (pollingTask!=null) pollingTask.cancel(true);
        
        ScheduledTask task = ScheduledTask.builder(taskFactory).period(pollPeriod).displayName("scheduled:[HA poller task]").tagTransient().build();
        pollingTask = managementContext.getExecutionManager().submit(task);
    }
}