org.eclipse.jetty.util.component.AbstractLifeCycle Java Examples

The following examples show how to use org.eclipse.jetty.util.component.AbstractLifeCycle. 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: ApiServer.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
public static ApiServer start(
    String schedulerHostname,
    SchedulerConfig schedulerConfig,
    Collection<Object> resources,
    Runnable startedCallback)
{
  ApiServer apiServer = new ApiServer(schedulerConfig, resources);
  apiServer.start(new AbstractLifeCycle.AbstractLifeCycleListener() {
    @Override
    public void lifeCycleStarted(LifeCycle event) {
      awaitSchedulerDns(schedulerHostname, schedulerConfig);
      startedCallback.run();
    }
  });
  return apiServer;
}
 
Example #2
Source File: MockApplication.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public void run(MockConfiguration configuration, Environment environment) throws Exception
{
    AbstractBinder abstractBinder = new AbstractBinder()
    {
        @Override
        protected void configure()
        {
            bind(new MockHK2Injected()).to(MockHK2Injected.class);
        }
    };
    environment.jersey().register(abstractBinder);
    environment.jersey().register(MockResource.class);
    LifeCycle.Listener listener = new AbstractLifeCycle.AbstractLifeCycleListener()
    {
        @Override
        public void lifeCycleStarted(LifeCycle event)
        {
            System.out.println("Starting...");
            startedLatch.countDown();
        }
    };
    environment.lifecycle().addLifeCycleListener(listener);
}
 
Example #3
Source File: MyApp.java    From dropwizard-websockets with MIT License 6 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws InvalidKeySpecException, NoSuchAlgorithmException, ServletException, DeploymentException {
    environment.lifecycle().addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {

        @Override
        public void lifeCycleStarted(LifeCycle event) {
            cdl.countDown();
        }
    });
    environment.jersey().register(new MyResource());
    environment.healthChecks().register("alive", new HealthCheck() {
        @Override
        protected HealthCheck.Result check() throws Exception {
            return HealthCheck.Result.healthy();
        }
    });

    // Using ServerEndpointConfig lets you inject objects to the websocket endpoint:
    final ServerEndpointConfig config = ServerEndpointConfig.Builder.create(EchoServer.class, "/extends-ws").build();
    // config.getUserProperties().put(Environment.class.getName(), environment);
    // Then you can get it from the Session object
    // - obj = session.getUserProperties().get("objectName");            
    websocketBundle.addEndpoint(config);
}
 
Example #4
Source File: JettyClientMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void beforeEach() throws Exception {
    server.insertHandler(new HandlerWrapper() {
        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
            switch (request.getPathInfo()) {
                case "/errorUnchecked":
                    throw new RuntimeException("big boom");
                case "/error":
                    response.setStatus(500);
                case "/ok":
                    baseRequest.setHandled(true);
            }
        }
    });
    server.setConnectors(new Connector[]{connector});
    server.start();

    httpClient.setFollowRedirects(false);
    httpClient.getRequestListeners().add(JettyClientMetrics
            .builder(registry, result -> result.getRequest().getURI().getPath()).build());

    httpClient.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {
        @Override
        public void lifeCycleStopped(LifeCycle event) {
            singleRequestLatch.countDown();
        }
    });

    httpClient.start();

}
 
Example #5
Source File: JettyConnectionMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void contributesServerConnectorMetrics() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + connector.getLocalPort());
    post.setEntity(new StringEntity("123456"));

    try (CloseableHttpResponse ignored = client.execute(post)) {
        try (CloseableHttpResponse ignored2 = client.execute(post)) {
            assertThat(registry.get("jetty.connections.current").gauge().value()).isEqualTo(2.0);
            assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
        }
    }

    CountDownLatch latch = new CountDownLatch(1);
    connector.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {
        @Override
        public void lifeCycleStopped(LifeCycle event) {
            latch.countDown();
        }
    });
    // Convenient way to get Jetty to flush its connections, which is required to update the sent/received bytes metrics
    server.stop();

    assertTrue(latch.await(10, SECONDS));
    assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
    assertThat(registry.get("jetty.connections.request").tag("type", "server").timer().count())
            .isEqualTo(2);
    assertThat(registry.get("jetty.connections.bytes.in").summary().totalAmount()).isGreaterThan(1);
}
 
Example #6
Source File: JettyConnectionMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void contributesClientConnectorMetrics() throws Exception {
    HttpClient httpClient = new HttpClient();
    httpClient.setFollowRedirects(false);
    httpClient.addBean(new JettyConnectionMetrics(registry));

    CountDownLatch latch = new CountDownLatch(1);
    httpClient.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {
        @Override
        public void lifeCycleStopped(LifeCycle event) {
            latch.countDown();
        }
    });

    httpClient.start();

    Request post = httpClient.POST("http://localhost:" + connector.getLocalPort());
    post.content(new StringContentProvider("123456"));
    post.send();
    httpClient.stop();

    assertTrue(latch.await(10, SECONDS));
    assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(1.0);
    assertThat(registry.get("jetty.connections.request").tag("type", "client").timer().count())
            .isEqualTo(1);
    assertThat(registry.get("jetty.connections.bytes.out").summary().totalAmount()).isGreaterThan(1);
}
 
Example #7
Source File: MockOldStyleApplication.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception
{
    LifeCycle.Listener listener = new AbstractLifeCycle.AbstractLifeCycleListener()
    {
        @Override
        public void lifeCycleStarted(LifeCycle event)
        {
            System.out.println("Starting...");
            startedLatch.countDown();
        }
    };
    environment.lifecycle().addLifeCycleListener(listener);
}
 
Example #8
Source File: S3ProxyRule.java    From s3proxy with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    logger.debug("S3 proxy is starting");
    s3Proxy.start();
    while (!s3Proxy.getState().equals(AbstractLifeCycle.STARTED)) {
        Thread.sleep(10);
    }
    endpointUri = URI.create(String.format(endpointFormat, LOCALHOST,
            s3Proxy.getPort()));
    logger.debug("S3 proxy is running");
}
 
Example #9
Source File: TestUtils.java    From s3proxy with Apache License 2.0 4 votes vote down vote up
static S3ProxyLaunchInfo startS3Proxy(String configFile) throws Exception {
    S3ProxyLaunchInfo info = new S3ProxyLaunchInfo();

    try (InputStream is = Resources.asByteSource(Resources.getResource(
            configFile)).openStream()) {
        info.getProperties().load(is);
    }

    String provider = info.getProperties().getProperty(
            Constants.PROPERTY_PROVIDER);
    String identity = info.getProperties().getProperty(
            Constants.PROPERTY_IDENTITY);
    String credential = info.getProperties().getProperty(
            Constants.PROPERTY_CREDENTIAL);
    if (provider.equals("google-cloud-storage")) {
        File credentialFile = new File(credential);
        if (credentialFile.exists()) {
            credential = Files.asCharSource(credentialFile,
                    StandardCharsets.UTF_8).read();
        }
        info.getProperties().remove(Constants.PROPERTY_CREDENTIAL);
    }
    String endpoint = info.getProperties().getProperty(
            Constants.PROPERTY_ENDPOINT);

    ContextBuilder builder = ContextBuilder
            .newBuilder(provider)
            .credentials(identity, credential)
            .modules(ImmutableList.<Module>of(new SLF4JLoggingModule()))
            .overrides(info.getProperties());
    if (!Strings.isNullOrEmpty(endpoint)) {
        builder.endpoint(endpoint);
    }
    BlobStoreContext context = builder.build(BlobStoreContext.class);
    info.blobStore = context.getBlobStore();

    S3Proxy.Builder s3ProxyBuilder = S3Proxy.Builder.fromProperties(
            info.getProperties());
    s3ProxyBuilder.blobStore(info.blobStore);
    info.endpoint = s3ProxyBuilder.getEndpoint();
    info.secureEndpoint = s3ProxyBuilder.getSecureEndpoint();
    info.s3Identity = s3ProxyBuilder.getIdentity();
    info.s3Credential = s3ProxyBuilder.getCredential();
    info.servicePath = s3ProxyBuilder.getServicePath();
    info.getProperties().setProperty(Constants.PROPERTY_USER_AGENT,
            String.format("s3proxy/%s jclouds/%s java/%s",
                    TestUtils.class.getPackage().getImplementationVersion(),
                    JcloudsVersion.get(),
                    System.getProperty("java.version")));

    // resolve relative path for tests
    String keyStorePath = info.getProperties().getProperty(
            S3ProxyConstants.PROPERTY_KEYSTORE_PATH);
    String keyStorePassword = info.getProperties().getProperty(
            S3ProxyConstants.PROPERTY_KEYSTORE_PASSWORD);
    if (keyStorePath != null || keyStorePassword != null) {
        s3ProxyBuilder.keyStore(
                Resources.getResource(keyStorePath).toString(),
                keyStorePassword);
    }
    info.s3Proxy = s3ProxyBuilder.build();
    info.s3Proxy.start();
    while (!info.s3Proxy.getState().equals(AbstractLifeCycle.STARTED)) {
        Thread.sleep(1);
    }

    // reset endpoint to handle zero port
    info.endpoint = new URI(info.endpoint.getScheme(),
            info.endpoint.getUserInfo(), info.endpoint.getHost(),
            info.s3Proxy.getPort(), info.endpoint.getPath(),
            info.endpoint.getQuery(), info.endpoint.getFragment());
    if (info.secureEndpoint != null) {
        info.secureEndpoint = new URI(info.secureEndpoint.getScheme(),
                info.secureEndpoint.getUserInfo(),
                info.secureEndpoint.getHost(),
                info.s3Proxy.getSecurePort(),
                info.secureEndpoint.getPath(),
                info.secureEndpoint.getQuery(),
                info.secureEndpoint.getFragment());
    }

    return info;
}