Java Code Examples for org.eclipse.jetty.server.Server#destroy()

The following examples show how to use org.eclipse.jetty.server.Server#destroy() . 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: ServerMain.java    From wisp with 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 2
Source File: CodeGenBugTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testHelloWorldExternalBindingFile() throws Exception {
    Server server = new Server(0);
    try {
        ResourceHandler reshandler = new ResourceHandler();
        reshandler.setResourceBase(getLocation("/wsdl2java_wsdl/"));
        // this is the only handler we're supposed to need, so we don't need to
        // 'add' it.
        server.setHandler(reshandler);
        server.start();
        Thread.sleep(250); //give network connector a little time to spin up
        int port = ((NetworkConnector)server.getConnectors()[0]).getLocalPort();
        env.put(ToolConstants.CFG_WSDLURL, "http://localhost:"
            + port + "/hello_world.wsdl");
        env.put(ToolConstants.CFG_BINDING, "http://localhost:"
            + port + "/remote-hello_world_binding.xsd");
        processor.setContext(env);
        processor.execute();
        reshandler.stop();
    } finally {
        server.stop();
        server.destroy();
    }

}
 
Example 3
Source File: Main.java    From wingtips with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = createServer(Integer.parseInt(System.getProperty(PORT_SYSTEM_PROP_KEY, "8080")));

    try {
        server.start();
        server.join();
    }
    finally {
        server.destroy();
    }
}
 
Example 4
Source File: RESTInterface.java    From nadia with Apache License 2.0 5 votes vote down vote up
@Override
public void start(){
	try{
		NadiaProcessorConfig config = NadiaProcessorConfig.getInstance();
		
		//Jetty:
		server = new Server();
		
		//main config
        WebAppContext context = new WebAppContext();
        context.setDescriptor(config.getProperty(NadiaProcessorConfig.JETTYWEBXMLPATH));
        context.setResourceBase(config.getProperty(NadiaProcessorConfig.JETTYRESOURCEBASE));
        context.setContextPath(config.getProperty(NadiaProcessorConfig.JETTYCONTEXTPATH));
        context.setParentLoaderPriority(true);
        server.setHandler(context);
        
        //ssl (https)
        SslContextFactory sslContextFactory = new SslContextFactory(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPATH));
        sslContextFactory.setKeyStorePassword(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPASS));

        ServerConnector serverconn = new ServerConnector(server, sslContextFactory);
        serverconn.setPort(8080); //443 (or 80) not allowed on Linux unless run as root
        server.setConnectors(new Connector[] {serverconn});
        
        //start	        
        server.start();
        logger.info("REST interface started on "+server.getURI());
        server.join();
		
	}
	catch(Exception ex){
		ex.printStackTrace();
		logger.severe("Nadia: failed to start Jetty: "+ex.getMessage());
		server.destroy();
	}
}
 
Example 5
Source File: ListenHTTP.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void shutdownHttpServer(Server toShutdown) {
    try {
        toShutdown.stop();
        toShutdown.destroy();
        clearInit();
    } catch (final Exception ex) {
        getLogger().warn("unable to cleanly shutdown embedded server due to {}", new Object[] {ex});
        this.server = null;
    }
}
 
Example 6
Source File: Application.java    From cantor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {
    logger.info("starting cantor http server...");
    final Server server = new EmbeddedHttpServer().createServer(port, basePath);

    try {
        server.start();
        System.out.println("Server started: http://localhost:" + port);
        server.join();
    } catch (final Exception e) {
        logger.error("failed to start Cantor HTTP Server: ", e);
        System.exit(1);
    } finally {
        server.destroy();
    }
}
 
Example 7
Source File: Main.java    From wingtips with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = createServer(Integer.parseInt(System.getProperty(PORT_SYSTEM_PROP_KEY, "8080")));

    try {
        server.start();
        server.join();
    }
    finally {
        server.destroy();
    }
}
 
Example 8
Source File: Main.java    From wingtips with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = createServer(Integer.parseInt(System.getProperty(PORT_SYSTEM_PROP_KEY, "8080")));

    try {
        server.start();
        server.join();
    }
    finally {
        server.destroy();
    }
}
 
Example 9
Source File: IftttIndegoAdapter.java    From iot-device-bosch-indego-controller with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the HTTP server.
 * 
 * @param httpServer the HTTP server to close
 */
private void disconnect (Server httpServer)
{
    if ( httpServer != null ) {
        httpServer.destroy();
    }
}
 
Example 10
Source File: Main.java    From backstopper with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = createServer(Integer.parseInt(System.getProperty(PORT_SYSTEM_PROP_KEY, "8080")));

    try {
        server.start();
        server.join();
    }
    finally {
        server.destroy();
    }
}
 
Example 11
Source File: Main.java    From backstopper with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = createServer(Integer.parseInt(System.getProperty(PORT_SYSTEM_PROP_KEY, "8080")));

    try {
        server.start();
        server.join();
    }
    finally {
        server.destroy();
    }
}
 
Example 12
Source File: Main.java    From backstopper with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = createServer(Integer.parseInt(System.getProperty(PORT_SYSTEM_PROP_KEY, "8080")));

    try {
        server.start();
        server.join();
    }
    finally {
        server.destroy();
    }
}
 
Example 13
Source File: ListenHTTP.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void shutdownHttpServer(Server toShutdown) {
    try {
        toShutdown.stop();
        toShutdown.destroy();
    } catch (final Exception ex) {
        getLogger().warn("unable to cleanly shutdown embedded server due to {}", new Object[] {ex});
        this.server = null;
    }
}
 
Example 14
Source File: Runtime.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"IllegalCatch", "RegexpSinglelineJava"})
public static void main(String[] args) throws Exception {
  final Options options = createOptions();
  final Options helpOptions = constructHelpOptions();

  CommandLineParser parser = new DefaultParser();

  // parse the help options first.
  CommandLine cmd = parser.parse(helpOptions, args, true);
  if (cmd.hasOption(Flag.Help.name)) {
    usage(options);
    return;
  }

  try {
    cmd = parser.parse(options, args);
  } catch (ParseException pe) {
    System.err.println(pe.getMessage());
    usage(options);
    return;
  }

  final boolean verbose = isVerbose(cmd);
  // set and configure logging level
  Logging.setVerbose(verbose);
  Logging.configure(verbose);

  LOG.debug("API server overrides:\n {}", cmd.getOptionProperties(Flag.Property.name));

  final String toolsHome = getToolsHome();

  // read command line flags
  final String cluster = cmd.getOptionValue(Flag.Cluster.name);
  final String heronConfigurationDirectory = getConfigurationDirectory(toolsHome, cmd);
  final String heronDirectory = getHeronDirectory(cmd);
  final String releaseFile = getReleaseFile(toolsHome, cmd);
  final String configurationOverrides = loadOverrides(cmd);
  final int port = getPort(cmd);
  final String downloadHostName = getDownloadHostName(cmd);
  final String heronCorePackagePath = getHeronCorePackagePath(cmd);

  final Config baseConfiguration =
      ConfigUtils.getBaseConfiguration(heronDirectory,
          heronConfigurationDirectory,
          releaseFile,
          configurationOverrides);

  final ResourceConfig config = new ResourceConfig(Resources.get());
  final Server server = new Server(port);

  final ServletContextHandler contextHandler =
      new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  contextHandler.setContextPath("/");

  LOG.info("using configuration path: {}", heronConfigurationDirectory);

  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CLUSTER, cluster);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION, baseConfiguration);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_DIRECTORY,
      heronConfigurationDirectory);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_OVERRIDE_PATH,
      configurationOverrides);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_PORT,
      String.valueOf(port));
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_DOWNLOAD_HOSTNAME,
      Utils.isNotEmpty(downloadHostName)
          ? String.valueOf(downloadHostName) : null);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_HERON_CORE_PACKAGE_PATH,
      Utils.isNotEmpty(heronCorePackagePath)
          ? String.valueOf(heronCorePackagePath) : null);

  server.setHandler(contextHandler);

  final ServletHolder apiServlet =
      new ServletHolder(new ServletContainer(config));

  contextHandler.addServlet(apiServlet, API_BASE_PATH);

  try {
    server.start();

    LOG.info("Heron API server started at {}", server.getURI());

    server.join();
  } catch (Exception ex) {
    final String message = getErrorMessage(server, port, ex);
    LOG.error(message);
    System.err.println(message);
    System.exit(1);
  } finally {
    server.destroy();
  }
}
 
Example 15
Source File: RESTApp.java    From account-provisioning-for-google-apps with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the Jetty server.
 */
private void initJettyServer() {
  logger.log(Level.INFO, "Initialzing Jetty server...");
  int port;
  if (customPort == null) {
    logger.log(Level.INFO, "Initialzing server in default port: " + PORT_DEFAULT_VALUE);
    port = PORT_DEFAULT_VALUE;
  } else {
    logger.log(Level.INFO, "Initialzing server in custom port: " + customPort.toString());
    port = customPort;
  }
  jettyServer = new Server(port);

  ConfigData config = ProvisioningApp.getInstance().getContext().getConfig();
  if (config.getUseSSL()) {
    HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getKeyStorePath());
    sslContextFactory.setKeyStorePassword(config.getKeyStorePassword());
    sslContextFactory.setKeyManagerPassword(config.getKeyManagerPassword());

    ServerConnector sslConnector =
        new ServerConnector(jettyServer,
            new SslConnectionFactory(sslContextFactory, HTTP_VERSION), new HttpConnectionFactory(
                https));
    sslConnector.setPort(port);

    jettyServer.setConnectors(new Connector[] {sslConnector});
  }

  jettyServer.setHandler(servletContext);

  try {
    jettyServer.start();
    jettyServer.join();
  } catch (Throwable e) {
    logger.log(Level.SEVERE, "Exception during server initialization", e);
    jettyServer.destroy();
  }
}
 
Example 16
Source File: JettyServiceBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a newly-created {@link JettyService} based on the properties of this builder.
 */
public JettyService build() {
    final JettyServiceConfig config = new JettyServiceConfig(
            hostname, dumpAfterStart, dumpBeforeStop, stopTimeoutMillis, handler, requestLog,
            sessionIdManagerFactory, attrs, beans, handlerWrappers, eventListeners, lifeCycleListeners,
            configurators);

    final Function<ScheduledExecutorService, Server> serverFactory = blockingTaskExecutor -> {
        final Server server = new Server(new ArmeriaThreadPool(blockingTaskExecutor));

        if (config.dumpAfterStart() != null) {
            server.setDumpAfterStart(config.dumpAfterStart());
        }
        if (config.dumpBeforeStop() != null) {
            server.setDumpBeforeStop(config.dumpBeforeStop());
        }
        if (config.stopTimeoutMillis() != null) {
            server.setStopTimeout(config.stopTimeoutMillis());
        }

        if (config.handler() != null) {
            server.setHandler(config.handler());
        }
        if (config.requestLog() != null) {
            server.setRequestLog(requestLog);
        }
        if (config.sessionIdManagerFactory() != null) {
            server.setSessionIdManager(config.sessionIdManagerFactory().apply(server));
        }

        config.handlerWrappers().forEach(server::insertHandler);
        config.attrs().forEach(server::setAttribute);
        config.beans().forEach(bean -> {
            final Boolean managed = bean.isManaged();
            if (managed == null) {
                server.addBean(bean.bean());
            } else {
                server.addBean(bean.bean(), managed);
            }
        });

        config.eventListeners().forEach(server::addEventListener);
        config.lifeCycleListeners().forEach(server::addLifeCycleListener);

        config.configurators().forEach(c -> c.accept(server));

        return server;
    };

    final Consumer<Server> postStopTask = server -> {
        try {
            JettyService.logger.info("Destroying an embedded Jetty: {}", server);
            server.destroy();
        } catch (Exception e) {
            JettyService.logger.warn("Failed to destroy an embedded Jetty: {}", server, e);
        }
    };

    return new JettyService(config.hostname(), serverFactory, postStopTask);
}
 
Example 17
Source File: TopologyServerUnify.java    From netphony-topology with Apache License 2.0 4 votes vote down vote up
@Override
public void run() 
{
	log.info("Unify Topology Server");
	
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
       context.setContextPath("/");
       log.info("Service-Topology Port: "+params.getExportUnifyPort());
       Server jettyServer = new Server(params.getExportUnifyPort());
       jettyServer.setHandler(context);
       ServletHolder jerseyServlet =  
       		context.addServlet( com.sun.jersey.spi.container.servlet.ServletContainer.class, "/*");


       jerseyServlet.setInitParameter(
               "com.sun.jersey.config.property.packages",
               "io.swagger.jaxrs.json;io.swagger.jaxrs.listing;es.tid.topologyModuleBase.UnifyTopoModel.api");
       
       jerseyServlet.setInitParameter(
               "com.sun.jersey.spi.container.ContainerRequestFilters",
               "com.sun.jersey.api.container.filter.PostReplaceFilter");
       
       jerseyServlet.setInitParameter(
               "com.sun.jersey.api.json.POJOMappingFeatures",
               "true");
       
       jerseyServlet.setInitOrder(1);
	
       
       try {
       	isRunning=true;
           jettyServer.start();
           //jettyServer.dumpStdErr();
           jettyServer.join();
       } catch(Exception e){
       	log.severe(e.getStackTrace().toString());
       }finally {     
           jettyServer.destroy();
       }
	
}
 
Example 18
Source File: TopologyServerCOP.java    From netphony-topology with Apache License 2.0 4 votes vote down vote up
@Override
public void run() 
{
	log.info("Acting as BGP Peer");
	
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
       context.setContextPath("/");
       log.info("Service-Topology Port: "+params.getExportCOPPort());
       Server jettyServer = new Server(params.getExportCOPPort());
       jettyServer.setHandler(context);
       ServletHolder jerseyServlet =  
       		context.addServlet( com.sun.jersey.spi.container.servlet.ServletContainer.class, "/*");


       jerseyServlet.setInitParameter(
               "com.sun.jersey.config.property.packages",
               "io.swagger.jaxrs.json;io.swagger.jaxrs.listing;es.tid.topologyModuleBase.COPServiceTopology.server.api");
       
       jerseyServlet.setInitParameter(
               "com.sun.jersey.spi.container.ContainerRequestFilters",
               "com.sun.jersey.api.container.filter.PostReplaceFilter");
       
       jerseyServlet.setInitParameter(
               "com.sun.jersey.api.json.POJOMappingFeatures",
               "true");
       
       jerseyServlet.setInitOrder(1);
	
       
       try {
       	isRunning=true;
           jettyServer.start();
           //jettyServer.dumpStdErr();
           jettyServer.join();
       } catch(Exception e){
       	log.severe(e.getStackTrace().toString());
       }finally {     
           jettyServer.destroy();
       }
	
}
 
Example 19
Source File: TopologyServerIETF.java    From netphony-topology with Apache License 2.0 4 votes vote down vote up
@Override
public void run() 
{
	log.info("IETF Topology Server");
	
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
       context.setContextPath("/");
       log.info("Service-Topology Port: "+params.getExportIETFPort());
       Server jettyServer = new Server(params.getExportIETFPort());
       jettyServer.setHandler(context);
       ServletHolder jerseyServlet =  
       		context.addServlet( com.sun.jersey.spi.container.servlet.ServletContainer.class, "/*");


       jerseyServlet.setInitParameter(
               "com.sun.jersey.config.property.packages",
               "io.swagger.jaxrs.json;io.swagger.jaxrs.listing;es.tid.topologyModuleBase.IETFTopoModel.api");
       
       jerseyServlet.setInitParameter(
               "com.sun.jersey.spi.container.ContainerRequestFilters",
               "com.sun.jersey.api.container.filter.PostReplaceFilter");
       
       jerseyServlet.setInitParameter(
               "com.sun.jersey.api.json.POJOMappingFeatures",
               "true");
       
       jerseyServlet.setInitOrder(1);
	
       
       try {
       	isRunning=true;
           jettyServer.start();
           //jettyServer.dumpStdErr();
           jettyServer.join();
       } catch(Exception e){
       	log.severe(e.getStackTrace().toString());
       }finally {     
           jettyServer.destroy();
       }
	
}
 
Example 20
Source File: JdbcBridge.java    From clickhouse-jdbc-bridge with Apache License 2.0 4 votes vote down vote up
@Override
@SneakyThrows
public void run() {
    log.info("Starting jdbc-bridge");

    JdbcDriverLoader.load(config.getDriverPath());

    BridgeConnectionManager manager = new BridgeConnectionManager();
    if (null != config.getConnectionFile()) {
        manager.load(config.getConnectionFile());
    }

    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new QueryHandlerServlet(manager)), "/");
    handler.addServletWithMapping(new ServletHolder(new ColumnsInfoServlet(manager, new ClickHouseConverter())), "/columns_info");
    handler.addServletWithMapping(new ServletHolder(new IdentifierQuoteServlet(manager)), "/identifier_quote");
    handler.addServletWithMapping(new ServletHolder(new PingHandlerServlet()), "/ping");
    handler.addFilterWithMapping(RequestLogger.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    InetSocketAddress address = new InetSocketAddress(config.getListenHost(), config.getHttpPort());
    log.info("Will bind to {}", address);

    // this tricks are don in order to get good thread name in logs :(
    QueuedThreadPool pool = new QueuedThreadPool(1024, 10); // @todo make configurable?
    pool.setName("HTTP Handler");
    Server jettyServer = new Server(pool);
    ServerConnector connector = new ServerConnector(jettyServer);

    // @todo a temporary solution for dealing with too long URI for some endpoints
    HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setRequestHeaderSize(24 * 1024);
    HttpConnectionFactory factory = new HttpConnectionFactory(httpConfiguration);
    connector.setConnectionFactories(Collections.singleton(factory));

    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    jettyServer.setConnectors(new Connector[]{connector});

    jettyServer.setHandler(handler);
    jettyServer.setErrorHandler(new ErrorHandler() {
        @Override
        protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
            writer.write(message);
        }
    });

    try {
        log.info("Starting server");
        jettyServer.start();
        log.info("Server is ready to accept connections");
        jettyServer.join();
    } finally {
        jettyServer.destroy();
    }
}