Search in sources :

Example 21 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class StandardStopper method processBinding.

@Override
public void processBinding(Node node, App app) throws Exception {
    ContextHandler handler = app.getContextHandler();
    // Before stopping, take back management from the context
    app.getDeploymentManager().getContexts().unmanage(handler);
    // Stop it
    handler.stop();
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler)

Example 22 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class StandardUndeployer method recursiveRemoveContext.

private void recursiveRemoveContext(HandlerCollection coll, ContextHandler context) {
    Handler[] children = coll.getHandlers();
    int originalCount = children.length;
    for (int i = 0, n = children.length; i < n; i++) {
        Handler child = children[i];
        LOG.debug("Child handler {}", child);
        if (child.equals(context)) {
            LOG.debug("Removing handler {}", child);
            coll.removeHandler(child);
            child.destroy();
            if (LOG.isDebugEnabled())
                LOG.debug("After removal: {} (originally {})", coll.getHandlers().length, originalCount);
        } else if (child instanceof HandlerCollection) {
            recursiveRemoveContext((HandlerCollection) child, context);
        }
    }
}
Also used : Handler(org.eclipse.jetty.server.Handler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection)

Example 23 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class OverlayedAppProvider method createContextHandler.

/**
     * Create Context Handler.
     * <p>
     * Callback from the deployment manager to create a context handler instance.
     * @see org.eclipse.jetty.deploy.AppProvider#createContextHandler(org.eclipse.jetty.deploy.App)
     */
public synchronized ContextHandler createContextHandler(App app) throws Exception {
    final OverlayedApp overlayed = (OverlayedApp) app;
    final String origin = overlayed.getOriginId();
    final Instance instance = overlayed.getInstance();
    final Template template = instance.getTemplate();
    final Webapp webapp = template.getWebapp();
    final Node node = _node;
    // remember the original loader
    ClassLoader orig_loader = Thread.currentThread().getContextClassLoader();
    try {
        // Look for existing shared resources
        String key = (node == null ? "" : node.getLoadedKey()) + template.getLoadedKey() + (webapp == null ? "" : webapp.getLoadedKey());
        instance.setSharedKey(key);
        TemplateContext shared = _shared.get(key);
        // Create shared resourced
        if (shared == null)
            shared = createTemplateContext(key, webapp, template, node, orig_loader);
        // Build the instance lib loader
        ClassLoader shared_loader = shared.getWebappLoader() != null ? shared.getWebappLoader() : (shared.getLibLoader() != null ? shared.getLibLoader() : orig_loader);
        ClassLoader loader = shared_loader;
        Resource instance_lib = instance.getResource(LIB);
        if (instance_lib.exists()) {
            List<URL> libs = new ArrayList<URL>();
            for (String jar : instance_lib.list()) {
                if (!jar.toLowerCase(Locale.ENGLISH).endsWith(".jar"))
                    continue;
                libs.add(instance_lib.addPath(jar).getURL());
            }
            __log.debug("{}: libs={}", origin, libs);
            loader = URLClassLoader.newInstance(libs.toArray(new URL[] {}), loader);
        }
        // set the thread loader
        Thread.currentThread().setContextClassLoader(loader);
        // Create properties to be shared by overlay.xmls
        Map<String, Object> idMap = new HashMap<String, Object>();
        idMap.putAll(shared.getIdMap());
        idMap.put(_serverID, getDeploymentManager().getServer());
        // Create the instance context for the template
        ContextHandler context = null;
        Resource template_context_xml = template.getResource(OVERLAY_XML);
        if (template_context_xml.exists()) {
            __log.debug("{}: overlay.xml={}", origin, template_context_xml);
            XmlConfiguration xmlc = newXmlConfiguration(template_context_xml.getURL(), idMap, template, instance);
            context = (ContextHandler) xmlc.configure();
            idMap = xmlc.getIdMap();
        } else if (webapp == null)
            // If there is no webapp, this is a plain context
            context = new ContextHandler();
        else
            // It is a webapp context
            context = new WebAppContext();
        // Set the resource base
        final Resource instance_webapp = instance.getResource(WEBAPP);
        if (instance_webapp.exists()) {
            context.setBaseResource(new ResourceCollection(instance_webapp, shared.getBaseResource()));
            // Create the resource cache
            ResourceCache cache = new ResourceCache(shared.getResourceCache(), instance_webapp, context.getMimeTypes(), false, false);
            context.setAttribute(ResourceCache.class.getCanonicalName(), cache);
        } else {
            context.setBaseResource(shared.getBaseResource());
            context.setAttribute(ResourceCache.class.getCanonicalName(), shared.getResourceCache());
        }
        __log.debug("{}: baseResource={}", origin, context.getResourceBase());
        // Set the shared session scavenger timer
        context.setAttribute("org.eclipse.jetty.server.session.timer", _sessionScavenger);
        // Apply any node or instance overlay.xml
        for (Resource context_xml : getLayeredResources(OVERLAY_XML, node, instance)) {
            __log.debug("{}: overlay.xml={}", origin, context_xml);
            XmlConfiguration xmlc = newXmlConfiguration(context_xml.getURL(), idMap, template, instance);
            xmlc.getIdMap().put("Cache", context.getAttribute(ResourceCache.class.getCanonicalName()));
            xmlc.configure(context);
            idMap = xmlc.getIdMap();
        }
        // Is it a webapp?
        if (context instanceof WebAppContext) {
            final WebAppContext webappcontext = (WebAppContext) context;
            if (Arrays.asList(((WebAppContext) context).getServerClasses()).toString().equals(Arrays.asList(WebAppContext.__dftServerClasses).toString())) {
                __log.debug("clear server classes");
                webappcontext.setServerClasses(null);
            }
            // set classloader
            webappcontext.setCopyWebDir(false);
            webappcontext.setCopyWebInf(false);
            webappcontext.setExtractWAR(false);
            if (instance_webapp.exists()) {
                final Resource classes = instance_webapp.addPath("WEB-INF/classes");
                final Resource lib = instance_webapp.addPath("WEB-INF/lib");
                if (classes.exists() || lib.exists()) {
                    final AtomicBoolean locked = new AtomicBoolean(false);
                    WebAppClassLoader webapp_loader = new WebAppClassLoader(loader, webappcontext) {

                        @Override
                        public void addClassPath(Resource resource) throws IOException {
                            if (!locked.get())
                                super.addClassPath(resource);
                        }

                        @Override
                        public void addClassPath(String classPath) throws IOException {
                            if (!locked.get())
                                super.addClassPath(classPath);
                        }

                        @Override
                        public void addJars(Resource lib) {
                            if (!locked.get())
                                super.addJars(lib);
                        }
                    };
                    if (classes.exists())
                        webapp_loader.addClassPath(classes);
                    if (lib.exists())
                        webapp_loader.addJars(lib);
                    locked.set(true);
                    loader = webapp_loader;
                }
            }
            // Make sure loader is unique for JNDI
            if (loader == shared_loader)
                loader = new URLClassLoader(new URL[] {}, shared_loader);
            // add default descriptor
            List<Resource> webdefaults = getLayeredResources(WEB_DEFAULT_XML, instance, node, template);
            if (webdefaults.size() > 0) {
                Resource webdefault = webdefaults.get(0);
                __log.debug("{}: defaultweb={}", origin, webdefault);
                webappcontext.setDefaultsDescriptor(webdefault.toString());
            }
            // add overlay descriptors
            for (Resource override : getLayeredResources(WEB_FRAGMENT_XML, template, node, instance)) {
                __log.debug("{}: web override={}", origin, override);
                webappcontext.addOverrideDescriptor(override.toString());
            }
        }
        context.setClassLoader(loader);
        __log.debug("{}: baseResource={}", origin, context.getBaseResource());
        Resource jetty_web_xml = context.getResource("/WEB-INF/" + JettyWebXmlConfiguration.JETTY_WEB_XML);
        if (jetty_web_xml != null && jetty_web_xml.exists())
            context.setAttribute(JettyWebXmlConfiguration.XML_CONFIGURATION, newXmlConfiguration(jetty_web_xml.getURL(), idMap, template, instance));
        // Add listener to expand parameters from descriptors before other listeners execute
        Map<String, String> params = new HashMap<String, String>();
        populateParameters(params, template, instance);
        context.addEventListener(new ParameterExpander(params, context));
        System.err.println("created:\n" + context.dump());
        return context;
    } finally {
        Thread.currentThread().setContextClassLoader(orig_loader);
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) JettyWebXmlConfiguration(org.eclipse.jetty.webapp.JettyWebXmlConfiguration) URL(java.net.URL) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) URLClassLoader(java.net.URLClassLoader) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) ResourceCache(org.eclipse.jetty.server.ResourceCache) JarResource(org.eclipse.jetty.util.resource.JarResource) Resource(org.eclipse.jetty.util.resource.Resource) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) URLClassLoader(java.net.URLClassLoader) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection)

Example 24 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class TestJettyOSGiBootContextAsService method testContextHandlerAsOSGiService.

/**
     */
@Test
public void testContextHandlerAsOSGiService() throws Exception {
    // now test the context
    HttpClient client = new HttpClient();
    try {
        client.start();
        ContentResponse response = client.GET("http://127.0.0.1:" + TestJettyOSGiBootCore.DEFAULT_HTTP_PORT + "/acme/index.html");
        assertEquals(HttpStatus.OK_200, response.getStatus());
        String content = new String(response.getContent());
        assertTrue(content.indexOf("<h1>Test OSGi Context</h1>") != -1);
    } finally {
        client.stop();
    }
    ServiceReference[] refs = bundleContext.getServiceReferences(ContextHandler.class.getName(), null);
    assertNotNull(refs);
    assertEquals(1, refs.length);
    ContextHandler ch = (ContextHandler) bundleContext.getService(refs[0]);
    assertEquals("/acme", ch.getContextPath());
    // Stop the bundle with the ContextHandler in it and check the jetty
    // Context is destroyed for it.
    // TODO: think of a better way to communicate this to the test, other
    // than checking stderr output
    Bundle testWebBundle = TestOSGiUtil.getBundle(bundleContext, "org.eclipse.jetty.osgi.testcontext");
    assertNotNull("Could not find the org.eclipse.jetty.test-jetty-osgi-context.jar bundle", testWebBundle);
    assertTrue("The bundle org.eclipse.jetty.testcontext is not correctly resolved", testWebBundle.getState() == Bundle.ACTIVE);
    testWebBundle.stop();
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Bundle(org.osgi.framework.Bundle) CoreOptions.mavenBundle(org.ops4j.pax.exam.CoreOptions.mavenBundle) HttpClient(org.eclipse.jetty.client.HttpClient) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 25 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class Response method sendError.

@Override
public void sendError(int code, String message) throws IOException {
    if (isIncluding())
        return;
    if (isCommitted()) {
        if (LOG.isDebugEnabled())
            LOG.debug("Aborting on sendError on committed response {} {}", code, message);
        code = -1;
    } else
        resetBuffer();
    switch(code) {
        case -1:
            _channel.abort(new IOException());
            return;
        case 102:
            sendProcessing();
            return;
        default:
            break;
    }
    _mimeType = null;
    _characterEncoding = null;
    _outputType = OutputType.NONE;
    setHeader(HttpHeader.EXPIRES, null);
    setHeader(HttpHeader.LAST_MODIFIED, null);
    setHeader(HttpHeader.CACHE_CONTROL, null);
    setHeader(HttpHeader.CONTENT_TYPE, null);
    setHeader(HttpHeader.CONTENT_LENGTH, null);
    setStatus(code);
    Request request = _channel.getRequest();
    Throwable cause = (Throwable) request.getAttribute(Dispatcher.ERROR_EXCEPTION);
    if (message == null) {
        _reason = HttpStatus.getMessage(code);
        message = cause == null ? _reason : cause.toString();
    } else
        _reason = message;
    // If we are allowed to have a body, then produce the error page.
    if (code != SC_NO_CONTENT && code != SC_NOT_MODIFIED && code != SC_PARTIAL_CONTENT && code >= SC_OK) {
        ContextHandler.Context context = request.getContext();
        ContextHandler contextHandler = context == null ? _channel.getState().getContextHandler() : context.getContextHandler();
        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, code);
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
        request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());
        request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, request.getServletName());
        ErrorHandler error_handler = ErrorHandler.getErrorHandler(_channel.getServer(), contextHandler);
        if (error_handler != null)
            error_handler.handle(null, request, request, this);
        else
            closeOutput();
    }
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException)

Aggregations

ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)127 Server (org.eclipse.jetty.server.Server)47 ServerConnector (org.eclipse.jetty.server.ServerConnector)27 URI (java.net.URI)21 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)20 Test (org.junit.Test)20 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)19 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)19 IOException (java.io.IOException)18 Handler (org.eclipse.jetty.server.Handler)14 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)14 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)14 File (java.io.File)13 ServletException (javax.servlet.ServletException)13 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)13 BeforeClass (org.junit.BeforeClass)11 BaseIntegrationTest (com.ctrip.framework.apollo.BaseIntegrationTest)10 Config (com.ctrip.framework.apollo.Config)10 ApolloConfig (com.ctrip.framework.apollo.core.dto.ApolloConfig)10 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)10