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

The following examples show how to use org.eclipse.jetty.util.component.LifeCycle. 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: ClientStarter.java    From jetty-web-sockets-jsr356 with Apache License 2.0 6 votes vote down vote up
public static void main( final String[] args ) throws Exception {
	final String client = UUID.randomUUID().toString().substring( 0, 8 );
	
	final WebSocketContainer container = ContainerProvider.getWebSocketContainer();				
	final String uri = "ws://localhost:8080/broadcast";		
	
	try( Session session = container.connectToServer( BroadcastClientEndpoint.class, URI.create( uri ) ) ) {
		for( int i = 1; i <= 10; ++i ) {
			session.getBasicRemote().sendObject( new Message( client, "Message #" + i ) );
			Thread.sleep( 1000 );
		}
	}
	
	// JSR-356 has no concept of Container lifecycle.
	// (This is an oversight on the spec's part)
	// This stops the lifecycle of the Client WebSocketContainer
	if( container instanceof LifeCycle ) {
	    ( ( LifeCycle )container ).stop();
	}
}
 
Example #2
Source File: JettyResourceFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	String name = this.threadPrefix + "@" + Integer.toHexString(hashCode());
	if (this.executor == null) {
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setName(name);
		this.executor = threadPool;
	}
	if (this.byteBufferPool == null) {
		this.byteBufferPool = new MappedByteBufferPool(2048,
				this.executor instanceof ThreadPool.SizedThreadPool
						? ((ThreadPool.SizedThreadPool) executor).getMaxThreads() / 2
						: ProcessorUtils.availableProcessors() * 2);
	}
	if (this.scheduler == null) {
		this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false);
	}

	if (this.executor instanceof LifeCycle) {
		((LifeCycle)this.executor).start();
	}
	this.scheduler.start();
}
 
Example #3
Source File: DeploymentCheck.java    From jetty-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void lifeCycleStarted(LifeCycle bean) {
  if (bean instanceof Server) {
    Server server = (Server)bean;
    Connector[] connectors = server.getConnectors();
    if (connectors == null || connectors.length == 0) {
      server.dumpStdErr();
      throw new IllegalStateException("No Connector");
    } else if (!Arrays.stream(connectors).allMatch(Connector::isStarted)) {
      server.dumpStdErr();
      throw new IllegalStateException("Connector not started");
    }
    ContextHandler context = server.getChildHandlerByClass(ContextHandler.class);
    if (context == null || !context.isAvailable()) {
      server.dumpStdErr();
      throw new IllegalStateException("No Available Context");
    }
  }
}
 
Example #4
Source File: JettyResourceFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	String name = this.threadPrefix + "@" + Integer.toHexString(hashCode());
	if (this.executor == null) {
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setName(name);
		this.executor = threadPool;
	}
	if (this.byteBufferPool == null) {
		this.byteBufferPool = new MappedByteBufferPool(2048,
				this.executor instanceof ThreadPool.SizedThreadPool
						? ((ThreadPool.SizedThreadPool) executor).getMaxThreads() / 2
						: ProcessorUtils.availableProcessors() * 2);
	}
	if (this.scheduler == null) {
		this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false);
	}

	if (this.executor instanceof LifeCycle) {
		((LifeCycle)this.executor).start();
	}
	this.scheduler.start();
}
 
Example #5
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 #6
Source File: JettyServer.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public void stopComponents() throws Exception {
  Collections.reverse(components);

  // if Jetty thread is still waiting for a component to start, this should unblock it
  interrupt();

  for (LifeCycle component : components) {
    if (component.isRunning()) {
      log.info("Stopping: {}", component);
      component.stop();
    }
  }

  components.clear();
  stopped.await();
}
 
Example #7
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 #8
Source File: JettyServiceConfig.java    From armeria with Apache License 2.0 6 votes vote down vote up
JettyServiceConfig(@Nullable String hostname,
                   @Nullable Boolean dumpAfterStart, @Nullable Boolean dumpBeforeStop,
                   @Nullable Long stopTimeoutMillis,
                   @Nullable Handler handler, @Nullable RequestLog requestLog,
                   @Nullable Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory,
                   Map<String, Object> attrs, List<Bean> beans, List<HandlerWrapper> handlerWrappers,
                   List<Listener> eventListeners, List<LifeCycle.Listener> lifeCycleListeners,
                   List<Consumer<? super Server>> configurators) {

    this.hostname = hostname;
    this.dumpAfterStart = dumpAfterStart;
    this.dumpBeforeStop = dumpBeforeStop;
    this.stopTimeoutMillis = stopTimeoutMillis;
    this.handler = handler;
    this.requestLog = requestLog;
    this.sessionIdManagerFactory = sessionIdManagerFactory;
    this.attrs = Collections.unmodifiableMap(attrs);
    this.beans = Collections.unmodifiableList(beans);
    this.handlerWrappers = Collections.unmodifiableList(handlerWrappers);
    this.eventListeners = Collections.unmodifiableList(eventListeners);
    this.lifeCycleListeners = Collections.unmodifiableList(lifeCycleListeners);
    this.configurators = Collections.unmodifiableList(configurators);
}
 
Example #9
Source File: JettyServiceConfig.java    From armeria with Apache License 2.0 6 votes vote down vote up
static String toString(
        Object holder, @Nullable String hostname, @Nullable Boolean dumpAfterStart,
        @Nullable Boolean dumpBeforeStop, @Nullable Long stopTimeout,
        @Nullable Handler handler, @Nullable RequestLog requestLog,
        @Nullable Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory,
        Map<String, Object> attrs, List<Bean> beans, List<HandlerWrapper> handlerWrappers,
        List<Listener> eventListeners, List<LifeCycle.Listener> lifeCycleListeners,
        List<Consumer<? super Server>> configurators) {

    return MoreObjects.toStringHelper(holder)
                      .add("hostname", hostname)
                      .add("dumpAfterStart", dumpAfterStart)
                      .add("dumpBeforeStop", dumpBeforeStop)
                      .add("stopTimeoutMillis", stopTimeout)
                      .add("handler", handler)
                      .add("requestLog", requestLog)
                      .add("sessionIdManagerFactory", sessionIdManagerFactory)
                      .add("attrs", attrs)
                      .add("beans", beans)
                      .add("handlerWrappers", handlerWrappers)
                      .add("eventListeners", eventListeners)
                      .add("lifeCycleListeners", lifeCycleListeners)
                      .add("configurators", configurators)
                      .toString();
}
 
Example #10
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 #11
Source File: WebSocketClient.java    From product-cep with Apache License 2.0 6 votes vote down vote up
public void send(String url, String message) {
    receivedMessage = null;
    URI uri = URI.create(url);

    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            // Attempt Connect
            Session session = container.connectToServer(EventSocketClient.class, uri);
            // Send a message
            session.getBasicRemote().sendText(message);
            // Close session
            session.close();
        } finally {
            // Force lifecycle stop when done with container.
            // This is to free up threads and resources that the
            // JSR-356 container allocates. But unfortunately
            // the JSR-356 spec does not handle lifecycles (yet)
            if (container instanceof LifeCycle) {
                ((LifeCycle) container).stop();
            }
        }
    } catch (Throwable t) {
        log.error(t);
    }
}
 
Example #12
Source File: WebSocketClient.java    From product-cep with Apache License 2.0 6 votes vote down vote up
public void connect(String url) {
    URI uri = URI.create(url);

    try {
        container = ContainerProvider.getWebSocketContainer();
        // Attempt Connect
        session = container.connectToServer(EventSocketClient.class, uri);

        if (session == null) {
            throw new RuntimeException("Cannot connect to url :" + url);
        }
    } catch (Throwable t) {
        log.error(t);
        if (container != null) {
            if (container instanceof LifeCycle) {
                try {
                    ((LifeCycle) container).stop();
                } catch (Exception e) {
                    log.error(e);
                }
            }
        }
    }
}
 
Example #13
Source File: WebSocketClient.java    From product-cep with Apache License 2.0 6 votes vote down vote up
public void connect(String url) {
    URI uri = URI.create(url);

    try {
        container = ContainerProvider.getWebSocketContainer();
        // Attempt Connect
        session = container.connectToServer(EventSocketClient.class, uri);

        if (session == null) {
            throw new RuntimeException("Cannot connect to url :" + url);
        }
    } catch (Throwable t) {
        log.error(t);
        if (container != null) {
            if (container instanceof LifeCycle) {
                try {
                    ((LifeCycle) container).stop();
                } catch (Exception e) {
                    log.error(e);
                }
            }
        }
    }
}
 
Example #14
Source File: WebSocketClient.java    From product-cep with Apache License 2.0 6 votes vote down vote up
public void send(String message) {

        try {
            // Send a message

            session.getBasicRemote().sendText(message);

        } catch (Throwable t) {
            log.error(t);
            if (container != null) {
                if (container instanceof LifeCycle) {
                    try {
                        ((LifeCycle) container).stop();
                    } catch (Exception e) {
                        log.error(e);
                    }
                }
            }
        }
    }
 
Example #15
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 #16
Source File: ManagerFactory.java    From passopolis-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void lifeCycleStopping(LifeCycle event) {
  executor.shutdown();
  try {
    boolean terminated = executor.awaitTermination(1, TimeUnit.SECONDS);
    if (!terminated) {
      logger.warn("timed out waiting for scheduled task to stop");
    }
  } catch (InterruptedException e) {
    logger.warn("interrupted while waiting for scheduled task", e);
  }
}
 
Example #17
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 #18
Source File: SpnegoLoginServiceWithAuthServiceLifecycle.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void doStop() throws Exception {
  super.doStop();
  if (_authorizationService instanceof LifeCycle) {
    ((LifeCycle) _authorizationService).stop();
  }
}
 
Example #19
Source File: SpnegoLoginServiceWithAuthServiceLifecycle.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
  if (_authorizationService instanceof LifeCycle) {
    ((LifeCycle) _authorizationService).start();
  }
  super.doStart();
}
 
Example #20
Source File: JwtLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void doStop() throws Exception {
  if (_authorizationService instanceof LifeCycle) {
    ((LifeCycle) _authorizationService).stop();
  }
  super.doStop();
}
 
Example #21
Source File: WebSocketClient.java    From product-cep with Apache License 2.0 5 votes vote down vote up
public void receive(String url, int retryCount) {

        receivedMessage = null;
        final URI uri = URI.create(url);
        final int tryCount = retryCount;

        new Thread(new Runnable() {
            @Override

            public void run() {
                try {

                    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
                    try {
                        // Attempt Connect
                        Session session = container.connectToServer(EventSocketClient.class, uri);

                        int count = 0;
                        while (count < tryCount && receivedMessage == null) {
                            log.info("Waiting for the sever to send message");
                            Thread.sleep(1000);
                        }

                        session.close();
                    } finally {
                        // Force lifecycle stop when done with container.
                        // This is to free up threads and resources that the
                        // JSR-356 container allocates. But unfortunately
                        // the JSR-356 spec does not handle lifecycles (yet)
                        if (container instanceof LifeCycle) {
                            ((LifeCycle) container).stop();
                        }
                    }
                } catch (Throwable t) {
                    log.error(t);
                }
            }
        }).start();

    }
 
Example #22
Source File: JwtLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
  super.doStart();
  // The authorization service might want to start a connection or access a file
  if (_authorizationService instanceof LifeCycle) {
    ((LifeCycle) _authorizationService).start();
  }
}
 
Example #23
Source File: WebSocketClient.java    From product-cep with Apache License 2.0 5 votes vote down vote up
public void stop() {

        if (container != null) {
            if (container instanceof LifeCycle) {
                try {
                    ((LifeCycle) container).stop();
                } catch (Exception e) {
                    log.error(e);
                }
            }
        }
    }
 
Example #24
Source File: TrustedProxyLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void doStop() throws Exception {
  super.doStop();
  _delegateSpnegoLoginService.stop();
  if (_endUserAuthorizer instanceof LifeCycle) {
    ((LifeCycle) _endUserAuthorizer).stop();
  }
}
 
Example #25
Source File: TrustedProxyLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
  if (_endUserAuthorizer instanceof LifeCycle) {
    ((LifeCycle) _endUserAuthorizer).start();
  }
  _delegateSpnegoLoginService.start();
  super.doStart();
}
 
Example #26
Source File: WebSocketClient.java    From product-cep with Apache License 2.0 5 votes vote down vote up
public void stop() {

        if (container != null) {
            if (container instanceof LifeCycle) {
                try {
                    ((LifeCycle) container).stop();
                } catch (Exception e) {
                    log.error(e);
                }
            }
        }
    }
 
Example #27
Source File: AssetsContextHandlerInitializer.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public void lifeCycleStarted(LifeCycle event) {
    try {
        assetsContextHandler.init(webAppContext);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: SingularityTestModule.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
  // Start all the managed instances in dropwizard.
  Set<LifeCycle> managedObjects = ImmutableSet.copyOf(
    environment.lifecycle().getManagedObjects()
  );
  for (LifeCycle managed : managedObjects) {
    managed.start();
  }
}
 
Example #29
Source File: SingularityTestModule.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public void stop() throws Exception {
  ImmutableSet<LifeCycle> managedObjects = ImmutableSet.copyOf(
    environment.lifecycle().getManagedObjects()
  );
  for (LifeCycle managed : Lists.reverse(managedObjects.asList())) {
    managed.stop();
  }
}
 
Example #30
Source File: ODataTestServer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public ODataTestServer(Options... options) throws Exception {
    super();
    this.optionsList = Arrays.asList(options);

    SSLContext sslContext = null;
    String userName = null;

    if (optionsList.contains(Options.SSL)) {
        sslContext = createServerSSLContext();
    }

    if (optionsList.contains(Options.AUTH_USER)) {
        userName = USER;
    }

    if (optionsList.contains(Options.HTTP_PORT)) {
        httpPort = extractPort(HTTP_PROPERTY);
    }

    if (optionsList.contains(Options.HTTPS_PORT)) {
        httpsPort = extractPort(HTTPS_PROPERTY);
    }

    this.addLifeCycleListener(new AbstractLifeCycleListener() {

        @Override
        public void lifeCycleStopped(LifeCycle event) {
            // Ensure storage is destroyed on stopping
            Storage.dispose();
        }
    });

    initServer(sslContext, userName);
}