Java Code Examples for org.eclipse.jetty.server.Server

The following examples show how to use org.eclipse.jetty.server.Server. 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: heroic   Author: spotify   File: HttpServer.java    License: Apache License 2.0 6 votes vote down vote up
private AsyncFuture<Void> stop() {
    return async.call(() -> {
        final Server s;

        synchronized (lock) {
            if (server == null) {
                throw new IllegalStateException("Server has not been started");
            }

            s = server;
            server = null;
        }

        log.info("Stopping http server");
        s.stop();
        s.join();
        return null;
    });
}
 
Example #2
Source Project: homework_tester   Author: vitaly-chibrikov   File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

    context.addServlet(new ServletHolder(new WebSocketChatServlet()), "/chat");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setResourceBase("public_html");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, context});
    server.setHandler(handlers);

    server.start();
    System.out.println("Server started!");
    server.join();
}
 
Example #3
Source Project: AppStash   Author: zutherb   File: JettyStart.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) {
    if (args.length < 1) {
        System.out.println("JettyStart <httpport>");
        return;
    }

    Validate.notNull(args[0], "A Port is needed to start the server");

    Server server = new Server(Integer.valueOf(args[0]));
    WebAppContext context = new WebAppContext();
    context.setContextPath("/shop");
    context.setResourceBase("src/main/webapp/");
    context.setDescriptor("src/main/webapp/WEB-INF/web.xml");
    context.setParentLoaderPriority(true);
    server.setHandler(context);

    try {
        LOGGER.info("JETTY SERVER STARTING NOW ...");
        server.start();
        server.join();
    } catch (Exception e) {
        LOGGER.error("Jetty Server could not be started", e);
        System.exit(100);
    }
}
 
Example #4
Source Project: dapeng-soa   Author: dapeng-soa   File: ApiWebSite.java    License: Apache License 2.0 6 votes vote down vote up
public static Server createServer(int port) throws MalformedURLException, URISyntaxException {
    Server server = new Server();
    server.setStopAtShutdown(true);

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    connector.setReuseAddress(true);

    server.setConnectors(new Connector[]{connector});

    WebAppContext webContext = new WebAppContext("webapp", CONTEXT);
    webContext.setBaseResource(Resource.newResource(new URL(ApiWebSite.class.getResource("/webapp/WEB-INF"), ".")));
    webContext.setClassLoader(ApiWebSite.class.getClassLoader());

    server.setHandler(webContext);

    return server;
}
 
Example #5
Source Project: AisAbnormal   Author: dma-ais   File: WebServer.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public WebServer(
        int port,
        String repositoryName,
        String pathToEventDatabase,
        String eventRepositoryType,
        String eventDataDbHost,
        Integer eventDataDbPort,
        String eventDataDbName,
        String eventDataDbUsername,
        String eventDataDbPassword
    ) {
    server = new Server(port);
    this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    this.repositoryName = repositoryName;
    this.pathToEventDatabase = pathToEventDatabase;
    this.eventRepositoryType = eventRepositoryType;
    this.eventDataDbHost = eventDataDbHost;
    this.eventDataDbPort = eventDataDbPort;
    this.eventDataDbName = eventDataDbName;
    this.eventDataDbUsername = eventDataDbUsername;
    this.eventDataDbPassword = eventDataDbPassword;
}
 
Example #6
Source Project: bootique   Author: bootique   File: BQInternalWebServerTestFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Server provideServer(Environment env, ShutdownManager shutdownManager) {
    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(12025);
    server.addConnector(connector);

    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");

    DefaultServlet servlet = new DefaultServlet();

    ServletHolder holder = new ServletHolder(servlet);
    handler.addServlet(holder, "/*");
    handler.setResourceBase(env.getProperty("bq.internaljetty.base"));

    server.setHandler(handler);

    shutdownManager.addShutdownHook(() -> {
        server.stop();
    });

    return server;
}
 
Example #7
Source Project: phoebus   Author: ControlSystemStudio   File: EngineWebServer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public EngineWebServer(final int port)
{
    // Configure Jetty to use java.util.logging, and don't announce that it's doing that
    System.setProperty("org.eclipse.jetty.util.log.announce", "false");
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog");

    server = new Server(port);

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    // Our servlets
    context.addServlet(MainServlet.class, "/main/*");
    context.addServlet(DisconnectedServlet.class, "/disconnected/*");
    context.addServlet(GroupsServlet.class, "/groups/*");
    context.addServlet(GroupServlet.class, "/group/*");
    context.addServlet(ChannelServlet.class, "/channel/*");
    context.addServlet(RestartServlet.class, "/restart/*");
    context.addServlet(StopServlet.class, "/stop/*");

    // Serve static files from webroot to "/"
    context.setContextPath("/");
    context.setResourceBase(EngineWebServer.class.getResource("/webroot").toExternalForm());
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);
}
 
Example #8
Source Project: oxygen   Author: justlive1   File: JettyWebServer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void listen(int port) {
  JettyConf jettyConf = ConfigFactory.load(JettyConf.class);
  this.port = port;
  this.contextPath = WebConfigKeys.SERVER_CONTEXT_PATH.getValue();

  server = new Server();

  ServerConnector connector = new ServerConnector(server);
  server.addConnector(connector);
  configConnector(connector, jettyConf);

  WebAppContext webapp = new WebAppContext();
  server.setHandler(webapp);
  try {
    configWebapp(webapp, jettyConf);
    server.start();
  } catch (Exception e) {
    throw Exceptions.wrap(e);
  }
}
 
Example #9
Source Project: wisp   Author: warlock-china   File: ServerMain.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        Server jettyServer = new Server(8067);
        jettyServer.setHandler(context);

        ServletHolder jerseyServlet = context.addServlet(
                org.glassfish.jersey.servlet.ServletContainer.class, "/*");
        jerseyServlet.setInitOrder(0);

        // Tells the Jersey Servlet which REST service/class to load.
        jerseyServlet.setInitParameter(
                "jersey.config.server.provider.classnames",
                EntryPointTestHandler.class.getCanonicalName());

        try {
            jettyServer.start();
            jettyServer.join();
        } finally {
            jettyServer.destroy();
        }
    }
 
Example #10
Source Project: qmq   Author: qunarcorp   File: Bootstrap.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    DynamicConfig config = DynamicConfigLoader.load("broker.properties");
    ServerWrapper wrapper = new ServerWrapper(config);
    Runtime.getRuntime().addShutdownHook(new Thread(wrapper::destroy));
    wrapper.start(true);

    if (wrapper.isSlave()) {
        final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setResourceBase(System.getProperty("java.io.tmpdir"));
        final QueryMessageServlet servlet = new QueryMessageServlet(config, wrapper.getStorage());

        ServletHolder servletHolder = new ServletHolder(servlet);
        servletHolder.setAsyncSupported(true);
        context.addServlet(servletHolder, "/api/broker/message");

        final int port = config.getInt("slave.server.http.port", 8080);
        final Server server = new Server(port);
        server.setHandler(context);
        server.start();
        server.join();
    }
}
 
Example #11
Source Project: lucene-solr   Author: apache   File: HttpServer2.java    License: Apache License 2.0 6 votes vote down vote up
private ServerConnector createHttpChannelConnector(
    Server server, HttpConfiguration httpConfig) {
  ServerConnector conn = new ServerConnector(server,
      conf.getInt(HTTP_ACCEPTOR_COUNT_KEY, HTTP_ACCEPTOR_COUNT_DEFAULT),
      conf.getInt(HTTP_SELECTOR_COUNT_KEY, HTTP_SELECTOR_COUNT_DEFAULT));
  ConnectionFactory connFactory = new HttpConnectionFactory(httpConfig);
  conn.addConnectionFactory(connFactory);
  if(Shell.WINDOWS) {
    // result of setting the SO_REUSEADDR flag is different on Windows
    // http://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
    // without this 2 NN's can start on the same machine and listen on
    // the same port with indeterminate routing of incoming requests to them
    conn.setReuseAddress(false);
  }
  return conn;
}
 
Example #12
Source Project: athenz   Author: yahoo   File: AthenzJettyContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInitContainerInvalidHTTPSPort() {
    
    System.setProperty(AthenzConsts.ATHENZ_PROP_HTTP_PORT, "4080");
    System.setProperty(AthenzConsts.ATHENZ_PROP_HTTPS_PORT, "-10");

    AthenzJettyContainer container = AthenzJettyContainer.createJettyContainer();
    assertNotNull(container);
    
    Server server = container.getServer();
    Connector[] connectors = server.getConnectors();
    assertEquals(connectors.length, 2);
    
    assertTrue(connectors[0].getProtocols().contains("http/1.1"));
    
    assertTrue(connectors[1].getProtocols().contains("http/1.1"));
    assertTrue(connectors[1].getProtocols().contains("ssl"));
}
 
Example #13
Source Project: athenz   Author: yahoo   File: AthenzJettyContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSSLContextObjectNoTrustStore() {
    
    AthenzJettyContainer container = new AthenzJettyContainer();
    
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PATH, "file:///tmp/keystore");
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_TYPE, "PKCS12");
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PASSWORD, "pass123");
    System.setProperty(AthenzConsts.ATHENZ_PROP_EXCLUDED_CIPHER_SUITES, DEFAULT_EXCLUDED_CIPHERS);
    System.setProperty(AthenzConsts.ATHENZ_PROP_INCLUDED_CIPHER_SUITES, DEFAULT_INCLUDED_CIPHERS);
    System.setProperty(AthenzConsts.ATHENZ_PROP_EXCLUDED_PROTOCOLS, AthenzJettyContainer.ATHENZ_DEFAULT_EXCLUDED_PROTOCOLS);
    
    SslContextFactory.Server sslContextFactory = container.createSSLContextObject(false);
    assertNotNull(sslContextFactory);
    assertEquals(sslContextFactory.getKeyStorePath(), "file:///tmp/keystore");
    assertEquals(sslContextFactory.getKeyStoreType(), "PKCS12");
    assertNull(sslContextFactory.getTrustStore());
    // store type always defaults to PKCS12
    assertEquals(sslContextFactory.getTrustStoreType(), "PKCS12");
    assertEquals(sslContextFactory.getExcludeCipherSuites(), DEFAULT_EXCLUDED_CIPHERS.split(","));
    assertEquals(sslContextFactory.getIncludeCipherSuites(), DEFAULT_INCLUDED_CIPHERS.split(","));
    assertEquals(sslContextFactory.getExcludeProtocols(), AthenzJettyContainer.ATHENZ_DEFAULT_EXCLUDED_PROTOCOLS.split(","));
}
 
Example #14
Source Project: git-as-svn   Author: bozaro   File: WebServer.java    License: GNU General Public License v2.0 6 votes vote down vote up
public WebServer(@NotNull SharedContext context, @NotNull Server server, @Nullable URL baseUrl, @NotNull EncryptionFactory tokenFactory) throws URISyntaxException {
  this.context = context;
  this.server = server;
  this.baseUrl = baseUrl == null ? null : baseUrl.toURI();
  this.tokenFactory = tokenFactory;
  final ServletContextHandler contextHandler = new ServletContextHandler();
  contextHandler.setContextPath("/");
  handler = contextHandler.getServletHandler();

  final RequestLogHandler logHandler = new RequestLogHandler();
  logHandler.setRequestLog((request, response) -> {
    final User user = (User) request.getAttribute(User.class.getName());
    final String username = (user == null || user.isAnonymous()) ? "" : user.getUsername();
    log.info("{}:{} - {} - \"{} {}\" {} {}", request.getRemoteHost(), request.getRemotePort(), username, request.getMethod(), request.getHttpURI(), response.getStatus(), response.getReason());
  });

  final HandlerCollection handlers = new HandlerCollection();
  handlers.addHandler(contextHandler);
  handlers.addHandler(logHandler);
  server.setHandler(handlers);
}
 
Example #15
Source Project: xdocreport.samples   Author: opensagres   File: EmbeddedServer.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
    throws Exception
{
    Server server = new Server( 8080 );

    WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );

    ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
    webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );

    server.setHandler( handlers );


    server.start();
    server.join();
}
 
Example #16
Source Project: knox   Author: apache   File: WebsocketBackendUrlTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  WebsocketEchoTestBase.setUpBeforeClass();

  backendServer = new Server();
  ServerConnector connector = new ServerConnector(backendServer);
  backendServer.addConnector(connector);

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
  backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/testpart/", host, port));
  WebsocketEchoTestBase.setupGatewayConfig(backendServerUri.toString());
}
 
Example #17
Source Project: XRTB   Author: benmfaul   File: Zippy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Starts the JETTY server
 */

 public void run() {
	Server server = new Server(port);
	Handler handler = new Handler();

	try {
		SessionHandler sh = new SessionHandler(); // org.eclipse.jetty.server.session.SessionHandler
		sh.addEventListener(new CustomListener());
		sh.setHandler(handler);
		server.setHandler(sh);
		server.start();
		server.join();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #18
Source Project: heroic   Author: spotify   File: JettyServerConnector.java    License: Apache License 2.0 6 votes vote down vote up
public ServerConnector setup(final Server server, final InetSocketAddress address) {
    final HttpConfiguration config = this.config.build();

    final ConnectionFactory[] factories = this.factories
        .stream()
        .map(f -> f.setup(config))
        .toArray(size -> new ConnectionFactory[size]);

    final ServerConnector c = new ServerConnector(server, factories);

    c.setHost(this.address.map(a -> a.getHostString()).orElseGet(address::getHostString));
    c.setPort(this.address.map(a -> a.getPort()).orElseGet(address::getPort));

    defaultProtocol.ifPresent(c::setDefaultProtocol);
    return c;
}
 
Example #19
Source Project: Jax-RS-Performance-Comparison   Author: smallnest   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String host = "0.0.0.0";
    int port = 8080;
    if (args.length > 0) {
        host = args[0];
    }
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }

    final Server server = startServer(host, port);
    System.in.read();
    server.stop();
}
 
Example #20
Source Project: java-slack-sdk   Author: slackapi   File: SlackAppServer.java    License: MIT License 5 votes vote down vote up
private static void removeServerHeader(Server server) {
    // https://stackoverflow.com/a/15675075/840108
    for (Connector y : server.getConnectors()) {
        for (ConnectionFactory x : y.getConnectionFactories()) {
            if (x instanceof HttpConnectionFactory) {
                ((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(false);
            }
        }
    }
}
 
Example #21
Source Project: zsync4j   Author: salesforce   File: BaseJettyTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Before
public void startJetty() throws Exception {
  this.server = new Server(0);
  ServletContextHandler servletContextHandler = new ServletContextHandler();
  servletContextHandler.setContextPath("/");
  servletContextHandler.setBaseResource(Resource.newClassPathResource(WEB_ROOT));
  ServletHolder defaultServletHolder = new ServletHolder("default", DefaultServlet.class);
  defaultServletHolder.setInitParameter("acceptRanges", "true");
  servletContextHandler.addServlet(defaultServletHolder, "/");
  this.server.setHandler(servletContextHandler);
  this.server.start();
  this.port = ((ServerConnector) this.server.getConnectors()[0]).getLocalPort();
}
 
Example #22
Source Project: cxf   Author: apache   File: BookCxfContinuationServlet3Server.java    License: Apache License 2.0 5 votes vote down vote up
private Server httpServer(CXFNonSpringServlet cxf) {
    Server server = new Server(Integer.parseInt(PORT));
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(new ServletHolder(cxf), "/*");
    return server;
}
 
Example #23
Source Project: distributedlog   Author: twitter   File: ServletReporter.java    License: Apache License 2.0 5 votes vote down vote up
public ServletReporter(MetricRegistry metricRegistry,
                       HealthCheckRegistry healthCheckRegistry,
                       int port) {
    this.metricRegistry = metricRegistry;
    this.healthCheckRegistry = healthCheckRegistry;
    this.port = port;
    this.jettyServer = new Server(port);
}
 
Example #24
Source Project: brooklyn-server   Author: apache   File: MultiSessionAttributeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
protected SessionHandler findPreferredBundleHandler(Session localSession, Server server, Handler[] handlers) {
    if (PREFERRED_SYMBOLIC_NAME==null) return null;

    SessionHandler preferredHandler = null;

    if (handlers != null) {
        for (Handler handler: handlers) {
            SessionHandler sh = (SessionHandler) handler;
            ContextHandler.Context ctx = getContext(sh);
            if (ctx!=null) {
                BundleContext bundle = (BundleContext) ctx.getAttribute("osgi-bundlecontext");
                if (bundle!=null) {
                    if (PREFERRED_SYMBOLIC_NAME.equals(bundle.getBundle().getSymbolicName())) {
                        if (preferredHandler==null) {
                            preferredHandler = sh;
                            server.setAttribute(KEY_PREFERRED_SESSION_HANDLER_INSTANCE, sh);
                            log.trace("Recording "+info(sh)+" as server-wide preferred session handler");
                        } else {
                            log.warn("Multiple preferred session handlers detected; keeping "+info(preferredHandler)+", ignoring "+info(sh));
                        }
                    }
                }
            }
        }
    }
    if (preferredHandler==null) {
        log.warn("Did not find handler in bundle "+PREFERRED_SYMBOLIC_NAME+"; not using server-wide handler; check whether bundle is installed!");
    }
    return preferredHandler;
}
 
Example #25
Source Project: knox   Author: apache   File: GatewayPortMappingConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckPortConflict()
    throws IOException, NoSuchFieldException, IllegalAccessException {
  /* Check port conflict with default port */
  exception.expect(IOException.class);
  exception.expectMessage(String.format(Locale.ROOT,
      " Port %d used by topology %s is used by other topology, ports for topologies (if defined) have to be unique. ",
      huronPort, "eerie"));

  GatewayServer gatewayServer = new GatewayServer(gatewayConfig);

  Server mockedJetty = EasyMock.createNiceMock(Server.class);

  ServerConnector mockConnector = EasyMock.createNiceMock(ServerConnector.class);
  EasyMock.expect(mockConnector.getPort()).andReturn(huronPort).anyTimes();
  EasyMock.replay(mockConnector);

  ServerConnector[] mockConnectorArray = new ServerConnector[] {mockConnector};

  EasyMock.expect(mockedJetty.getConnectors()).andReturn(mockConnectorArray).anyTimes();

  EasyMock.replay(mockedJetty);

  Field field = gatewayServer.getClass().getDeclaredField("jetty");
  field.setAccessible(true);
  field.set(gatewayServer, mockedJetty);

  gatewayServer.checkPortConflict(huronPort, "eerie", gatewayConfig);
}
 
Example #26
Source Project: hapi-fhir-jpaserver-starter   Author: hapifhir   File: MultitenantServerR4IT.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  String path = Paths.get("").toAbsolutePath().toString();

  ourLog.info("Project base path is: {}", path);

  ourServer = new Server(0);

  WebAppContext webAppContext = new WebAppContext();
  webAppContext.setContextPath("/hapi-fhir-jpaserver");
  webAppContext.setDisplayName("HAPI FHIR");
  webAppContext.setDescriptor(path + "/src/main/webapp/WEB-INF/web.xml");
  webAppContext.setResourceBase(path + "/target/hapi-fhir-jpaserver-starter");
  webAppContext.setParentLoaderPriority(true);

  ourServer.setHandler(webAppContext);
  ourServer.start();

  ourPort = JettyUtil.getPortForStartedServer(ourServer);

  ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
  ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
  String ourServerBase = HapiProperties.getServerAddress();
  ourServerBase = "http://localhost:" + ourPort + "/hapi-fhir-jpaserver/fhir/";

  ourClient = ourCtx.newRestfulGenericClient(ourServerBase);
  ourClient.registerInterceptor(new LoggingInterceptor(true));

  ourClientTenantInterceptor = new UrlTenantSelectionInterceptor();
  ourClient.registerInterceptor(ourClientTenantInterceptor);
}
 
Example #27
Source Project: java-slack-sdk   Author: slackapi   File: MockSlackApiServer.java    License: MIT License 5 votes vote down vote up
public MockSlackApiServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(MockSlackApi.class, "/*");
}
 
Example #28
Source Project: calcite   Author: apache   File: HttpServer.java    License: Apache License 2.0 5 votes vote down vote up
void stop() {
  if (server == null) {
    throw new RuntimeException("Server is already stopped");
  } else {
    try {
      final Server server1 = server;
      port = -1;
      server = null;
      server1.stop();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example #29
Source Project: qmq   Author: qunarcorp   File: Bootstrap.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DynamicConfig config = DynamicConfigLoader.load("backup.properties");
    DynamicConfig deadConfig = DynamicConfigLoader.load("dead_backup.properties");
    ServerWrapper wrapper = new ServerWrapper(config, deadConfig);
    Runtime.getRuntime().addShutdownHook(new Thread(wrapper::destroy));
    wrapper.start();

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase(System.getProperty("java.io.tmpdir"));

    final MessageService messageService = wrapper.getMessageService();

    DeadMessageApiServlet deadMessageApiServlet = new DeadMessageApiServlet(messageService);
    addServlet(context, deadMessageApiServlet, "/api/message/dead");

    MessageApiServlet messageApiServlet = new MessageApiServlet(messageService);
    addServlet(context, messageApiServlet, "/api/message");

    MessageDetailsServlet messageDetailsServlet = new MessageDetailsServlet(messageService);
    addServlet(context, messageDetailsServlet, "/api/message/detail");

    MessageRecordsServlet messageRecordsServlet = new MessageRecordsServlet(messageService);
    addServlet(context, messageRecordsServlet, "/api/message/records");

    int port = config.getInt("backup.server.http.port", 8080);
    final Server server = new Server(port);
    server.setHandler(context);
    server.start();
    server.join();
}
 
Example #30
Source Project: android-uiconductor   Author: google   File: StartUpInit.java    License: Apache License 2.0 5 votes vote down vote up
private void initLogServer() {
  if (logServerThread != null && logServerThread.isAlive()) {
    logServerThread.interrupt();
  }

  if (logServer != null && logServer.isStarted()) {
    try {
      logServer.stop();
    } catch (Exception e) {
      logger.warning(e.getMessage());
    }
  }

  logServerThread =
      new Thread(
          () -> {
            logServer = new Server(8888);

            WebSocketHandler wsHandler =
                new WebSocketHandler() {
                  @Override
                  public void configure(WebSocketServletFactory factory) {
                    factory.register(LogWebSocketHandler.class);
                  }
                };
            logServer.setHandler(wsHandler);

            try {
              logServer.start();
              logServer.join();
            } catch (Exception e) {
              logger.warning(e.getMessage());
            }
          });
  logServerThread.start();
}