Java Code Examples for org.eclipse.jetty.http.pathmap.ServletPathSpec

Following code examples demonstrate how to use org.eclipse.jetty.http.pathmap.ServletPathSpec from jetty. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.eclipse.jetty.http.pathmap.ServletPathSpec and various code implementation of this class.

    }

    private PathSpec toPathSpec(String rawspec)
    {
        if (rawspec.charAt(0) == '/' || rawspec.startsWith("*.") || rawspec.startsWith("servlet|"))
        {
            return new ServletPathSpec(rawspec);
        }
        else if (rawspec.charAt(0) == '^' || rawspec.startsWith("regex|"))
        {
            return new RegexPathSpec(rawspec);
        }
        else if (rawspec.startsWith("uri-template|"))
        {
            return new UriTemplatePathSpec(rawspec.substring("uri-template|".length()));
        }


        throw new IllegalArgumentException("Unrecognized path spec syntax [" + rawspec + "]");
    } 


    {
        if (spec instanceof org.eclipse.jetty.websocket.server.pathmap.ServletPathSpec)
        {
            addMapping(new ServletPathSpec(spec.getSpec()), creator);
        }
        else if (spec instanceof org.eclipse.jetty.websocket.server.pathmap.RegexPathSpec)
        {
            addMapping(new RegexPathSpec(spec.getSpec()), creator);
        }
        else
        {
            throw new RuntimeException("Unsupported (Deprecated) PathSpec implementation type: " + spec.getClass().getName());
        }
    } 

    public void start(int portNumber) throws Exception{
        QueuedThreadPool threadPool = new QueuedThreadPool(MAX_THREADS, MIN_THREADS, IDLE_TIMEOUT);

        server = new Server(threadPool);
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(portNumber);
        server.setConnectors(new Connector[] {connector});

        Path webRootPath = new File("server/site/").toPath().toRealPath();

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setBaseResource(new PathResource(webRootPath));
        context.setWelcomeFiles(new String[] { "index.html" });
        server.setHandler(context);

        WebSocketUpgradeFilter wsfilter = WebSocketUpgradeFilter.configureContext(context);
        wsfilter.getFactory().getPolicy().setIdleTimeout(11000);
        wsfilter.addMapping(new ServletPathSpec("/connect"), new ClientSocketCreator());

        ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class);
        holderDefault.setInitParameter("dirAllowed", "true");
        context.addServlet(holderDefault, "/");

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

    } 

    public static void main(String[] args) throws ServletException, IOException {
        Server          server    = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8080);
        server.addConnector(connector);

        Path webRootPath = new File("webapps/static-root/").toPath().toRealPath();

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setBaseResource(new PathResource(webRootPath));
        context.setWelcomeFiles(new String[]{"index.html"});
        server.setHandler(context);

        WebSocketUpgradeFilter wsfilter = WebSocketUpgradeFilter.configureContext(context);
        wsfilter.getFactory().getPolicy().setIdleTimeout(5000);
        wsfilter.addMapping(new ServletPathSpec("/time/"), new TimeSocketCreator());

        context.addServlet(TimeServlet.class, "/time/");

        ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class);
        holderDefault.setInitParameter("dirAllowed", "true");
        context.addServlet(holderDefault, "/");

        try {
            server.start();
            server.join();
        } catch (Throwable t) {
            t.printStackTrace(System.err);
        }
    } 

    
    public static ServletContextHandler create(Map<String, WebSocketHandlerWrapper> webSocketHandlers,
                                               Optional<Integer> webSocketIdleTimeoutMillis) {
        ServletContextHandler webSocketServletContextHandler = null;
        if (webSocketHandlers != null) {
            try {
                webSocketServletContextHandler = new ServletContextHandler(null, "/", true, false);
                WebSocketUpgradeFilter webSocketUpgradeFilter = WebSocketUpgradeFilter.configureContext(webSocketServletContextHandler);
                if (webSocketIdleTimeoutMillis.isPresent()) {
                    webSocketUpgradeFilter.getFactory().getPolicy().setIdleTimeout(webSocketIdleTimeoutMillis.get());
                }
                NativeWebSocketConfiguration webSocketConfiguration = (NativeWebSocketConfiguration) webSocketServletContextHandler
                    .getServletContext().getAttribute(NativeWebSocketConfiguration.class.getName());
                for (String path : webSocketHandlers.keySet()) {
                    WebSocketCreator webSocketCreator = WebSocketCreatorFactory.create(webSocketHandlers.get(path));
                    webSocketConfiguration.addMapping(new ServletPathSpec(path), webSocketCreator);
                }
            } catch (Exception ex) {
                logger.error("creation of websocket context handler failed.", ex);
                webSocketServletContextHandler = null;
            }
        }
        return webSocketServletContextHandler;
    } 

    {
        if (spec instanceof org.eclipse.jetty.websocket.server.pathmap.ServletPathSpec)
        {
            addMapping(new ServletPathSpec(spec.getSpec()), creator);
        }
        else if (spec instanceof org.eclipse.jetty.websocket.server.pathmap.RegexPathSpec)
        {
            addMapping(new RegexPathSpec(spec.getSpec()), creator);
        }
        else
        {
            throw new RuntimeException("Unsupported (Deprecated) PathSpec implementation: " + spec.getClass().getName());
        }
    } 

    public ServletAndPath(String pathSpec, Servlet servlet) {
        this.pathSpec = new ServletPathSpec(pathSpec);
        this.servlet = servlet;
    } 

    @Override
    public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        if (ServletPathSpec.match(_pattern, target))
        {
            return apply(target,request, response);
        }
        return null;
    } 

    @Override
    public String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        target = URIUtil.addPaths(_replacement, ServletPathSpec.pathInfo(_pattern, target));
        return target;
    } 

    }

    public void prepare(Config config) throws IOException, URISyntaxException, ServletException, DeploymentException
    {
        QueuedThreadPool threadPool = new QueuedThreadPool();
        server = new Server(threadPool);
        executor = threadPool;

        connector = new ServerConnector(server);
        connector.setPort(config.port);
        connector.setIdleTimeout(config.connectorIdleTimeout);

        LOG.info("Connector Idle Timeout (ms): {}", config.connectorIdleTimeout);

        server.addConnector(connector);

        HandlerList handlers = new HandlerList();

        ServletContextHandler rootContext = new ServletContextHandler();
        rootContext.setServer(server);
        rootContext.setContextPath("/");
        rootContext.setBaseResource(findBaseResource());
        rootContext.setWelcomeFiles(new String[]{"index.html"});

        LOG.info("WebSocket Idle Timeout (ms): {}", config.websocketIdleTimeout);

        ServerContainer container = WebSocketServerContainerInitializer.configureContext(rootContext);
        container.setDefaultMaxSessionIdleTimeout(config.websocketIdleTimeout);
        container.addEndpoint(JsrBasicWebSocket.class);
        container.addEndpoint(JsrAsyncWebSocket.class);

        WebSocketUpgradeFilter wsuf = (WebSocketUpgradeFilter) rootContext.getAttribute(WebSocketUpgradeFilter.class.getName() + ".SCI");
        wsuf.getFactory().getPolicy().setIdleTimeout(config.websocketIdleTimeout);
        JettyWebSocketCreator jettyWebSocketCreator = new JettyWebSocketCreator();
        wsuf.addMapping(new ServletPathSpec("/ws/jetty/basic"), jettyWebSocketCreator);
        wsuf.addMapping(new ServletPathSpec("/ws/jetty/async"), jettyWebSocketCreator);

        ServletHolder defHolder = new ServletHolder("default", DefaultServlet.class);
        rootContext.addServlet(defHolder, "/");

        handlers.addHandler(rootContext);
        handlers.addHandler(new DefaultHandler());

        if (config.enableJmx)
        {
            String host = "localhost";
            int port = 1099;

            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

            MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
            server.addBean(mBeanContainer);

            server.addBean(Log.getLog());

            JMXServiceURL jmxServiceURL = new JMXServiceURL("rmi", host, 1099, urlPath);
            ConnectorServer jmxServer = new ConnectorServer(jmxServiceURL, "org.eclipse.jetty.jmx:name=rmiconnectorserver");

            LOG.info("JMX Remote enabled at {}:{}", host, port);
            LOG.info("Tip: set -Djava.rmi.server.hostname=127.0.0.1 if you have a bad /etc/hosts file");
            server.addBean(jmxServer);
        }

        server.setHandler(handlers);
    } 

    
    boolean appliesTo(String path, int type)
    {
        if (appliesTo(type))
        {
            for (int i=0;i<_pathSpecs.length;i++)
                if (_pathSpecs[i]!=null && ServletPathSpec.match(_pathSpecs[i], path, true))
                    return true;
        }

        return false;
    } 

    public static void startServer() throws ServletException {
        QueuedThreadPool threadPool = new QueuedThreadPool(10);
        threadPool.setDaemon(true);
        threadPool.setMaxThreads(10);
        Server server = new Server(threadPool);
        server.addBean(new ScheduledExecutorScheduler("JettyScheduler", true), true);
        ServerConnector http = new ServerConnector(server, new HttpConnectionFactory());
        http.setPort(2992);
        server.addConnector(http);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setBaseResource(Resource.newClassPathResource("/org/lwjglx/debug/static"));
        context.setWelcomeFiles(new String[] { "index.html" });
        server.setHandler(context);

        WebSocketUpgradeFilter wsfilter = WebSocketUpgradeFilter.configureContext(context);
        wsfilter.addMapping(new ServletPathSpec("/ws"), new ProfilingConnectionCreator());

        ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class);
        holderDefault.setInitParameter("dirAllowed", "true");
        context.addServlet(holderDefault, "/");

        try {
            server.start();
        } catch (Exception e) {
            throw new AssertionError("Could not start profiling server", e);
        }
    } 

    
    public ServletMapping getMapping()
    {
        final PathSpec pathSpec = _pathSpec;
        final MappingMatch match;
        final String mapping;
        if (pathSpec instanceof ServletPathSpec)
        {
            switch(((ServletPathSpec)pathSpec).getGroup())
            {
                case ROOT:
                    match = MappingMatch.CONTEXT_ROOT;
                    mapping = "";
                    break;
                case DEFAULT:
                    match = MappingMatch.DEFAULT;
                    mapping = "/";
                    break;
                case EXACT:
                    match = MappingMatch.EXACT;
                    mapping = _servletPath;
                    break;
                case SUFFIX_GLOB:
                    match = MappingMatch.EXTENSION;
                    int dot = _servletPath.lastIndexOf('.');
                    mapping = _servletPath.substring(0,dot);
                    break;
                case PREFIX_GLOB:
                    match = MappingMatch.PATH;
                    mapping = _servletPath;
                    break;
                default:
                    match = null;
                    mapping = _servletPath;
                    break;
            }
        }
        else
        {
            match = null;
            mapping = _servletPath;
        }
        
        return new ServletMapping()
        {
            @Override
            public String getMatchValue()
            {   
                return mapping;
            }

            @Override
            public String getPattern()
            {
                if (pathSpec!=null)
                    pathSpec.toString();
                return null;
            }

            @Override
            public String getServletName()
            {
                return Request.this.getServletName();
            }

            @Override
            public MappingMatch getMappingMatch()
            {
                return match;
            }
        };
    } 

    }

    public ServletMapping addServletMapping (String servletName, XmlParser.Node node, WebAppContext context, Descriptor descriptor)
    {
        ServletMapping mapping = new ServletMapping(new Source(Source.Origin.DESCRIPTOR, descriptor.getResource().toString()));
        mapping.setServletName(servletName);
        mapping.setDefault(descriptor instanceof DefaultsDescriptor);
        
        List<String> paths = new ArrayList<String>();
        Iterator<XmlParser.Node> iter = node.iterator("url-pattern");
        while (iter.hasNext())
        {
            String p = iter.next().toString(false, true);
            p = ServletPathSpec.normalize(p);
            
            ListIterator<ServletMapping> listItor = _servletMappings.listIterator();
            boolean found = false;
            while (listItor.hasNext() && !found)
            {
                ServletMapping sm = listItor.next();
                if (sm.getPathSpecs() != null)
                {
                    for (String ps:sm.getPathSpecs())
                    {
                        if (p.equals(ps) && (sm.isDefault() || servletName.equals(sm.getServletName())))
                        {
                            if (sm.isDefault())
                            {
                                if (LOG.isDebugEnabled()) LOG.debug("{} in mapping {} from defaults descriptor is overridden by ",ps,sm,servletName);
                            }
                            else
                                LOG.warn("Duplicate mapping from {} to {}", p, servletName);

                            String[] updatedPaths = ArrayUtil.removeFromArray(sm.getPathSpecs(), ps);
                            
                            if (updatedPaths == null || updatedPaths.length == 0)
                            {
                                if (LOG.isDebugEnabled()) LOG.debug("Removed empty mapping {}",sm);
                                listItor.remove();
                            }
                            else 
                            {
                                sm.setPathSpecs(updatedPaths);
                                if (LOG.isDebugEnabled()) LOG.debug("Removed path {} from mapping {}", p,sm);
                            }
                            found = true;
                            break;
                        }
                    }
                }
            }

            paths.add(p);
            context.getMetaData().setOrigin(servletName+".servlet.mapping."+p, descriptor);
        }

        mapping.setPathSpecs((String[]) paths.toArray(new String[paths.size()]));
        if (LOG.isDebugEnabled()) LOG.debug("Added mapping {} ",mapping);
        _servletMappings.add(mapping);
        return mapping;
    } 

    }

    public void addFilterMapping (String filterName, XmlParser.Node node, WebAppContext context, Descriptor descriptor)
    {
        FilterMapping mapping = new FilterMapping();
        mapping.setFilterName(filterName);

        List<String> paths = new ArrayList<String>();
        Iterator<XmlParser.Node>  iter = node.iterator("url-pattern");
        while (iter.hasNext())
        {
            String p = iter.next().toString(false, true);
            p = ServletPathSpec.normalize(p);
            paths.add(p);
            context.getMetaData().setOrigin(filterName+".filter.mapping."+p, descriptor);
        }
        mapping.setPathSpecs((String[]) paths.toArray(new String[paths.size()]));

        List<String> names = new ArrayList<String>();
        iter = node.iterator("servlet-name");
        while (iter.hasNext())
        {
            String n = ((XmlParser.Node) iter.next()).toString(false, true);
            names.add(n);
        }
        mapping.setServletNames((String[]) names.toArray(new String[names.size()]));


        List<DispatcherType> dispatches = new ArrayList<DispatcherType>();
        iter=node.iterator("dispatcher");
        while(iter.hasNext())
        {
            String d=((XmlParser.Node)iter.next()).toString(false,true);
            dispatches.add(FilterMapping.dispatch(d));
        }

        if (dispatches.size()>0)
            mapping.setDispatcherTypes(EnumSet.copyOf(dispatches));

        _filterMappings.add(mapping);
    } 

Advertisement
Advertisement