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

The following examples show how to use org.mortbay.jetty.Server#start() . 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: Main.java    From hbase-indexer with Apache License 2.0 6 votes vote down vote up
private void startHttpServer() throws Exception {
    server = new Server();
    SelectChannelConnector selectChannelConnector = new SelectChannelConnector();
    selectChannelConnector.setPort(11060);
    server.setConnectors(new Connector[]{selectChannelConnector});

    PackagesResourceConfig packagesResourceConfig = new PackagesResourceConfig("com/ngdata/hbaseindexer/rest");

    ServletHolder servletHolder = new ServletHolder(new ServletContainer(packagesResourceConfig));
    servletHolder.setName("HBase-Indexer");


    Context context = new Context(server, "/", Context.NO_SESSIONS);
    context.addServlet(servletHolder, "/*");
    context.setContextPath("/");
    context.setAttribute("indexerModel", indexerModel);
    context.setAttribute("indexerSupervisor", indexerSupervisor);

    server.setHandler(context);
    server.start();
}
 
Example 2
Source File: CacheReplicationTestCase.java    From reladomo with Apache License 2.0 6 votes vote down vote up
protected void setupPspMithraService()
    {
        server = new Server(this.getApplicationPort1());
        Context context = new Context (server,"/",Context.SESSIONS);
        ServletHolder holder = context.addServlet(PspServlet.class, "/PspServlet");
        holder.setInitParameter("serviceInterface.MasterCacheService", "com.gs.fw.common.mithra.cache.offheap.MasterCacheService");
        holder.setInitParameter("serviceClass.MasterCacheService", "com.gs.fw.common.mithra.cache.offheap.MasterCacheServiceImpl");
        holder.setInitOrder(10);
//        System.out.println(holder.getServlet().getClass().getName());

        try
        {
            server.start();
        }
        catch (Exception e)
        {
            throw new RuntimeException("could not start server", e);
        }
        finally
        {
        }
    }
 
Example 3
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 4
Source File: EmbeddedServer.java    From xdocreport.samples with 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( 8081 );

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

    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 5
Source File: GitkitExample.java    From identity-toolkit-java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  Server server = new Server(4567);
  ServletHandler servletHandler = new ServletHandler();
  SessionHandler sessionHandler = new SessionHandler();
  sessionHandler.setHandler(servletHandler);
  server.setHandler(sessionHandler);
  servletHandler.addServletWithMapping(LoginServlet.class, "/login");
  servletHandler.addServletWithMapping(WidgetServlet.class, "/gitkit");
  servletHandler.addServletWithMapping(LoginServlet.class, "/");
  server.start();
  server.join();
}
 
Example 6
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 7
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 8
Source File: Main.java    From blog-codes with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
	Server server = new Server(PORT);
	
	// Static file handler
	Context fileContext = new Context(server, "/mxgraph", Context.SESSIONS);
	ResourceHandler fileHandler = new ResourceHandler();
	fileHandler.setResourceBase(".");
	fileContext.setHandler(fileHandler);

	// Servlets
	Context context = new Context(server, "/", Context.SESSIONS);
	context.addServlet(new ServletHolder(new Roundtrip()), "/Roundtrip");
	context.addServlet(new ServletHolder(new ServerView()), "/ServerView");
	context.addServlet(new ServletHolder(new ExportServlet()), "/Export");
	context.addServlet(new ServletHolder(new EchoServlet()), "/Echo");
	context.addServlet(new ServletHolder(new Deploy()), "/Deploy");
	context.addServlet(new ServletHolder(new Link()), "/Link");
	context.addServlet(new ServletHolder(new EmbedImage()), "/EmbedImage");
	context.addServlet(new ServletHolder(new Backend()), "/Backend");

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

	System.out.println("Go to http://localhost:" + PORT + "/");
	
	server.start();
	server.join();
}
 
Example 9
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 10
Source File: JettyServer.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
		System.setProperty("ntut.csie.ezScrum.container", "Jetty");
		
		server = new Server();
		logger = Logger.getLogger(JettyServer.class.getName());
		FileHandler handler = new FileHandler("JettyServer.log");
		logger.addHandler(handler);
		
		try {
			while (restart == true) {
				restart = false;
				XmlConfiguration configuration = new XmlConfiguration(
						new FileInputStream("JettyServer.xml"));
				configuration.configure(server);
				
/*
 * comment by liullen
 * 因為socket監聽固定的port,為了讓 jetty能夠執行多個instance,所以把重新啟動的功能註解
 * 
				// 開啟一個localhost的Socket專門接收Stop的訊息
				Thread monitor = new MonitorThread();
				monitor.start();
*/

				server.start();
				server.join();
				
			}
		} catch (Exception e) {
			logger.severe(e.getMessage());
		}
	}
 
Example 11
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 12
Source File: TestWebDelegationToken.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testExternalDelegationTokenSecretManager() throws Exception {
  DummyDelegationTokenSecretManager secretMgr
      = new DummyDelegationTokenSecretManager();
  final Server jetty = createJettyServer();
  Context context = new Context();
  context.setContextPath("/foo");
  jetty.setHandler(context);
  context.addFilter(new FilterHolder(AFilter.class), "/*", 0);
  context.addServlet(new ServletHolder(PingServlet.class), "/bar");
  try {
    secretMgr.startThreads();
    context.setAttribute(DelegationTokenAuthenticationFilter.
            DELEGATION_TOKEN_SECRET_MANAGER_ATTR, secretMgr);
    jetty.start();
    URL authURL = new URL(getJettyURL() + "/foo/bar?authenticated=foo");

    DelegationTokenAuthenticatedURL.Token token =
        new DelegationTokenAuthenticatedURL.Token();
    DelegationTokenAuthenticatedURL aUrl =
        new DelegationTokenAuthenticatedURL();

    aUrl.getDelegationToken(authURL, token, FOO_USER);
    Assert.assertNotNull(token.getDelegationToken());
    Assert.assertEquals(new Text("fooKind"),
        token.getDelegationToken().getKind());

  } finally {
    jetty.stop();
    secretMgr.stopThreads();
  }
}
 
Example 13
Source File: TestWebAppProxyServlet.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Simple http server. Server should send answer with status 200
 */
@BeforeClass
public static void start() throws Exception {
  server = new Server(0);
  Context context = new Context();
  context.setContextPath("/foo");
  server.setHandler(context);
  context.addServlet(new ServletHolder(TestServlet.class), "/bar");
  server.getConnectors()[0].setHost("localhost");
  server.start();
  originalPort = server.getConnectors()[0].getLocalPort();
  LOG.info("Running embedded servlet container at: http://localhost:"
      + originalPort);
}
 
Example 14
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 15
Source File: TestWebDelegationToken.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testFallbackToPseudoDelegationTokenAuthenticator()
    throws Exception {
  final Server jetty = createJettyServer();
  Context context = new Context();
  context.setContextPath("/foo");
  jetty.setHandler(context);
  context.addFilter(new FilterHolder(PseudoDTAFilter.class), "/*", 0);
  context.addServlet(new ServletHolder(UserServlet.class), "/bar");

  try {
    jetty.start();
    final URL url = new URL(getJettyURL() + "/foo/bar");

    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(FOO_USER);
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        DelegationTokenAuthenticatedURL.Token token =
            new DelegationTokenAuthenticatedURL.Token();
        DelegationTokenAuthenticatedURL aUrl =
            new DelegationTokenAuthenticatedURL();
        HttpURLConnection conn = aUrl.openConnection(url, token);
        Assert.assertEquals(HttpURLConnection.HTTP_OK,
            conn.getResponseCode());
        List<String> ret = IOUtils.readLines(conn.getInputStream());
        Assert.assertEquals(1, ret.size());
        Assert.assertEquals(FOO_USER, ret.get(0));

        aUrl.getDelegationToken(url, token, FOO_USER);
        Assert.assertNotNull(token.getDelegationToken());
        Assert.assertEquals(new Text("token-kind"),
            token.getDelegationToken().getKind());
        return null;
      }
    });
  } finally {
    jetty.stop();
  }
}
 
Example 16
Source File: SLSWebApp.java    From hadoop with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {
  // static files
  final ResourceHandler staticHandler = new ResourceHandler();
  staticHandler.setResourceBase("html");

  Handler handler = new AbstractHandler() {
    @Override
    public void handle(String target, HttpServletRequest request,
                       HttpServletResponse response, int dispatch) {
      try{
        // timeunit
        int timeunit = 1000;   // second, divide millionsecond / 1000
        String timeunitLabel = "second";
        if (request.getParameter("u")!= null &&
                request.getParameter("u").equalsIgnoreCase("m")) {
          timeunit = 1000 * 60;
          timeunitLabel = "minute";
        }

        // http request
        if (target.equals("/")) {
          printPageIndex(request, response);
        } else if (target.equals("/simulate")) {
          printPageSimulate(request, response, timeunit, timeunitLabel);
        } else if (target.equals("/track")) {
          printPageTrack(request, response, timeunit, timeunitLabel);
        } else
          // js/css request
          if (target.startsWith("/js") || target.startsWith("/css")) {
            response.setCharacterEncoding("utf-8");
            staticHandler.handle(target, request, response, dispatch);
          } else
            // json request
            if (target.equals("/simulateMetrics")) {
              printJsonMetrics(request, response);
            } else if (target.equals("/trackMetrics")) {
              printJsonTrack(request, response);
            }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  };

  server = new Server(port);
  server.setHandler(handler);

  server.start();
}
 
Example 17
Source File: JettyHttpServer.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler){
        super(url, handler);

        // modified by lishen
        this.url = url;
        // TODO we should leave this setting to slf4j
        Log.setLog(new StdErrLog());
        Log.getLog().setDebugEnabled(false);

        DispatcherServlet.addHttpHandler(url.getPort(), handler);

        int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setDaemon(true);
        threadPool.setMaxThreads(threads);
        threadPool.setMinThreads(threads);

        SelectChannelConnector connector = new SelectChannelConnector();
        if (! url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) {
            connector.setHost(url.getHost());
        }
        connector.setPort(url.getPort());

        server = new Server();
        server.setThreadPool(threadPool);
        server.addConnector(connector);

        ServletHandler servletHandler = new ServletHandler();
        ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
        servletHolder.setInitOrder(2);

        // modified by lishen
        // dubbo's original impl can't support the use of ServletContext
//        server.addHandler(servletHandler);
        // TODO Context.SESSIONS is the best option here?
        Context context = new Context(server, "/", Context.SESSIONS);
        context.setServletHandler(servletHandler);
        ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext());

        try {
            server.start();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: "
                                            + e.getMessage(), e);
        }
    }
 
Example 18
Source File: TestWebDelegationToken.java    From big-c with Apache License 2.0 4 votes vote down vote up
private void testDelegationTokenAuthenticatedURLWithNoDT(
    Class<? extends Filter> filterClass)  throws Exception {
  final Server jetty = createJettyServer();
  Context context = new Context();
  context.setContextPath("/foo");
  jetty.setHandler(context);
  context.addFilter(new FilterHolder(filterClass), "/*", 0);
  context.addServlet(new ServletHolder(UserServlet.class), "/bar");

  try {
    jetty.start();
    final URL url = new URL(getJettyURL() + "/foo/bar");

    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(FOO_USER);
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        DelegationTokenAuthenticatedURL.Token token =
            new DelegationTokenAuthenticatedURL.Token();
        DelegationTokenAuthenticatedURL aUrl =
            new DelegationTokenAuthenticatedURL();
        HttpURLConnection conn = aUrl.openConnection(url, token);
        Assert.assertEquals(HttpURLConnection.HTTP_OK,
            conn.getResponseCode());
        List<String> ret = IOUtils.readLines(conn.getInputStream());
        Assert.assertEquals(1, ret.size());
        Assert.assertEquals(FOO_USER, ret.get(0));

        try {
          aUrl.getDelegationToken(url, token, FOO_USER);
          Assert.fail();
        } catch (AuthenticationException ex) {
          Assert.assertTrue(ex.getMessage().contains(
              "delegation token operation"));
        }
        return null;
      }
    });
  } finally {
    jetty.stop();
  }
}
 
Example 19
Source File: JettyMain.java    From fraud-detection-tutorial with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {

    if (args.length == 0) {
      System.out.println("JettyMain {port} {zookeeperQuorum}");
    }
    try {
      Configuration config = HBaseConfiguration.create();
      config.addResource("/etc/hbase/conf/hbase-site.xml");
      config.set(HConstants.ZOOKEEPER_QUORUM, args[1]);
      //config.set(HConstants.ZOOKEEPER_CLIENT_PORT, "2181");

      HBaseService hbaseService = new HBaseService(config);

      Server server = new Server(Integer.parseInt(args[0]));

      WebAppContext webapp = new WebAppContext();
      webapp.setContextPath("/fe");
      webapp.setResourceBase("./webapp");
      webapp.setWelcomeFiles(new String[]{"index.html"});

      Context servletContext = new Context();
      servletContext.setContextPath("/be");
      servletContext.addServlet(GraphTsvServlet.class, "/graph.tsv");
      servletContext.addServlet(FileGetterServlet.class, "/file/*");
      servletContext.addServlet(NodeAutoCompleteServlet.class, "/auto/*");
      servletContext.addServlet(GraphNodeJsonServlet.class, "/nodeGraph/*");
      servletContext.addServlet(NodeHomeDashBoardInfoServlet.class, "/nodeDash/*");

      server.setHandlers(new Handler[]{webapp, servletContext});

      System.out.println("-");

      GraphTsvServlet.setHBaseService(hbaseService);
      FileGetterServlet.setHBaseService(hbaseService);
      NodeAutoCompleteServlet.setHBaseService(hbaseService);
      GraphNodeJsonServlet.setHBaseService(hbaseService);
      NodeHomeDashBoardInfoServlet.setHBaseService(hbaseService);

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

    } finally {
      System.out.println("Step 7: Shut Down");
    }
  }
 
Example 20
Source File: TestWebDelegationToken.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test
public void testHttpUGI() throws Exception {
  final Server jetty = createJettyServer();
  Context context = new Context();
  context.setContextPath("/foo");
  jetty.setHandler(context);
  context.addFilter(new FilterHolder(PseudoDTAFilter.class), "/*", 0);
  context.addServlet(new ServletHolder(UGIServlet.class), "/bar");

  try {
    jetty.start();
    final URL url = new URL(getJettyURL() + "/foo/bar");

    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(FOO_USER);
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        DelegationTokenAuthenticatedURL.Token token =
            new DelegationTokenAuthenticatedURL.Token();
        DelegationTokenAuthenticatedURL aUrl =
            new DelegationTokenAuthenticatedURL();

        // user foo
        HttpURLConnection conn = aUrl.openConnection(url, token);
        Assert.assertEquals(HttpURLConnection.HTTP_OK,
            conn.getResponseCode());
        List<String> ret = IOUtils.readLines(conn.getInputStream());
        Assert.assertEquals(1, ret.size());
        Assert.assertEquals("remoteuser=" + FOO_USER+ ":ugi=" + FOO_USER, 
            ret.get(0));

        // user ok-user via proxyuser foo
        conn = aUrl.openConnection(url, token, OK_USER);
        Assert.assertEquals(HttpURLConnection.HTTP_OK,
            conn.getResponseCode());
        ret = IOUtils.readLines(conn.getInputStream());
        Assert.assertEquals(1, ret.size());
        Assert.assertEquals("realugi=" + FOO_USER +":remoteuser=" + OK_USER + 
                ":ugi=" + OK_USER, ret.get(0));

        return null;
      }
    });
  } finally {
    jetty.stop();
  }
}