Search in sources :

Example 96 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class TestJNDI method testThreadContextClassloaderAndCurrentContext.

@Test
public void testThreadContextClassloaderAndCurrentContext() throws Exception {
    //create a jetty context, and start it so that its classloader it created
    //and it is the current context
    ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
    ContextHandler ch = new ContextHandler();
    URLClassLoader chLoader = new URLClassLoader(new URL[0], currentLoader);
    ch.setClassLoader(chLoader);
    Server server = new Server();
    HandlerList hl = new HandlerList();
    server.setHandler(hl);
    hl.addHandler(ch);
    //Create another one
    ContextHandler ch2 = new ContextHandler();
    URLClassLoader ch2Loader = new URLClassLoader(new URL[0], currentLoader);
    ch2.setClassLoader(ch2Loader);
    hl.addHandler(ch2);
    try {
        ch.setContextPath("/ch");
        ch.addEventListener(new ServletContextListener() {

            private Context comp;

            private Object testObj = new Object();

            public void contextInitialized(ServletContextEvent sce) {
                try {
                    InitialContext initCtx = new InitialContext();
                    Context java = (Context) initCtx.lookup("java:");
                    assertNotNull(java);
                    comp = (Context) initCtx.lookup("java:comp");
                    assertNotNull(comp);
                    Context env = ((Context) comp).createSubcontext("env");
                    assertNotNull(env);
                    env.bind("ch", testObj);
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }

            public void contextDestroyed(ServletContextEvent sce) {
                try {
                    assertNotNull(comp);
                    assertEquals(testObj, comp.lookup("env/ch"));
                    comp.destroySubcontext("env");
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        });
        //Starting the context makes it current and creates a classloader for it
        ch.start();
        ch2.setContextPath("/ch2");
        ch2.addEventListener(new ServletContextListener() {

            private Context comp;

            private Object testObj = new Object();

            public void contextInitialized(ServletContextEvent sce) {
                try {
                    InitialContext initCtx = new InitialContext();
                    comp = (Context) initCtx.lookup("java:comp");
                    assertNotNull(comp);
                    //another context's bindings should not be visible
                    Context env = ((Context) comp).createSubcontext("env");
                    try {
                        env.lookup("ch");
                        fail("java:comp/env visible from another context!");
                    } catch (NameNotFoundException e) {
                    //expected
                    }
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }

            public void contextDestroyed(ServletContextEvent sce) {
                try {
                    assertNotNull(comp);
                    comp.destroySubcontext("env");
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        });
        //make the new context the current one
        ch2.start();
    } finally {
        ch.stop();
        ch2.stop();
        Thread.currentThread().setContextClassLoader(currentLoader);
    }
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) NamingContext(org.eclipse.jetty.jndi.NamingContext) Server(org.eclipse.jetty.server.Server) ServletContextListener(javax.servlet.ServletContextListener) NameNotFoundException(javax.naming.NameNotFoundException) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException) NameNotFoundException(javax.naming.NameNotFoundException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) ServletContextEvent(javax.servlet.ServletContextEvent) Test(org.junit.Test)

Example 97 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class Runner method configure.

/**
     * Configure a jetty instance and deploy the webapps presented as args
     *
     * @param args the command line arguments
     * @throws Exception if unable to configure
     */
public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
        if ("--lib".equals(args[i])) {
            try (Resource lib = Resource.newResource(args[++i])) {
                if (!lib.exists() || !lib.isDirectory())
                    usage("No such lib directory " + lib);
                _classpath.addJars(lib);
            }
        } else if ("--jar".equals(args[i])) {
            try (Resource jar = Resource.newResource(args[++i])) {
                if (!jar.exists() || jar.isDirectory())
                    usage("No such jar " + jar);
                _classpath.addPath(jar);
            }
        } else if ("--classes".equals(args[i])) {
            try (Resource classes = Resource.newResource(args[++i])) {
                if (!classes.exists() || !classes.isDirectory())
                    usage("No such classes directory " + classes);
                _classpath.addPath(classes);
            }
        } else if (args[i].startsWith("--"))
            i++;
    }
    initClassLoader();
    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);
    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;
    boolean runnerServerInitialized = false;
    for (int i = 0; i < args.length; i++) {
        switch(args[i]) {
            case "--port":
                port = Integer.parseInt(args[++i]);
                break;
            case "--host":
                host = args[++i];
                break;
            case "--stop-port":
                stopPort = Integer.parseInt(args[++i]);
                break;
            case "--stop-key":
                stopKey = args[++i];
                break;
            case "--log":
                _logFile = args[++i];
                break;
            case "--out":
                String outFile = args[++i];
                PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
                LOG.info("Redirecting stderr/stdout to " + outFile);
                System.setErr(out);
                System.setOut(out);
                break;
            case "--path":
                contextPath = args[++i];
                contextPathSet = true;
                break;
            case "--config":
                if (_configFiles == null)
                    _configFiles = new ArrayList<>();
                _configFiles.add(args[++i]);
                break;
            case "--lib":
                //skip
                ++i;
                break;
            case "--jar":
                //skip
                ++i;
                break;
            case "--classes":
                //skip
                ++i;
                break;
            case "--stats":
                _enableStats = true;
                _statsPropFile = args[++i];
                _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
                break;
            default:
                if (// log handlers not registered, server maybe not created, etc
                !runnerServerInitialized) {
                    if (// server not initialized yet
                    _server == null) {
                        // build the server
                        _server = new Server();
                    }
                    //apply jetty config files if there are any
                    if (_configFiles != null) {
                        for (String cfg : _configFiles) {
                            try (Resource resource = Resource.newResource(cfg)) {
                                XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                                xmlConfiguration.configure(_server);
                            }
                        }
                    }
                    //check that everything got configured, and if not, make the handlers
                    HandlerCollection handlers = (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
                    if (handlers == null) {
                        handlers = new HandlerCollection();
                        _server.setHandler(handlers);
                    }
                    //check if contexts already configured
                    _contexts = (ContextHandlerCollection) handlers.getChildHandlerByClass(ContextHandlerCollection.class);
                    if (_contexts == null) {
                        _contexts = new ContextHandlerCollection();
                        prependHandler(_contexts, handlers);
                    }
                    if (_enableStats) {
                        //if no stats handler already configured
                        if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                            StatisticsHandler statsHandler = new StatisticsHandler();
                            Handler oldHandler = _server.getHandler();
                            statsHandler.setHandler(oldHandler);
                            _server.setHandler(statsHandler);
                            ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                            statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                            statsContext.setSessionHandler(new SessionHandler());
                            if (_statsPropFile != null) {
                                HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile);
                                Constraint constraint = new Constraint();
                                constraint.setName("Admin Only");
                                constraint.setRoles(new String[] { "admin" });
                                constraint.setAuthenticate(true);
                                ConstraintMapping cm = new ConstraintMapping();
                                cm.setConstraint(constraint);
                                cm.setPathSpec("/*");
                                ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                                securityHandler.setLoginService(loginService);
                                securityHandler.setConstraintMappings(Collections.singletonList(cm));
                                securityHandler.setAuthenticator(new BasicAuthenticator());
                                statsContext.setSecurityHandler(securityHandler);
                            }
                        }
                    }
                    //ensure a DefaultHandler is present
                    if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
                        handlers.addHandler(new DefaultHandler());
                    }
                    //ensure a log handler is present
                    _logHandler = (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
                    if (_logHandler == null) {
                        _logHandler = new RequestLogHandler();
                        handlers.addHandler(_logHandler);
                    }
                    //check a connector is configured to listen on
                    Connector[] connectors = _server.getConnectors();
                    if (connectors == null || connectors.length == 0) {
                        ServerConnector connector = new ServerConnector(_server);
                        connector.setPort(port);
                        if (host != null)
                            connector.setHost(host);
                        _server.addConnector(connector);
                        if (_enableStats)
                            connector.addBean(new ConnectionStatistics());
                    } else {
                        if (_enableStats) {
                            for (Connector connector : connectors) {
                                ((AbstractConnector) connector).addBean(new ConnectionStatistics());
                            }
                        }
                    }
                    runnerServerInitialized = true;
                }
                // Create a context
                try (Resource ctx = Resource.newResource(args[i])) {
                    if (!ctx.exists())
                        usage("Context '" + ctx + "' does not exist");
                    if (contextPathSet && !(contextPath.startsWith("/")))
                        contextPath = "/" + contextPath;
                    // Configure the context
                    if (!ctx.isDirectory() && ctx.toString().toLowerCase(Locale.ENGLISH).endsWith(".xml")) {
                        // It is a context config file
                        XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
                        xmlConfiguration.getIdMap().put("Server", _server);
                        ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
                        if (contextPathSet)
                            handler.setContextPath(contextPath);
                        _contexts.addHandler(handler);
                        String containerIncludeJarPattern = (String) handler.getAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN);
                        if (containerIncludeJarPattern == null)
                            containerIncludeJarPattern = __containerIncludeJarPattern;
                        else {
                            if (!containerIncludeJarPattern.contains(__containerIncludeJarPattern)) {
                                containerIncludeJarPattern = containerIncludeJarPattern + (StringUtil.isBlank(containerIncludeJarPattern) ? "" : "|") + __containerIncludeJarPattern;
                            }
                        }
                        handler.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern);
                        //check the configurations, if not explicitly set up, then configure all of them
                        if (handler instanceof WebAppContext) {
                            WebAppContext wac = (WebAppContext) handler;
                            if (wac.getConfigurationClasses() == null || wac.getConfigurationClasses().length == 0)
                                wac.setConfigurationClasses(__plusConfigurationClasses);
                        }
                    } else {
                        // assume it is a WAR file
                        WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
                        webapp.setConfigurationClasses(__plusConfigurationClasses);
                        webapp.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, __containerIncludeJarPattern);
                    }
                }
                //reset
                contextPathSet = false;
                contextPath = __defaultContextPath;
                break;
        }
    }
    if (_server == null)
        usage("No Contexts defined");
    _server.setStopAtShutdown(true);
    switch((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
        case 1:
            usage("Must specify --stop-key when --stop-port is specified");
            break;
        case 2:
            usage("Must specify --stop-port when --stop-key is specified");
            break;
        case 3:
            ShutdownMonitor monitor = ShutdownMonitor.getInstance();
            monitor.setPort(stopPort);
            monitor.setKey(stopKey);
            monitor.setExitVm(true);
            break;
    }
    if (_logFile != null) {
        NCSARequestLog requestLog = new NCSARequestLog(_logFile);
        requestLog.setExtended(false);
        _logHandler.setRequestLog(requestLog);
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) AbstractConnector(org.eclipse.jetty.server.AbstractConnector) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) ShutdownMonitor(org.eclipse.jetty.server.ShutdownMonitor) Server(org.eclipse.jetty.server.Server) ConnectionStatistics(org.eclipse.jetty.io.ConnectionStatistics) Constraint(org.eclipse.jetty.util.security.Constraint) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ArrayList(java.util.ArrayList) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) RolloverFileOutputStream(org.eclipse.jetty.util.RolloverFileOutputStream) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) ServerConnector(org.eclipse.jetty.server.ServerConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) HashLoginService(org.eclipse.jetty.security.HashLoginService) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) PrintStream(java.io.PrintStream) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Resource(org.eclipse.jetty.util.resource.Resource) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) Constraint(org.eclipse.jetty.util.security.Constraint) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) StatisticsServlet(org.eclipse.jetty.servlet.StatisticsServlet) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) AbstractConnector(org.eclipse.jetty.server.AbstractConnector)

Example 98 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class ConstraintTest method startServer.

@Before
public void startServer() {
    _server = new Server();
    _connector = new LocalConnector(_server);
    _config = _connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    _server.setConnectors(new Connector[] { _connector });
    ContextHandler _context = new ContextHandler();
    SessionHandler _session = new SessionHandler();
    TestLoginService _loginService = new TestLoginService(TEST_REALM);
    _loginService.putUser("user0", new Password("password"), new String[] {});
    _loginService.putUser("user", new Password("password"), new String[] { "user" });
    _loginService.putUser("user2", new Password("password"), new String[] { "user" });
    _loginService.putUser("admin", new Password("password"), new String[] { "user", "administrator" });
    _loginService.putUser("user3", new Password("password"), new String[] { "foo" });
    _context.setContextPath("/ctx");
    _server.setHandler(_context);
    _context.setHandler(_session);
    _server.addBean(_loginService);
    _security = new ConstraintSecurityHandler();
    _session.setHandler(_security);
    RequestHandler _handler = new RequestHandler();
    _security.setHandler(_handler);
    _security.setConstraintMappings(getConstraintMappings(), getKnownRoles());
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) Server(org.eclipse.jetty.server.Server) LocalConnector(org.eclipse.jetty.server.LocalConnector) Password(org.eclipse.jetty.util.security.Password) Before(org.junit.Before)

Example 99 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class BadRequestLogHandlerTest method testLogHandler.

@Test(timeout = 4000)
public void testLogHandler() throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.setConnectors(new Connector[] { connector });
    CaptureLog captureLog = new CaptureLog();
    RequestLogHandler requestLog = new RequestLogHandler();
    requestLog.setRequestLog(captureLog);
    requestLog.setHandler(new HelloHandler());
    server.setHandler(requestLog);
    try {
        server.start();
        String host = connector.getHost();
        if (host == null) {
            host = "localhost";
        }
        InetAddress destAddr = InetAddress.getByName(host);
        int port = connector.getLocalPort();
        SocketAddress endpoint = new InetSocketAddress(destAddr, port);
        Socket socket = new Socket();
        socket.setSoTimeout(1000);
        socket.connect(endpoint);
        try (OutputStream out = socket.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            InputStream in = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
            StringReader request = new StringReader(requestHeader);
            IO.copy(request, writer);
            writer.flush();
            StringWriter response = new StringWriter();
            IO.copy(reader, response);
            LOG.info("Response: {}", response);
        } finally {
            socket.close();
        }
        assertRequestLog(captureLog);
    } finally {
        server.stop();
    }
}
Also used : Server(org.eclipse.jetty.server.Server) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ServerConnector(org.eclipse.jetty.server.ServerConnector) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) OutputStreamWriter(java.io.OutputStreamWriter) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) Socket(java.net.Socket) Test(org.junit.Test)

Example 100 with Server

use of org.eclipse.jetty.server.Server in project jetty.project by eclipse.

the class ResourceHandlerTest method setUp.

@BeforeClass
public static void setUp() throws Exception {
    File dir = MavenTestingUtils.getTargetFile("test-classes/simple");
    File bigger = new File(dir, "bigger.txt");
    File big = new File(dir, "big.txt");
    try (OutputStream out = new FileOutputStream(bigger)) {
        for (int i = 0; i < 100; i++) {
            try (InputStream in = new FileInputStream(big)) {
                IO.copy(in, out);
            }
        }
    }
    bigger.deleteOnExit();
    // determine how the SCM of choice checked out the big.txt EOL
    // we can't just use whatever is the OS default.
    // because, for example, a windows system using git can be configured for EOL handling using
    // local, remote, file lists, patterns, etc, rendering assumptions about the OS EOL choice
    // wrong for unit tests.
    LN = System.getProperty("line.separator");
    try (BufferedReader reader = Files.newBufferedReader(big.toPath(), StandardCharsets.UTF_8)) {
        // a buffer large enough to capture at least 1 EOL
        char[] cbuf = new char[128];
        reader.read(cbuf);
        String sample = new String(cbuf);
        if (sample.contains("\r\n")) {
            LN = "\r\n";
        } else if (sample.contains("\n\r")) {
            LN = "\n\r";
        } else {
            LN = "\n";
        }
    }
    _server = new Server();
    _config = new HttpConfiguration();
    _config.setOutputBufferSize(2048);
    _connector = new ServerConnector(_server, new HttpConnectionFactory(_config));
    _local = new LocalConnector(_server);
    _server.setConnectors(new Connector[] { _connector, _local });
    _resourceHandler = new ResourceHandler();
    _resourceHandler.setResourceBase(MavenTestingUtils.getTargetFile("test-classes/simple").getAbsolutePath());
    _resourceHandler.setWelcomeFiles(new String[] { "welcome.txt" });
    _contextHandler = new ContextHandler("/resource");
    _contextHandler.setHandler(_resourceHandler);
    _server.setHandler(_contextHandler);
    _server.start();
}
Also used : Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) LocalConnector(org.eclipse.jetty.server.LocalConnector) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) FileInputStream(java.io.FileInputStream) ServerConnector(org.eclipse.jetty.server.ServerConnector) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) File(java.io.File) BeforeClass(org.junit.BeforeClass)

Aggregations

Server (org.eclipse.jetty.server.Server)521 ServerConnector (org.eclipse.jetty.server.ServerConnector)209 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)129 Test (org.junit.Test)103 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)99 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)68 IOException (java.io.IOException)66 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)65 File (java.io.File)62 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)61 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)58 URI (java.net.URI)52 Before (org.junit.Before)50 BeforeClass (org.junit.BeforeClass)47 ServletException (javax.servlet.ServletException)44 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)43 LocalConnector (org.eclipse.jetty.server.LocalConnector)42 URL (java.net.URL)37 HttpServletRequest (javax.servlet.http.HttpServletRequest)33 HttpServletResponse (javax.servlet.http.HttpServletResponse)31