Java 类org.eclipse.jetty.server.Server 实例源码

项目:otus_java_2017_06    文件:Main.java   
public static void main(String[] args) throws Exception {

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setResourceBase(PUBLIC_HTML);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

        //page reloaded by the timer
        context.addServlet(TimerServlet.class, "/timer");
        //part of a page reloaded by the timer
        context.addServlet(AjaxTimerServlet.class, "/server-time");
        //long-polling waits till a message
        context.addServlet(new ServletHolder(new MessengerServlet()), "/messenger");
        //web chat
        context.addServlet(WebSocketChatServlet.class, "/chat");

        Server server = new Server(PORT);
        server.setHandler(new HandlerList(resourceHandler, context));

        server.start();
        server.join();
    }
项目:crawling-framework    文件:Application.java   
public static void main(String[] args) {
    int port = Configuration.INSTANCE.getInt("port", 8080);
    Server server = new Server(port);
    ServletContextHandler contextHandler
            = new ServletContextHandler(ServletContextHandler.SESSIONS);
    contextHandler.setContextPath("/");
    ServletHolder sh = new ServletHolder(new VaadinServlet());
    contextHandler.addServlet(sh, "/*");
    contextHandler.setInitParameter("ui", CrawlerAdminUI.class.getCanonicalName());
    contextHandler.setInitParameter("productionMode", String.valueOf(PRODUCTION_MODE));
    server.setHandler(contextHandler);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        LOG.error("Failed to start application", e);
    }
}
项目:jmx-prometheus-exporter    文件:CollectorServer.java   
public @NotNull CollectorServer init(@NotNull InetSocketAddress address, @NotNull ExpositionFormat format) {
  try {
    Log.setLog(new Slf4jLog());

    final Server serverInstance = new Server(address);
    format.handler(serverInstance);
    serverInstance.start();

    server = serverInstance;

    Logger.instance.info("Prometheus server with JMX metrics started at " + address);
  } catch (Exception e) {
    Logger.instance.error("Failed to start server at " + address, e);
  }
  return this;
}
项目:jetty-embed-reverse-proxy-example    文件:ProxyServer.java   
private static void reverseProxy() throws Exception{
  Server server = new Server();

  SocketConnector connector = new SocketConnector();
  connector.setHost("127.0.0.1");
  connector.setPort(8888);

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

  // Setup proxy handler to handle CONNECT methods
  ConnectHandler proxy = new ConnectHandler();
  server.setHandler(proxy);

  // Setup proxy servlet
  ServletContextHandler context = new ServletContextHandler(proxy, "/", ServletContextHandler.SESSIONS);
  ServletHolder proxyServlet = new ServletHolder(ProxyServlet.Transparent.class);
  proxyServlet.setInitParameter("ProxyTo", "https://localhost:54321/");
  proxyServlet.setInitParameter("Prefix", "/");
  context.addServlet(proxyServlet, "/*");

  server.start();
}
项目:ZooKeeper    文件:LogServer.java   
public static void main(String[] args) {  
try {  
    MergedLogSource src = new MergedLogSource(args);
    System.out.println(src);

    Server server = new Server(8182);
    server.setHandler(new LogServer(src));

    server.start();
    server.join();

} catch (Exception e) {  
    // Something is wrong.  
    e.printStackTrace();  
}  
   }
项目:monarch    文件:JettyHelper.java   
public static Server addWebApplication(final Server jetty, final String webAppContext,
    final String warFilePath) {
  WebAppContext webapp = new WebAppContext();
  webapp.setContextPath(webAppContext);
  webapp.setWar(warFilePath);
  webapp.setParentLoaderPriority(false);
  webapp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

  File tmpPath = new File(getWebAppBaseDirectory(webAppContext));
  tmpPath.mkdirs();
  webapp.setTempDirectory(tmpPath);

  ((HandlerCollection) jetty.getHandler()).addHandler(webapp);

  return jetty;
}
项目:calcite-avatica    文件:HttpServer.java   
/**
 * Configures the <code>connector</code> given the <code>config</code> for using SPNEGO.
 *
 * @param connector The connector to configure
 * @param config The configuration
 */
protected ConstraintSecurityHandler configureSpnego(Server server, ServerConnector connector,
    AvaticaServerConfiguration config) {
  final String realm = Objects.requireNonNull(config.getKerberosRealm());
  final String principal = Objects.requireNonNull(config.getKerberosPrincipal());

  // A customization of SpnegoLoginService to explicitly set the server's principal, otherwise
  // we would have to require a custom file to set the server's principal.
  PropertyBasedSpnegoLoginService spnegoLoginService =
      new PropertyBasedSpnegoLoginService(realm, principal);

  // Roles are "realms" for Kerberos/SPNEGO
  final String[] allowedRealms = getAllowedRealms(realm, config);

  return configureCommonAuthentication(server, connector, config, Constraint.__SPNEGO_AUTH,
      allowedRealms, new AvaticaSpnegoAuthenticator(), realm, spnegoLoginService);
}
项目:n4js    文件:JettyManager.java   
@Override
public boolean isRunning(final int port) {

    if (!isValidPort(port)) {
        return false;
    }

    final Server server = serverCache.getIfPresent(port);
    if (null == server) {
        return false;
    }
    if (!server.isStarted()) {
        return false;
    }

    return isPortInUse(port);
}
项目:uavstack    文件:JettyPlusIT.java   
/**
 * startUAVServer
 */
public void startServer(Object... args) {

    Server server = (Server) args[0];

    // integrate Tomcat log
    UAVServer.instance().setLog(new JettyLog("MonitorServer"));
    // start Monitor Server when server starts
    UAVServer.instance().start(new Object[] { UAVServer.ServerVendor.JETTY });

    // get server port
    if (UAVServer.instance().getServerInfo(CaptureConstants.INFO_APPSERVER_LISTEN_PORT) == null) {
        // set port
        ServerConnector sc = (ServerConnector) server.getConnectors()[0];

        String protocol = sc.getDefaultProtocol();
        if (protocol.toLowerCase().indexOf("http") >= 0) {
            UAVServer.instance().putServerInfo(CaptureConstants.INFO_APPSERVER_LISTEN_PORT, sc.getPort());
        }
    }

}
项目:monarch    文件:JettyHelper.java   
public static void main(final String... args) throws Exception {
  if (args.length > 1) {
    System.out.printf("Temporary Directory @ ($1%s)%n", USER_DIR);

    final Server jetty = JettyHelper.initJetty(null, 8090, new SSLConfig());

    for (int index = 0; index < args.length; index += 2) {
      final String webAppContext = args[index];
      final String webAppArchivePath = args[index + 1];

      JettyHelper.addWebApplication(jetty, normalizeWebAppContext(webAppContext),
          normalizeWebAppArchivePath(webAppArchivePath));
    }

    JettyHelper.startJetty(jetty);
    latch.await();
  } else {
    System.out.printf(
        "usage:%n>java org.apache.geode.management.internal.TomcatHelper <web-app-context> <war-file-path> [<web-app-context> <war-file-path>]*");
  }
}
项目:otus_java_2017_04    文件:Main.java   
public static void main(String[] args) throws Exception {

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setResourceBase(PUBLIC_HTML);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

        context.addServlet(new ServletHolder(new LoginServlet("anonymous")), "/login");
        context.addServlet(AdminServlet.class, "/admin");
        context.addServlet(TimerServlet.class, "/timer");

        Server server = new Server(PORT);
        server.setHandler(new HandlerList(resourceHandler, context));

        server.start();
        server.join();
    }
项目:abhot    文件:Launcher.java   
public static Server createDevServer(int port, String contextPath) {

        Server server = new Server();
        server.setStopAtShutdown(true);

        ServerConnector connector = new ServerConnector(server);
        // 设置服务端口
        connector.setPort(port);
        connector.setReuseAddress(false);
        server.setConnectors(new Connector[] {connector});

        // 设置web资源根路径以及访问web的根路径
        WebAppContext webAppCtx = new WebAppContext(DEFAULT_APP_CONTEXT_PATH, contextPath);
        webAppCtx.setDescriptor(DEFAULT_APP_CONTEXT_PATH + "/WEB-INF/web.xml");
        webAppCtx.setResourceBase(DEFAULT_APP_CONTEXT_PATH);
        webAppCtx.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(webAppCtx);

        return server;
    }
项目:https-github.com-apache-zookeeper    文件:JettyAdminServer.java   
public JettyAdminServer(String address, int port, int timeout, String commandUrl) {
    this.port = port;
    this.idleTimeout = timeout;
    this.commandUrl = commandUrl;
    this.address = address;

    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address);
    connector.setPort(port);
    connector.setIdleTimeout(idleTimeout);
    server.addConnector(connector);

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

    context.addServlet(new ServletHolder(new CommandServlet()), commandUrl + "/*");
}
项目:openapi    文件:ProgramEntrance.java   
/**
 * 启动jetty服务,加载server.war
 */
public static void startJettyServer(String path) throws  Exception{
    String configPath=path+ File.separator+"conf"+File.separator+"conf.properties";
    InputStream is = new FileInputStream(configPath);;
    Properties properties =new Properties();
    properties.load(is);
    is.close();
    int serverPort = Integer.parseInt(properties.getProperty("server.port"));
    Server server = new Server(serverPort);
    WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    context.setWar(path+"/bin/service.war");
    server.setHandler(context);
    server.start();
    server.join();
}
项目:demo-springmvc-shiro    文件:JettyBootStrap.java   
public static void main(String[] args) {
    long beginTime = System.currentTimeMillis();
    Server server = createServer();
    try {
        server.start();
        System.err.println();
        System.out.println("*****************************************************************");
        System.err.print("[INFO] Server running in " + (System.currentTimeMillis() - beginTime) + "ms ");
        System.err.println("at http://127.0.0.1" + (80==port?"":":"+port) + contextPath);
        System.out.println("*****************************************************************");
    } catch (Exception e) {
        System.err.println("Jetty启动失败,堆栈轨迹如下");
        e.printStackTrace();
        System.exit(-1);
    }
}
项目:abhot    文件:Launcher.java   
public static Server createJettyServer(int port, String contextPath) {

        Server server = new Server(port);
        server.setStopAtShutdown(true);

        ProtectionDomain protectionDomain = Launcher.class.getProtectionDomain();
        URL location = protectionDomain.getCodeSource().getLocation();
        String warFile = location.toExternalForm();

        WebAppContext context = new WebAppContext(warFile, contextPath);
        context.setServer(server);

        // 设置work dir,war包将解压到该目录,jsp编译后的文件也将放入其中。
        String currentDir = new File(location.getPath()).getParent();
        File workDir = new File(currentDir, "work");
        context.setTempDirectory(workDir);

        server.setHandler(context);
        return server;

    }
项目:ZooKeeper    文件:LogServer.java   
public static void main(String[] args) {  
try {  
    MergedLogSource src = new MergedLogSource(args);
    System.out.println(src);

    Server server = new Server(8182);
    server.setHandler(new LogServer(src));

    server.start();
    server.join();

} catch (Exception e) {  
    // Something is wrong.  
    e.printStackTrace();  
}  
   }
项目:cmdbproxy    文件:ProgramEntrance.java   
/**
 * 启动jetty服务,加载server.war
 */
public static void startJettyServer(String path) throws  Exception{
    String configPath=path+ File.separator+"conf"+File.separator+"conf.properties";
    InputStream is = new FileInputStream(configPath);;
    Properties properties =new Properties();
    properties.load(is);
    is.close();
    int serverPort = Integer.parseInt(properties.getProperty("server.port"));
    Server server = new Server(serverPort);
    WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    context.setWar(path+"/bin/service.war");
    server.setHandler(context);
    server.start();
    server.join();
}
项目:skywalking-mock-collector    文件:Main.java   
public static void main(String[] args) throws Exception {
    NettyServerBuilder.forAddress(LocalAddress.ANY).forPort(19876)
        .maxConcurrentCallsPerConnection(12).maxMessageSize(16777216)
        .addService(new MockApplicationRegisterService())
        .addService(new MockInstanceDiscoveryService())
        .addService(new MockJVMMetricsService())
        .addService(new MockServiceNameDiscoveryService())
        .addService(new MockTraceSegmentService()).build().start();

    Server jettyServer = new Server(new InetSocketAddress("0.0.0.0",
        Integer.valueOf(12800)));
    String contextPath = "/";
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath(contextPath);
    servletContextHandler.addServlet(GrpcAddressHttpService.class, GrpcAddressHttpService.SERVLET_PATH);
    servletContextHandler.addServlet(ReceiveDataService.class, ReceiveDataService.SERVLET_PATH);
    servletContextHandler.addServlet(ClearReceiveDataService.class, ClearReceiveDataService.SERVLET_PATH);
    jettyServer.setHandler(servletContextHandler);
    jettyServer.start();
}
项目:act-platform    文件:ApiServer.java   
@Override
public void startComponent() {
  // Initialize servlet using RESTEasy and it's Guice bridge.
  // The listener must be injected by the same Guice module which also binds the REST endpoints.
  ServletContextHandler servletHandler = new ServletContextHandler();
  servletHandler.addEventListener(listener);
  servletHandler.addServlet(HttpServletDispatcher.class, "/*");

  // Starting up Jetty to serve the REST API.
  server = new Server(port);
  server.setHandler(servletHandler);

  try {
    server.start();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
项目:otter-G    文件:JettyEmbedServer.java   
public void afterPropertiesSet() throws Exception {
    Resource configXml = Resource.newSystemResource(config);
    XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream());
    server = (Server) configuration.configure();
    Integer port = getPort();
    if (port != null && port > 0) {
        Connector[] connectors = server.getConnectors();
        for (Connector connector : connectors) {
            connector.setPort(port);
        }
    }

    Handler handler = server.getHandler();
    if (handler != null && handler instanceof ServletContextHandler) {
        ServletContextHandler servletHandler = (ServletContextHandler) handler;
        servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", htdocsDir);
    }

    server.start();
    if (logger.isInfoEnabled()) {
        logger.info("##Jetty Embed Server is startup!");
    }
}
项目:strictfp-back-end    文件:MainServer.java   
public static void main(@NotNull @NonNls String[] args) throws Exception {
    PropertyConfigurator.configure(System.getProperty("user.dir") + "/log4j.properties");
    logger.warn("StrictFP | Back-end");
    logger.info("StrictFP Back-end is now running...");
    Server server = new Server(Constant.SERVER.SERVER_PORT);
    ServletContextHandler context =
            new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/api/v0");
    server.setHandler(context);
    server.setStopAtShutdown(true);
    // 像下面这行一样
    context.addServlet(new ServletHolder(new GetQuiz()), "/misc/getquiz");
    context.addServlet(new ServletHolder(new TimeLine()), "/timeline");
    context.addServlet(new ServletHolder(new Counter()), "/misc/counter");
    context.addServlet(new ServletHolder(new User()), "/user");
    context.addServlet(new ServletHolder(new Heartbeat()), "/misc/heartbeat");
    context.addServlet(new ServletHolder(new SafeCheck()), "/misc/safecheck");
    context.addServlet(new ServletHolder(new CheckCert()), "/auth/check_cert");
    //
    server.start();
    server.join();
}
项目:boutique-de-jus    文件:BoutiqueDeJusWebServer.java   
private static void restartWebServer(final Server server, final WebAppContext webApp) throws Exception {

        //TODO reconsider restart function
        /*
          restart doesnt help much regarding heap configuration, everything else can be configured at
          runtime. So better approach for convenient restart would be an orderly shutdown and start.
         */
        server.stop();
        LOG.info("Sent stop");
        server.join();
        LOG.info("Server joined");
        LOG.info("Starting web server");
        server.setHandler(webApp);
        server.start();
        LOG.info("Server restarted");
    }
项目:cassandra-prometheus    文件:PrometheusExporter.java   
public PrometheusExporter(int port, String path) {

    QueuedThreadPool threadPool = new QueuedThreadPool(25);
    server = new Server(threadPool);

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

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);

    CollectorRegistry collectorRegistry = new CollectorRegistry();

    collectorRegistry.register(new PrometheusExports(CassandraMetricsRegistry.Metrics));

    MetricsServlet metricsServlet = new MetricsServlet(collectorRegistry);

    context.addServlet(new ServletHolder(metricsServlet), "/" + path);
    try {
        server.start();
    } catch (Exception e) {
        System.err.println("cannot start metrics http server " + e.getMessage());
    }
}
项目:otus_java_2017_06    文件:Main.java   
private void start() throws Exception {
    resourcesExample();

    ResourceHandler resourceHandler = new ResourceHandler();
    Resource resource = Resource.newClassPathResource(PUBLIC_HTML);
    resourceHandler.setBaseResource(resource);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

    context.addServlet(new ServletHolder(new TimerServlet()), "/timer");

    Server server = new Server(PORT);
    server.setHandler(new HandlerList(resourceHandler, context));

    server.start();
    server.join();
}
项目:fuck_zookeeper    文件:LogServer.java   
public static void main(String[] args) {  
try {  
    MergedLogSource src = new MergedLogSource(args);
    System.out.println(src);

    Server server = new Server(8182);
    server.setHandler(new LogServer(src));

    server.start();
    server.join();

} catch (Exception e) {  
    // Something is wrong.  
    e.printStackTrace();  
}  
   }
项目:otter-G    文件:JettyEmbedIntegration.java   
public static void main(String args[]) throws Exception {
    Resource jetty_xml = Resource.newSystemResource("jetty/jetty.xml");
    XmlConfiguration configuration = new XmlConfiguration(jetty_xml.getInputStream());
    Server server = (Server) configuration.configure();
    int port = 8081;
    Connector[] connectors = server.getConnectors();
    for (Connector connector : connectors) {
        connector.setPort(port);
    }

    Handler handler = server.getHandler();
    if (handler != null && handler instanceof ServletContextHandler) {
        ServletContextHandler servletHandler = (ServletContextHandler) handler;
        servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", "/tmp/");
    }

    server.start();
    server.join();
}
项目:grpc-proxy    文件:LegacyHttpServer.java   
private LegacyHttpServer(int port, int threads) {
  this.server = new Server(new QueuedThreadPool(threads));
  server.setHandler(
      new AbstractHandler() {
        @Override
        public void handle(
            String target,
            Request baseRequest,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {
          final String method = baseRequest.getParameter("method");
          if ("helloworld.Greeter/SayHello".equals(method)) {
            baseRequest.setHandled(true);
            sayHello(baseRequest, response);
          }
        }
      });

  final ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
}
项目:jvm-sandbox    文件:JettyCoreServer.java   
private void initHttpServer(final CoreConfigure cfg) {

        // 如果IP:PORT已经被占用,则无法继续被绑定
        // 这里说明下为什么要这么无聊加个这个判断,让Jetty的Server.bind()抛出异常不是更好么?
        // 比较郁闷的是,如果这个端口的绑定是"SO_REUSEADDR"端口可重用的模式,那么这个server是能正常启动,但无法正常工作的
        // 所以这里必须先主动检查一次端口占用情况,当然了,这里也会存在一定的并发问题,BUT,我认为这种概率事件我可以选择暂时忽略
        if (NetworkUtils.isPortInUsing(cfg.getServerIp(), cfg.getServerPort())) {
            throw new IllegalStateException(String.format("server[ip=%s;port=%s;] already in using, server bind failed.",
                    cfg.getServerIp(), cfg.getServerPort()));
        }

        httpServer = new Server(new InetSocketAddress(cfg.getServerIp(), cfg.getServerPort()));
        if (httpServer.getThreadPool() instanceof QueuedThreadPool) {
            final QueuedThreadPool qtp = (QueuedThreadPool) httpServer.getThreadPool();
            qtp.setName("sandbox-jetty-qtp" + qtp.hashCode());
        }
    }
项目:webserver    文件:BeanParamIntegrationTest.java   
@BeforeClass
public static void initialize() throws Exception {
  injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(BookResource.class);
    }

    @DefaultConnector
    @Provides
    Configurator configurator() {
      return () -> 0; // port
    }
  }, new WebServerModule(), new HTTPConnectorModule());

  client = ClientBuilder.newClient();
  server = injector.getInstance(Server.class);
  server.start();
}
项目:distributed-task-scheduler    文件:TaskTrackerHandler.java   
/** {@inheritDoc} */
@Override
public void run() {
    try {
        this.server = new Server(this.serverPort);

        ServletHandler servletHandler = new ServletHandler();
        servletHandler.addServletWithMapping(TaskTrackerServlet.class, "/tracker");
        this.server.setHandler(servletHandler);

        this.server.start();
        this.server.join();
    } catch (Exception ex) {
        // suppress
    }
}
项目:https-github.com-apache-zookeeper    文件:LogServer.java   
public static void main(String[] args) {  
try {  
    MergedLogSource src = new MergedLogSource(args);
    System.out.println(src);

    Server server = new Server(8182);
    server.setHandler(new LogServer(src));

    server.start();
    server.join();

} catch (Exception e) {  
    // Something is wrong.  
    e.printStackTrace();  
}  
   }
项目:JInsight    文件:JettyFilterInstrumentationTest.java   
@BeforeClass
public static void setUp() throws Exception {
  System.out.println("Jetty [Configuring]");

  ServletContextHandler servletContext = new ServletContextHandler();
  servletContext.setContextPath("/");
  servletContext.addServlet(PingPongServlet.class, PingPongServlet.PATH);
  servletContext.addServlet(ExceptionServlet.class, ExceptionServlet.PATH);
  ServletHolder servletHolder = servletContext.addServlet(AsyncServlet.class, AsyncServlet.PATH);
  servletHolder.setAsyncSupported(true);

  jetty = new Server(0);
  jetty.setHandler(servletContext);
  System.out.println("Jetty [Starting]");
  jetty.start();
  System.out.println("Jetty [Started]");
  serverPort = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort();
}
项目:rainbow    文件:RwServer.java   
public void start() throws Exception
{
    String relativelyPath = System.getProperty("user.dir");

    server = new Server(port);
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setContextPath("/");
    webAppContext.setWar(relativelyPath + "\\rainbow-web\\target\\rainbow-web.war");
    webAppContext.setParentLoaderPriority(true);
    webAppContext.setServer(server);
    webAppContext.setClassLoader(ClassLoader.getSystemClassLoader());
    webAppContext.getSessionHandler().getSessionManager()
            .setMaxInactiveInterval(10);
    server.setHandler(webAppContext);
    server.start();
}
项目:demo-cas-client    文件:JettyBootStrap.java   
private void run(){
        long beginTime = System.currentTimeMillis();
        Server server = createServer(this.port, this.context_path, this.webapp_path);
        //setTldJarNames(server, new String[]{"sitemesh", "spring-webmvc", "shiro-web"});
        try {
            //启动Jetty
            server.start();
            this.log(System.currentTimeMillis() - beginTime);
//          //等待用户键入回车重载应用
//          while(true){
//              char c = (char)System.in.read();
//              if(c == '\n'){
//                  reloadContext(server, JettyBootStrap.class.getResource("/").getPath());
//              }
//          }
        } catch (Exception e) {
            System.err.println("Jetty启动失败,堆栈轨迹如下");
            e.printStackTrace();
            System.exit(-1);
        }
    }
项目:JDHttpAPI    文件:HttpAPIExtension.java   
private void startServer() {
    HttpAPIConfig cfg = getSettings();
    server = new Server(cfg.getPort());
    HandlerList lst = new HandlerList();
    LinkController ctr = new JDLinkController(LinkCollector.getInstance());
    if(cfg.getUsePassword() && cfg.getPassword() != null && !cfg.getPassword().equals("")) {
        lst.addHandler(new AuthorizationHandler(cfg.getPassword()));
    }
    lst.addHandler(new AjaxHandler(cfg.getAllowGet()));
    if(cfg.getAllowGet()) {
        lst.addHandler(new JDServerGETHandler(ctr));
    }
    lst.addHandler(new JDServerPOSTHandler(ctr));
    server.setHandler(lst);
    try {
        server.start();
    }
    catch(Exception e) {
        logger.log(new LogRecord(Level.SEVERE, e.getMessage()));
    }
}
项目:calcite-avatica    文件:HttpServer.java   
protected ConstraintSecurityHandler configureBasicAuthentication(Server server,
    ServerConnector connector, AvaticaServerConfiguration config) {
  final String[] allowedRoles = config.getAllowedRoles();
  final String realm = config.getHashLoginServiceRealm();
  final String loginServiceProperties = config.getHashLoginServiceProperties();

  HashLoginService loginService = new HashLoginService(realm, loginServiceProperties);
  server.addBean(loginService);

  return configureCommonAuthentication(server, connector, config, Constraint.__BASIC_AUTH,
      allowedRoles, new BasicAuthenticator(), null, loginService);
}
项目:EvoMaster    文件:SutController.java   
/**
 * Start the controller as a RESTful server.
 * Use the setters of this class to change the default
 * port and host.
 * <br>
 * This method is blocking until the server is initialized.
 */
public final boolean startTheControllerServer() {

    //Jersey
    ResourceConfig config = new ResourceConfig();
    config.register(JacksonFeature.class);
    config.register(new EMController(this));
    config.register(LoggingFeature.class);

    //Jetty
    controllerServer = new Server(InetSocketAddress.createUnresolved(
            getControllerHost(), getControllerPort()));

    ErrorHandler errorHandler = new ErrorHandler();
    errorHandler.setShowStacks(true);
    controllerServer.setErrorHandler(errorHandler);

    ServletHolder servlet = new ServletHolder(new ServletContainer(config));

    ServletContextHandler context = new ServletContextHandler(controllerServer,
            ControllerConstants.BASE_PATH + "/*");
    context.addServlet(servlet, "/*");


    try {
        controllerServer.start();
    } catch (Exception e) {
        SimpleLogger.error("Failed to start Jetty: " + e.getMessage());
        controllerServer.destroy();
    }

    //just make sure we start from a clean state
    newSearch();

    SimpleLogger.info("Started controller server on: " + controllerServer.getURI());

    return true;
}
项目:Backend    文件:RequestManager.java   
public void run()  {
try {
    System.out.println("Listening on Reqs...");

  Server server = new Server(Config.PORT);

  // Handler for the voting API
  ContextHandler votingContext = new ContextHandler();
  votingContext.setContextPath("/vote");
  votingContext.setHandler(new VoteHandler());
  // Handler for the stats API
  ContextHandler statContext = new ContextHandler();
  statContext.setContextPath("/stats");
  statContext.setHandler(new StatsHandler());

  // summing all the Handlers up to one
  ContextHandlerCollection contexts = new ContextHandlerCollection();
  contexts.setHandlers(new Handler[] { votingContext, statContext});
  server.setHandler(contexts);
  server.start();
  server.join();

  } catch (Exception e) {
    e.printStackTrace();
  }

}
项目:monarch    文件:JettyHelperJUnitTest.java   
@Test
public void testSetPortWithBindAddress() throws Exception {
  try {
    final Server jetty = JettyHelper.initJetty("10.123.50.1", 10480,
        SSLConfigurationFactory.getSSLConfigForComponent(SecurableCommunicationChannel.WEB));

    assertNotNull(jetty);
    assertNotNull(jetty.getConnectors()[0]);
    assertEquals(10480, ((ServerConnector) jetty.getConnectors()[0]).getPort());
  } catch (GemFireConfigException e) {
    fail(e.getMessage());
  }
}