Java Code Examples for org.mortbay.jetty.Server#addHandler()

The following examples show how to use org.mortbay.jetty.Server#addHandler() . 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: JettyLauncher.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(PORT);
    server.addConnector(connector);
    server.setStopAtShutdown(true);

    // the orders of handlers is very important!
    ContextHandler contextHandler = new ContextHandler();
    contextHandler.setContextPath("/reports");
    contextHandler.setResourceBase("./reports/");
    contextHandler.addHandler(new ResourceHandler());
    server.addHandler(contextHandler);

    server.addHandler(new WebAppContext("webapp", "/nextreports-server"));

    long t = System.currentTimeMillis();
    server.start();
    t = System.currentTimeMillis() - t;
    String version = server.getClass().getPackage().getImplementationVersion();
    System.out.println("Started Jetty Server " + version + " on port " + PORT + " in " + t / 1000 + "s");
    
    server.join();
}
 
Example 2
Source File: TestHTestCase.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
@TestJetty
public void testJetty() throws Exception {
  Context context = new Context();
  context.setContextPath("/");
  context.addServlet(MyServlet.class, "/bar");
  Server server = TestJettyHelper.getJettyServer();
  server.addHandler(context);
  server.start();
  URL url = new URL(TestJettyHelper.getJettyURL(), "/bar");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  assertEquals(reader.readLine(), "foo");
  reader.close();
}
 
Example 3
Source File: TestHFSTestCase.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
@TestJetty
public void testJetty() throws Exception {
  Context context = new Context();
  context.setContextPath("/");
  context.addServlet(MyServlet.class, "/bar");
  Server server = TestJettyHelper.getJettyServer();
  server.addHandler(context);
  server.start();
  URL url = new URL(TestJettyHelper.getJettyURL(), "/bar");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  assertEquals(reader.readLine(), "foo");
  reader.close();
}
 
Example 4
Source File: TestHTestCase.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
@TestJetty
public void testJetty() throws Exception {
  Context context = new Context();
  context.setContextPath("/");
  context.addServlet(MyServlet.class, "/bar");
  Server server = TestJettyHelper.getJettyServer();
  server.addHandler(context);
  server.start();
  URL url = new URL(TestJettyHelper.getJettyURL(), "/bar");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  assertEquals(reader.readLine(), "foo");
  reader.close();
}
 
Example 5
Source File: TestHFSTestCase.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
@TestJetty
public void testJetty() throws Exception {
  Context context = new Context();
  context.setContextPath("/");
  context.addServlet(MyServlet.class, "/bar");
  Server server = TestJettyHelper.getJettyServer();
  server.addHandler(context);
  server.start();
  URL url = new URL(TestJettyHelper.getJettyURL(), "/bar");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  assertEquals(reader.readLine(), "foo");
  reader.close();
}
 
Example 6
Source File: TestProtocolHttpClient.java    From nutch-htmlunit with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {

    ContextHandler context = new ContextHandler();
    context.setContextPath("/");
    context.setResourceBase(RES_DIR);
    ServletHandler sh = new ServletHandler();
    sh.addServlet("org.apache.jasper.servlet.JspServlet", "*.jsp");
    context.addHandler(sh);
    context.addHandler(new SessionHandler());

    server = new Server();
    server.addHandler(context);

    conf = new Configuration();
    conf.addResource("nutch-default.xml");
    conf.addResource("nutch-site-test.xml");
    
    http = new Http();
    http.setConf(conf);
  }
 
Example 7
Source File: TestProtocolHttpClient.java    From anthelion with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {

    ContextHandler context = new ContextHandler();
    context.setContextPath("/");
    context.setResourceBase(RES_DIR);
    ServletHandler sh = new ServletHandler();
    sh.addServlet("org.apache.jasper.servlet.JspServlet", "*.jsp");
    context.addHandler(sh);
    context.addHandler(new SessionHandler());

    server = new Server();
    server.addHandler(context);

    conf = new Configuration();
    conf.addResource("nutch-default.xml");
    conf.addResource("nutch-site-test.xml");
    
    http = new Http();
    http.setConf(conf);
  }
 
Example 8
Source File: HttpServer.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
/**
 * Create a status server on the given port.
 * The jsp scripts are taken from src/webapps/<name>.
 * @param name The name of the server
 * @param port The port to use on the server
 * @param findPort whether the server should start at the given port and 
 *        increment by 1 until it finds a free port.
 * @param conf Configuration 
 */
public HttpServer(String name, String bindAddress, int port,
    boolean findPort, Configuration conf) throws IOException {
  webServer = new Server();
  this.findPort = findPort;

  listener = createBaseListener(conf);
  listener.setHost(bindAddress);
  listener.setPort(port);
  webServer.addConnector(listener);

  webServer.setThreadPool(new QueuedThreadPool());

  final String appDir = getWebAppsPath();
  ContextHandlerCollection contexts = new ContextHandlerCollection();
  webServer.setHandler(contexts);

  webAppContext = new WebAppContext();
  webAppContext.setContextPath("/");
  webAppContext.setWar(appDir + "/" + name);
  webServer.addHandler(webAppContext);

  addDefaultApps(contexts, appDir);

  final FilterInitializer[] initializers = getFilterInitializers(conf); 
  if (initializers != null) {
    for(FilterInitializer c : initializers) {
      c.initFilter(this);
    }
  }
  addDefaultServlets();
}
 
Example 9
Source File: HermesClassLoaderMetaServer.java    From hermes with Apache License 2.0 5 votes vote down vote up
public void startServer() throws Exception {
	Server server = new Server(port);
	WebAppContext context = new ResourceFallbackWebAppContext();

	configure(context);
	ClassLoader parent = new HermesClassLoader(((URLClassLoader) this.getClass().getClassLoader()).getURLs(),
			  "com.ctrip.", "com.dianping.", "org.unidal.");

	context.setClassLoader(new WebAppClassLoader(parent, context));
	context.addServlet(new ServletHolder(new WebModuleServlet(m_resource)), "/");


	// find LoadMocksListener with HermesClassLoader
	Class clazz = parent.loadClass("com.ctrip.hermes.metaserver.fulltest.LoadMocksListener");
	Object obj = clazz.newInstance();
	Field field = clazz.getDeclaredField("port");
	field.setAccessible(true);
	field.set(obj, port);
	context.addEventListener((EventListener) obj);

	server.addHandler(context);
	try {
		server.start();
	} catch (java.net.BindException e) {
		log.warn("CustomClassLoaderMetaServer[localhost:{}] start fail, BindException.", port);
	}

	postConfigure(context);

	m_server = server;
}
 
Example 10
Source File: GenerateToken.java    From socialauth with MIT License 5 votes vote down vote up
private void startServer() throws Exception {
	server = new Server(port);
	for (Connector c : server.getConnectors()) {
		c.setHost(host);
	}

	server.addHandler(new CallbackHandler());
	try {
		server.start();
	} catch (Exception e) {
		throw new IOException(e);
	}

}
 
Example 11
Source File: CrawlDBTestUtil.java    From nutch-htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JettyServer with one static root context
 * 
 * @param port port to listen to
 * @param staticContent folder where static content lives
 * @throws UnknownHostException 
 */
public static Server getServer(int port, String staticContent) throws UnknownHostException{
  Server webServer = new org.mortbay.jetty.Server();
  SocketConnector listener = new SocketConnector();
  listener.setPort(port);
  listener.setHost("127.0.0.1");
  webServer.addConnector(listener);
  ContextHandler staticContext = new ContextHandler();
  staticContext.setContextPath("/");
  staticContext.setResourceBase(staticContent);
  staticContext.addHandler(new ResourceHandler());
  webServer.addHandler(staticContext);
  return webServer;
}
 
Example 12
Source File: HttpServer.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Create a status server on the given port.
 * The jsp scripts are taken from src/webapps/<name>.
 * @param name The name of the server
 * @param port The port to use on the server
 * @param findPort whether the server should start at the given port and 
 *        increment by 1 until it finds a free port.
 * @param conf Configuration 
 */
public HttpServer(String name, String bindAddress, int port,
    boolean findPort, Configuration conf) throws IOException {
  webServer = new Server();
  this.findPort = findPort;

  listener = createBaseListener(conf);
  listener.setHost(bindAddress);
  listener.setPort(port);
  webServer.addConnector(listener);

  int maxThreads = conf.getInt(HTTP_MAX_THREADS, -1);
  // If HTTP_MAX_THREADS is not configured, QueueThreadPool() will use the 
  // default value (currently 254).
  QueuedThreadPool threadPool = maxThreads == -1 ?
      new QueuedThreadPool() : new QueuedThreadPool(maxThreads);
  webServer.setThreadPool(threadPool);

  final String appDir = getWebAppsPath();
  ContextHandlerCollection contexts = new ContextHandlerCollection();
  webServer.setHandler(contexts);

  webAppContext = new WebAppContext();
  webAppContext.setContextPath("/");
  webAppContext.setWar(appDir + "/" + name);
  webAppContext.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, conf);
  webServer.addHandler(webAppContext);

  addDefaultApps(contexts, appDir);

  addGlobalFilter("safety", QuotingInputFilter.class.getName(), null);
  final FilterInitializer[] initializers = getFilterInitializers(conf); 
  if (initializers != null) {
    for(FilterInitializer c : initializers) {
      c.initFilter(this);
    }
  }
  addDefaultServlets();
}
 
Example 13
Source File: JettyContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 14
Source File: CrawlDBTestUtil.java    From anthelion with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JettyServer with one static root context
 * 
 * @param port port to listen to
 * @param staticContent folder where static content lives
 * @throws UnknownHostException 
 */
public static Server getServer(int port, String staticContent) throws UnknownHostException{
  Server webServer = new org.mortbay.jetty.Server();
  SocketConnector listener = new SocketConnector();
  listener.setPort(port);
  listener.setHost("127.0.0.1");
  webServer.addConnector(listener);
  ContextHandler staticContext = new ContextHandler();
  staticContext.setContextPath("/");
  staticContext.setResourceBase(staticContent);
  staticContext.addHandler(new ResourceHandler());
  webServer.addHandler(staticContext);
  return webServer;
}
 
Example 15
Source File: LocalServerWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Before
public void setupLocalServer() throws Exception {

    // Set up a local Jetty HTTP server
    Server server = new Server();
    server.addConnector(new SocketConnector());
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase("src/test/resources/server");
    server.addHandler(resourceHandler);
    server.start();

    // The server will have a random port assigned, so capture that
    localPort = server.getConnectors()[0].getLocalPort();
}
 
Example 16
Source File: JettyContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 17
Source File: JettyContainer.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 18
Source File: JettyContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void start() {
    String serverPort = ConfigUtils.getProperty(JETTY_PORT);
    int port;
    if (serverPort == null || serverPort.length() == 0) {
        port = DEFAULT_JETTY_PORT;
    } else {
        port = Integer.parseInt(serverPort);
    }
    connector = new SelectChannelConnector();
    connector.setPort(port);
    ServletHandler handler = new ServletHandler();
    
    String resources = ConfigUtils.getProperty(JETTY_DIRECTORY);
    if (resources != null && resources.length() > 0) {
        FilterHolder resourceHolder = handler.addFilterWithMapping(ResourceFilter.class, "/*", Handler.DEFAULT);
        resourceHolder.setInitParameter("resources", resources);
    }
    
    ServletHolder pageHolder = handler.addServletWithMapping(PageServlet.class, "/*");
    pageHolder.setInitParameter("pages", ConfigUtils.getProperty(JETTY_PAGES));
    pageHolder.setInitOrder(2);
    
    Server server = new Server();
    server.addConnector(connector);
    server.addHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + NetUtils.getLocalHost() + ":" + port + ", cause: " + e.getMessage(), e);
    }
}
 
Example 19
Source File: XTest.java    From vxquery with Apache License 2.0 4 votes vote down vote up
void init() throws Exception {
    finishCount = 0;
    if (opts.threads <= 0) {
        opts.threads = 1;
    }
    eSvc = Executors.newFixedThreadPool(opts.threads);
    if (opts.port > 0) {
        ServletReporterImpl servletHandler = new ServletReporterImpl();
        reporters.add(servletHandler);
        server = new Server(opts.port);
        server.addHandler(servletHandler);
        server.start();
    }
    if (opts.htmlReport != null) {
        reporters.add(new HTMLFileReporterImpl(new File(opts.htmlReport)));
    }
    if (opts.xmlReport != null) {
        reporters.add(new XMLFileReporterImpl(new File(opts.xmlReport)));
    }
    if (opts.diffable != null) {
        reporters.add(new LineFileReporterImpl(new File(opts.diffable)));
    }
    reporters.add(new ResultReporter() {
        @Override
        public void close() {
        }

        @Override
        public void reportResult(TestCaseResult result) {
            synchronized (XTest.this) {
                finishCount++;
                if (finishCount >= count) {
                    XTest.this.notifyAll();
                }
            }
        }
    });
    TestClusterUtil.startCluster(opts, TestClusterUtil.localClusterUtil);
    trf = new TestRunnerFactory(opts);
    trf.registerReporters(reporters);
    TestCaseFactory tcf = new TestCaseFactory(trf, eSvc, opts);
    count = tcf.process();
}
 
Example 20
Source File: SubsonicDeployer.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
private void deployWebApp() {
    try {
        Server server = new Server();
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setMaxIdleTime(MAX_IDLE_TIME_MILLIS);
        connector.setHeaderBufferSize(HEADER_BUFFER_SIZE);
        connector.setHost(getHost());
        connector.setPort(getPort());
        if (isHttpsEnabled()) {
            connector.setConfidentialPort(getHttpsPort());
        }
        server.addConnector(connector);

        if (isHttpsEnabled()) {
            SslSocketConnector sslConnector = new SslSocketConnector();
            sslConnector.setMaxIdleTime(MAX_IDLE_TIME_MILLIS);
            sslConnector.setHeaderBufferSize(HEADER_BUFFER_SIZE);
            sslConnector.setHost(getHost());
            sslConnector.setPort(getHttpsPort());
            sslConnector.setKeystore(System.getProperty("subsonic.ssl.keystore", getClass().getResource("/subsonic.keystore").toExternalForm()));
            sslConnector.setPassword(System.getProperty("subsonic.ssl.password", "subsonic"));
            server.addConnector(sslConnector);
        }

        WebAppContext context = new WebAppContext();
        context.setTempDirectory(getJettyDirectory());
        context.setContextPath(getContextPath());
        context.setWar(getWar());
        context.setOverrideDescriptor("/web-jetty.xml");

        if (isHttpsEnabled()) {

            // Allow non-https for streaming and cover art (for Chromecast, UPnP, Sonos etc)
            context.getSecurityHandler().setConstraintMappings(new ConstraintMapping[]{
                    createConstraintMapping("/stream", Constraint.DC_NONE),
                    createConstraintMapping("/coverArt.view", Constraint.DC_NONE),
                    createConstraintMapping("/ws/*", Constraint.DC_NONE),
                    createConstraintMapping("/sonos/*", Constraint.DC_NONE),
                    createConstraintMapping("/", Constraint.DC_CONFIDENTIAL)
            });
        }

        server.addHandler(context);
        server.start();

        System.err.println("Subsonic running on: " + getUrl());
        if (isHttpsEnabled()) {
            System.err.println("                and: " + getHttpsUrl());
        }

    } catch (Throwable x) {
        x.printStackTrace();
        exception = x;
    }
}