Java Code Examples for org.eclipse.jetty.webapp.MetaData

Following code examples demonstrate how to use org.eclipse.jetty.webapp.MetaData 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.webapp.MetaData and various code implementation of this class.

    @Test
    public void testIt () throws Exception
    {
        ClassLoader old_loader = Thread.currentThread().getContextClassLoader();

        try
        {
            InitialContext ic = new InitialContext();

            Server server = new Server();

            WebAppContext wac = new WebAppContext();
            wac.setServer(server);
            wac.setClassLoader(new WebAppClassLoader(Thread.currentThread().getContextClassLoader(), wac));
            wac.getSystemClasspathPattern().include("org.eclipse.jetty.jndi.");
            wac.getServerClasspathPattern().exclude("org.eclipse.jetty.jndi.");

            MetaData metaData = new MetaData();

            PlusDescriptorProcessor plusProcessor = new PlusDescriptorProcessor();

            EnvEntry ee1 = new EnvEntry(server, "xxx/a", "100", true);
            EnvEntry ee2 = new EnvEntry(server, "yyy/b", "200", false);
            EnvEntry ee3 = new EnvEntry(server, "zzz/c", "300", false);
            EnvEntry ee4 = new EnvEntry(server, "zzz/d", "400", false);
            EnvEntry ee5 = new EnvEntry(server, "zzz/f", "500", true);

            EnvEntry ee6 = new EnvEntry(wac, "xxx/a", "900", true);
            EnvEntry ee7 = new EnvEntry(wac, "yyy/b", "910", true);
            EnvEntry ee8 = new EnvEntry(wac, "zzz/c", "920", false);
            EnvEntry ee9 = new EnvEntry(wac, "zzz/e", "930", false);

            assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "xxx/a"));
            assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "yyy/b"));
            assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "zzz/c"));
            assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "zzz/d"));
            assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "xxx/a"));
            assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "yyy/b"));
            assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "zzz/c"));
            assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "zzz/e"));

            EnvConfiguration envConfig = new EnvConfiguration();


            Thread.currentThread().setContextClassLoader(wac.getClassLoader());
            MetaData metadata = new MetaData();
            envConfig.preConfigure(wac);
            envConfig.configure(wac);
            envConfig.bindEnvEntries(wac);

            String val = (String)ic.lookup("java:comp/env/xxx/a");
            val = (String)ic.lookup("java:comp/env/yyy/b");
            val = (String)ic.lookup("java:comp/env/zzz/c");
            val = (String)ic.lookup("java:comp/env/zzz/d");
            val = (String)ic.lookup("java:comp/env/zzz/e");

            NamingEntry ne = (NamingEntry)ic.lookup("java:comp/env/"+NamingEntry.__contextName+"/xxx/a");
            assertNotNull(ne);
            ne = (NamingEntry)ic.lookup("java:comp/env/"+NamingEntry.__contextName+"/yyy/b");
            assertNotNull(ne);
            ne = (NamingEntry)ic.lookup("java:comp/env/"+NamingEntry.__contextName+"/zzz/c");
            assertNotNull(ne);
            ne = (NamingEntry)ic.lookup("java:comp/env/"+NamingEntry.__contextName+"/zzz/d");
            assertNotNull(ne);
            ne = (NamingEntry)ic.lookup("java:comp/env/"+NamingEntry.__contextName+"/zzz/e");
            assertNotNull(ne);

            plusProcessor.bindEnvEntry("foo", "99");
            assertEquals("99",ic.lookup( "java:comp/env/foo"));

            plusProcessor.bindEnvEntry("xxx/a", "7");
            plusProcessor.bindEnvEntry("yyy/b", "7");
            plusProcessor.bindEnvEntry("zzz/c", "7");
            plusProcessor.bindEnvEntry("zzz/d", "7");
            plusProcessor.bindEnvEntry("zzz/e", "7");
            plusProcessor.bindEnvEntry("zzz/f", "7");

            ((Context)ic.lookup("java:comp")).destroySubcontext("env");
            ic.destroySubcontext("xxx");
            ic.destroySubcontext("yyy");
            ic.destroySubcontext("zzz");
        }
        finally
        {
            Thread.currentThread().setContextClassLoader(old_loader);
        }
    } 


    
    public void apply()
    {
        Class<? extends java.util.EventListener> clazz = (Class<? extends EventListener>)getTargetClass();

        if (clazz == null)
        {
            LOG.warn(_className+" cannot be loaded");
            return;
        }

        try
        {
            if (ServletContextListener.class.isAssignableFrom(clazz) ||
                    ServletContextAttributeListener.class.isAssignableFrom(clazz) ||
                    ServletRequestListener.class.isAssignableFrom(clazz) ||
                    ServletRequestAttributeListener.class.isAssignableFrom(clazz) ||
                    HttpSessionListener.class.isAssignableFrom(clazz) ||
                    HttpSessionAttributeListener.class.isAssignableFrom(clazz) ||
                    HttpSessionIdListener.class.isAssignableFrom(clazz))
            {
                java.util.EventListener listener = (java.util.EventListener)_context.getServletContext().createInstance(clazz);      
                MetaData metaData = _context.getMetaData();
                if (metaData.getOrigin(clazz.getName()+".listener") == Origin.NotSet)
                {
                    ListenerHolder h = _context.getServletHandler().newListenerHolder(Source.ANNOTATION);
                    h.setListener(listener);
                    _context.getServletHandler().addListener(h);
                    _context.addEventListener(listener);
                }
            }
            else
                LOG.warn(clazz.getName()+" does not implement one of the servlet listener interfaces");
        }
        catch (Exception e)
        {
            LOG.warn(e);
        }
    } 

    @Override
    public void parseWebInfClasses(final WebAppContext context, final AnnotationParser parser) throws Exception
    {
        JettyWebAppContext jwac = (JettyWebAppContext)context;
        if (jwac.getClassPathFiles() == null)
            super.parseWebInfClasses (context, parser);
        else
        {
            Log.debug("Scanning classes ");
            
            MetaData metaData = context.getMetaData();
            if (metaData == null)
               throw new IllegalStateException ("No metadata");

            clearAnnotationList(parser.getAnnotationHandlers());    

            for (File f:jwac.getClassPathFiles())
            {
                if (f.isDirectory() && f.exists())
                {
                    parser.parse(Resource.newResource(f.toURL()), 
                                new ClassNameResolver()
                    {
                        public boolean isExcluded (String name)
                        {
                            if (context.isSystemClass(name)) return true;
                            if (context.isServerClass(name)) return false;
                            return false;
                        }

                        public boolean shouldOverride (String name)
                        {
                            if (context.isParentLoaderPriority())
                                return false;
                            return true;
                        }
                    });
                }
            }
            List<DiscoveredAnnotation> annotations = new ArrayList<DiscoveredAnnotation>();
            gatherAnnotations(annotations, parser.getAnnotationHandlers());
            metaData.addDiscoveredAnnotations (annotations);
        }
    } 

	public void configure(WebAppContext context) throws Exception {

		MetaData metaData = context.getMetaData();
	} 

    
    public void doHandle(Class clazz)
    {
        if (!Servlet.class.isAssignableFrom(clazz))
            return;
        
        MultipartConfig multi = (MultipartConfig) clazz.getAnnotation(MultipartConfig.class);
        if (multi == null)
            return;
        
        MetaData metaData = _context.getMetaData();
              

        ServletHolder holder = getServletHolderForClass(clazz);
        if (holder != null)
        {
            Descriptor d = metaData.getOriginDescriptor(holder.getName()+".servlet.multipart-config");
            if (d == null)
            {
                metaData.setOrigin(holder.getName()+".servlet.multipart-config",multi,clazz);
                holder.getRegistration().setMultipartConfig(new MultipartConfigElement(multi));
            }
        }
    } 

    }

    public void doHandle (Class clazz)
    {
        if (!Servlet.class.isAssignableFrom(clazz))
            return;

        javax.annotation.security.RunAs runAs = (javax.annotation.security.RunAs)clazz.getAnnotation(javax.annotation.security.RunAs.class);
        if (runAs != null)
        {
            String role = runAs.value();
            if (role != null)
            {
                ServletHolder holder = getServletHolderForClass(clazz);
                if (holder != null)
                {
                    MetaData metaData = _context.getMetaData();
                    Descriptor d = metaData.getOriginDescriptor(holder.getName()+".servlet.run-as");
                    if (d == null)
                    {
                        metaData.setOrigin(holder.getName()+".servlet.run-as",runAs,clazz);
                        org.eclipse.jetty.plus.annotation.RunAs ra = new org.eclipse.jetty.plus.annotation.RunAs();
                        ra.setTargetClassName(clazz.getCanonicalName());
                        ra.setRoleName(role);
                        RunAsCollection raCollection = (RunAsCollection)_context.getAttribute(RunAsCollection.RUNAS_COLLECTION);
                        if (raCollection == null)
                        {
                            raCollection = new RunAsCollection();
                            _context.setAttribute(RunAsCollection.RUNAS_COLLECTION, raCollection);
                        }
                        raCollection.add(ra);
                    }
                }
            }
            else
                LOG.warn("Bad value for @RunAs annotation on class "+clazz.getName());
        }

    } 

	private HandlerCollection getWebAppContext(URI baseUri, File scratchDir) {
		WebAppContext webappCtx = new WebAppContext();
		webappCtx.setContextPath("/");
		webappCtx.setDisplayName("auto join");
		webappCtx.setTempDirectory(new File(param.getTempDir()));
		webappCtx.setConfigurationDiscovered(true);
		webappCtx.setParentLoaderPriority(true);
		RequestLogHandler logHandler = new RequestLogHandler();
		logHandler.setRequestLog(createRequestLog());

		webappCtx.setAttribute("javax.servlet.context.tempdir", scratchDir);
		webappCtx.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
				".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/.*taglibs.*\\.jar$");
		if (ObjectUtil.isNotEmpty(baseUri)) {
		} else {
			webappCtx.setResourceBase(param.getWebDir());
		}

		webappCtx.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
		webappCtx.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
		webappCtx.addBean(new ServletContainerInitializersStarter(webappCtx), true);
		webappCtx.setClassLoader(getUrlClassLoader());

		webappCtx.addServlet(jspServletHolder(), "*.jsp");
		webappCtx.addServlet(DateServlet.class, "/date/");
		webappCtx.addServlet(exampleJspFileMappedServletHolder(), "/test/foo/");
		webappCtx.addServlet(defaultServletHolder(baseUri), "/");
		
		setConfigurations(webappCtx);
		
		MetaData metaData = webappCtx.getMetaData();
		Resource webappInitializer = Resource.newResource(WebAppStrarUpInitializer.class.getProtectionDomain().getCodeSource().getLocation());
		metaData.addContainerResource(webappInitializer);

		HandlerCollection handlerCollection = new HandlerCollection();
		GzipHandler gzipHandler = new GzipHandler();
		handlerCollection.setHandlers(new Handler[] { webappCtx, logHandler, gzipHandler });
		return handlerCollection;
	} 

    @Nonnull
    private Map<String, Resource> findFragments() throws Exception
    {
        HashMap<String, Resource> results = new HashMap<>();

        Enumeration<URL> resources = this.getClass().getClassLoader().getResources(WEB_FRAGMENT_RESOURCE);
        while (resources.hasMoreElements())
        {
            Resource fragment = Resource.newResource(resources.nextElement());

            FragmentDescriptor fragmentDescriptor = new FragmentDescriptor(fragment);
            fragmentDescriptor.parse();

            results.put(fragmentDescriptor.getName(), fragment);
        }

        return results;
    } 

    @Nonnull
    public EmbeddedJetty start() throws Exception
    {
        server = new Server(port);

        context = new WebAppContext();

        context.setContextPath(contextPath);
        context.setResourceBase(resourceBase);
        context.setServer(server);
        context.setWelcomeFiles(new String[]{welcomeFile});

        for (String key : initParams.keySet())
        {
            context.setInitParameter(key, initParams.get(key));
        }

        MetaData metaData = context.getMetaData();

        Resource webXML = Resource.newClassPathResource(descriptor);
        metaData.setWebXml(webXML);

        if (webFragments)
        {
            Map<String, Resource> fragments = findFragments();

            if (!metaData.getWebXml().getOrdering().isEmpty())
            {
                for (String name : metaData.getWebXml().getOrdering())
                {
                    Resource fragmentXML = fragments.get(name);

                    addFragment(fragmentXML, webXML, metaData);
                }
            }
            else
            {
                for (Resource fragmentXML : fragments.values())
                {
                    addFragment(fragmentXML, webXML, metaData);
                }
            }
        }

        server.setHandler(context);
        server.start();
        server.setStopAtShutdown(true);

        return this;
    } 

    }


    public void doHandle(Class clazz)
    {
        if (Util.supportsPostConstructPreDestroy(clazz))
        {
            Method[] methods = clazz.getDeclaredMethods();
            for (int i=0; i<methods.length; i++)
            {
                Method m = (Method)methods[i];
                if (m.isAnnotationPresent(PostConstruct.class))
                {
                    if (m.getParameterTypes().length != 0)
                        throw new IllegalStateException(m+" has parameters");
                    if (m.getReturnType() != Void.TYPE)
                        throw new IllegalStateException(m+" is not void");
                    if (m.getExceptionTypes().length != 0)
                        throw new IllegalStateException(m+" throws checked exceptions");
                    if (Modifier.isStatic(m.getModifiers()))
                        throw new IllegalStateException(m+" is static");

                    MetaData metaData = _context.getMetaData();
                    Origin origin = metaData.getOrigin("post-construct");
                    if (origin != null &&
                        (origin == Origin.WebXml ||
                         origin == Origin.WebDefaults ||
                         origin == Origin.WebOverride))
                        return;

                    PostConstructCallback callback = new PostConstructCallback();
                    callback.setTarget(clazz.getName(), m.getName());
                    LifeCycleCallbackCollection lifecycles = (LifeCycleCallbackCollection)_context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION);
                    if (lifecycles == null)
                    {
                        lifecycles = new LifeCycleCallbackCollection();
                        _context.setAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION,lifecycles);
                    }
                    lifecycles.add(callback);
                }
            }
        }
    } 

    }

    public void doHandle(Class clazz)
    {
        if (Util.supportsPostConstructPreDestroy(clazz))
        {
            Method[] methods = clazz.getDeclaredMethods();
            for (int i=0; i<methods.length; i++)
            {
                Method m = (Method)methods[i];
                if (m.isAnnotationPresent(PreDestroy.class))
                {
                    if (m.getParameterTypes().length != 0)
                        throw new IllegalStateException(m+" has parameters");
                    if (m.getReturnType() != Void.TYPE)
                        throw new IllegalStateException(m+" is not void");
                    if (m.getExceptionTypes().length != 0)
                        throw new IllegalStateException(m+" throws checked exceptions");
                    if (Modifier.isStatic(m.getModifiers()))
                        throw new IllegalStateException(m+" is static");

                    MetaData metaData = _context.getMetaData();
                    Origin origin = metaData.getOrigin("pre-destroy");
                    if (origin != null &&
                            (origin == Origin.WebXml ||
                             origin == Origin.WebDefaults ||
                             origin == Origin.WebOverride))
                            return;

                    PreDestroyCallback callback = new PreDestroyCallback();
                    callback.setTarget(clazz.getName(), m.getName());

                    LifeCycleCallbackCollection lifecycles = (LifeCycleCallbackCollection)_context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION);
                    if (lifecycles == null)
                    {
                        lifecycles = new LifeCycleCallbackCollection();
                        _context.setAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION, lifecycles);
                    }

                    lifecycles.add(callback);
                }
            }
        }
    } 

        public void addClassPath(final String classPath) throws IOException {
            if (classPath != null) {
                for (final String path : classPath.split("[,;]")) {
                    final Resource resource = getContext().newResource(path.trim());
                    addURL(resource.toString().endsWith("/") ? resource.getURL() : Archives.Nested.nestedURL(resource.getURL()));
                }
            }
        } 

        NestedMetaData(final MetaData delegate) {
            assert delegate != null;
            this.delegate = delegate;
        } 

        }

        public void visitLoginConfig(WebAppContext context, Descriptor descriptor, XmlParser.Node node) throws Exception
        {
            if (null==_securityHandler.getRealmName())
            {
                WebMetaData metaData = ((JBossWebAppContext)_context)._webApp.getMetaData();
                String realmName = metaData.getSecurityDomain();
                if (null!=realmName)
                {
                    if (realmName.endsWith("/"))
                        realmName = realmName.substring (0, realmName.length());
                    int idx = realmName.lastIndexOf('/');
                    if (idx >= 0)
                        realmName = realmName.substring(idx+1);
                }
                _securityHandler.setRealmName(realmName);
            }
           
            if(__log.isDebugEnabled())
                __log.debug("Realm name is : "+_securityHandler.getRealmName());
        } 

    public void findWebFragments(WebAppContext context, MetaData metaData) throws Exception {
        final List<Resource> frags = (List<Resource>) context.getAttribute(FRAGMENT_RESOURCES);
        if (frags != null) {
            for (final Resource frag : frags) {
                final Resource parentResource = Util.chop(frag.getURL(), "/META-INF/web-fragment.xml");
                metaData.addFragment(parentResource, frag);
            }
        }
    } 

    }

    private static void outholder(XmlAppendable out, MetaData md, String tag, Holder<?> holder) throws IOException
    {
        out.open(tag,Collections.singletonMap("source",holder.getSource().toString()));
        String n = holder.getName();
        out.tag(tag + "-name",n);

        String ot = n + "." + tag + ".";

        out.tag(tag + "-class",origin(md,ot + tag + "-class"),holder.getClassName());

        for (String p : holder.getInitParameters().keySet())
        {
                continue;
            out.open("init-param",origin(md,ot + "init-param." + p))
            .tag("param-name",p)
            .tag("param-value",holder.getInitParameter(p))
            .close();
        }

        if (holder instanceof ServletHolder)
        {
            ServletHolder s = (ServletHolder)holder;
            if (s.getForcedPath() != null)
                out.tag("jsp-file",s.getForcedPath());

            if (s.getInitOrder() != 0)
                out.tag("load-on-startup",Integer.toString(s.getInitOrder()));

            if (s.getRunAsRole() != null)
                out.open("run-as",origin(md,ot + "run-as"))
                .tag("role-name",s.getRunAsRole())
                .close();

            Map<String,String> roles = s.getRoleRefMap();
            if (roles!=null)
            {
                for (Map.Entry<String, String> e : roles.entrySet())
                {
                    out.open("security-role-ref",origin(md,ot+"role-name."+e.getKey()))
                    .tag("role-name",e.getKey())
                    .tag("role-link",e.getValue())
                    .close();
                }
            }
            
            if (!s.isEnabled())
                out.tag("enabled",origin(md,ot + "enabled"),"false");

            MultipartConfigElement multipartConfig = ((ServletHolder.Registration)s.getRegistration()).getMultipartConfig();
            if (multipartConfig != null)
            {
                out.open("multipart-config", origin(md, s.getName()+".servlet.multipart-config"));
                if (multipartConfig.getLocation() != null)
                    out.tag("location", multipartConfig.getLocation());
                out.tag("max-file-size", Long.toString(multipartConfig.getMaxFileSize()));
                out.tag("max-request-size", Long.toString(multipartConfig.getMaxRequestSize()));
                out.tag("file-size-threshold", Long.toString(multipartConfig.getFileSizeThreshold()));
                out.close();
            }
        }

        out.tag("async-supported",origin(md,ot + "async-supported"),holder.isAsyncSupported()?"true":"false");
        out.close();
    } 

    }

    public static Map<String, String> origin(MetaData md, String name)
    {
        if (!LOG.isDebugEnabled())
            return Collections.emptyMap();
        if (name == null)
            return Collections.emptyMap();
        OriginInfo origin = md.getOriginInfo(name);
        if (origin == null)
            return Collections.emptyMap();
        return Collections.singletonMap("origin",origin.toString());

    } 

    
    private void outholder(XmlAppendable out, MetaData md, FilterHolder holder) throws IOException
    {
        if (LOG.isDebugEnabled())
            out.openTag("filter",Collections.singletonMap("source",holder.getSource().toString()));
        else
            out.openTag("filter");
        
        String n = holder.getName();
        out.tag("filter-name",n);

        String ot = n + ".filter.";
        
        if (holder instanceof FilterHolder)
        {
            out.tag("filter-class",origin(md,ot + "filter-class"),holder.getClassName());
            out.tag("async-supported",origin(md,ot + "async-supported"),holder.isAsyncSupported()?"true":"false");
        }
        
        for (String p : holder.getInitParameters().keySet())
        {
            out.openTag("init-param",origin(md,ot + "init-param." + p))
            .tag("param-name",p)
            .tag("param-value",holder.getInitParameter(p))
            .closeTag();
        }

        out.closeTag();
    } 

    
    public Map<String, String> origin(MetaData md, String name)
    {
        if (!(_generateOrigin || LOG.isDebugEnabled()))
            return Collections.emptyMap();
        if (name == null)
            return Collections.emptyMap();
        OriginInfo origin = md.getOriginInfo(name);
        if (LOG.isDebugEnabled()) LOG.debug("origin of "+name+" is "+origin);
        if (origin == null)
            return Collections.emptyMap();
        return Collections.singletonMap(_originAttribute,origin.toString()+":"+(_count++));
    } 

    }

    private void outholder(XmlAppendable out, MetaData md, ServletHolder holder) throws IOException
    {
        
        if (LOG.isDebugEnabled())
            out.openTag("servlet",Collections.singletonMap("source",holder.getSource().toString()));
        else
            out.openTag("servlet");
        
        String n = holder.getName();
        out.tag("servlet-name",n);

        String ot = n + ".servlet.";

        ServletHolder s = (ServletHolder)holder;
        if (s.getForcedPath() != null && s.getClassName() == null)
            out.tag("jsp-file",s.getForcedPath());
        else
            out.tag("servlet-class",origin(md,ot + "servlet-class"),s.getClassName());

        for (String p : holder.getInitParameters().keySet())
        {
                continue;
            out.openTag("init-param",origin(md,ot + "init-param." + p))
            .tag("param-name",p)
            .tag("param-value",holder.getInitParameter(p))
            .closeTag();
        }

        if (s.getInitOrder() >= 0)
            out.tag("load-on-startup",Integer.toString(s.getInitOrder()));

        if (!s.isEnabled())
            out.tag("enabled",origin(md,ot + "enabled"),"false");

        out.tag("async-supported",origin(md,ot + "async-supported"),holder.isAsyncSupported()?"true":"false");

        if (s.getRunAsRole() != null)
            out.openTag("run-as",origin(md,ot + "run-as"))
            .tag("role-name",s.getRunAsRole())
            .closeTag();

        Map<String,String> roles = s.getRoleRefMap();
        if (roles!=null)
        {
            for (Map.Entry<String, String> e : roles.entrySet())
            {
                out.openTag("security-role-ref",origin(md,ot+"role-name."+e.getKey()))
                .tag("role-name",e.getKey())
                .tag("role-link",e.getValue())
                .closeTag();
            }
        }

        MultipartConfigElement multipartConfig = ((ServletHolder.Registration)s.getRegistration()).getMultipartConfig();
        if (multipartConfig != null)
        {
            out.openTag("multipart-config", origin(md, s.getName()+".servlet.multipart-config"));
            if (multipartConfig.getLocation() != null)
                out.tag("location", multipartConfig.getLocation());
            out.tag("max-file-size", Long.toString(multipartConfig.getMaxFileSize()));
            out.tag("max-request-size", Long.toString(multipartConfig.getMaxRequestSize()));
            out.tag("file-size-threshold", Long.toString(multipartConfig.getFileSizeThreshold()));
            out.closeTag();
        }

        out.closeTag();
    } 

    @Override
    public void configure(WebAppContext context) throws Exception
    {
        MetaData metadata = context.getMetaData();
        metadata.resolve(context);

        Resource quickStartWebXml = _quickStartWebXml;
        if (_quickStartWebXml == null)
            quickStartWebXml = context.getBaseResource().addPath("/WEB-INF/quickstart-web.xml");
        if (!quickStartWebXml.exists())
            quickStartWebXml.getFile().createNewFile();
        try (FileOutputStream fos = new FileOutputStream(quickStartWebXml.getFile(),false))
        {
            generateQuickStartWebXml(context,fos);
        }
    } 

    public void preConfigure(WebAppContext context) throws Exception {
        
        MetaData meta = context.getMetaData();
        
        Resource baseResource = context.getBaseResource();
        
        addFiles(baseResource, meta);
        
    } 

    private void addFiles(Resource dir, MetaData meta) {
        for(String filePath : dir.list()) {
            try {
                Resource file = dir.addPath(filePath);
                
                if(file.getName().endsWith(".jar")) {
                    if(webInfJarsToInclude == null || webInfJarsToInclude.contains(file.getFile().getName())) {
                        System.out.println("Adding: "+file);
                        meta.addWebInfJar(file);
                    }
                } else if(file.isDirectory()) {
                    addFiles(file, meta);
                }
            } catch(Exception e) {
                System.out.println(""+e);
            }
        }
    } 

    private static void applyMetaInfResourcesAndFragmentXml(WebAppContext ctx) throws IOException{
    	String[] metaInfResources = Misc.findClasspathResources("META-INF/resources");
    	Resource[] collection=new Resource[]{
        		ctx.getBaseResource(),
        		new ResourceCollection(metaInfResources)
        };
        ctx.setBaseResource(new ResourceCollection(collection));

    	String[] fragmentXmls = Misc.findClasspathResources("META-INF/web-fragment.xml");
    	Arrays.sort(fragmentXmls);
        final MetaData metaData = ctx.getMetaData();
        metaData.setOrdering(new Ordering.RelativeOrdering(metaData));
        List<Resource> jarResources = new ArrayList<Resource>();
        List<Resource> dirResources = new ArrayList<Resource>();
    	for (int i = 0; i < fragmentXmls.length; i++) {
			String xmlRes = fragmentXmls[i];
			if (xmlRes.startsWith("jar:")){
				String jarRes = xmlRes.substring("jar:".length(), xmlRes.length()-"!/META-INF/web-fragment.xml".length());
				jarResources.add(Resource.newResource(jarRes));
			}else{
				String dirRes = xmlRes.substring(0, xmlRes.length()-"/META-INF/web-fragment.xml".length());
				dirResources.add(Resource.newResource(dirRes));
			}
		}
    	metaData.setWebInfClassesDirs(dirResources);
    	for (Resource r: jarResources){
    		metaData.addWebInfJar(r);
    	}
    	metaData.orderFragments();
    } 

    private void updateMetaData(MetaData metaData) {
        List<Class<?>> appClasses = getApplicationClasses();

        List<Resource> resources = appClasses.stream().map(c -> Resource.newResource(c.getProtectionDomain().getCodeSource().getLocation())).collect(Collectors.toList());

        metaData.setWebInfClassesDirs(resources);
    } 

    }

    private void outholder(XmlAppendable out, MetaData md, ServletHolder holder) throws IOException
    {
        
        if (LOG.isDebugEnabled())
            out.openTag("servlet",Collections.singletonMap("source",holder.getSource().toString()));
        else
            out.openTag("servlet");
        
        String n = holder.getName();
        out.tag("servlet-name",n);

        String ot = n + ".servlet.";

        ServletHolder s = (ServletHolder)holder;
        if (s.getForcedPath() != null && s.getClassName() == null)
            out.tag("jsp-file",s.getForcedPath());
        else
            out.tag("servlet-class",origin(md,ot + "servlet-class"),s.getClassName());

        for (String p : holder.getInitParameters().keySet())
        {
                continue;
            out.openTag("init-param",origin(md,ot + "init-param." + p))
            .tag("param-name",p)
            .tag("param-value",holder.getInitParameter(p))
            .closeTag();
        }

        if (s.getInitOrder() >= 0)
            out.tag("load-on-startup",Integer.toString(s.getInitOrder()));

        if (!s.isEnabled())
            out.tag("enabled",origin(md,ot + "enabled"),"false");

        out.tag("async-supported",origin(md,ot + "async-supported"),holder.isAsyncSupported()?"true":"false");

        if (s.getRunAsRole() != null)
            out.openTag("run-as",origin(md,ot + "run-as"))
            .tag("role-name",s.getRunAsRole())
            .closeTag();

        Map<String,String> roles = s.getRoleRefMap();
        if (roles!=null)
        {
            for (Map.Entry<String, String> e : roles.entrySet())
            {
                out.openTag("security-role-ref",origin(md,ot+"role-name."+e.getKey()))
                .tag("role-name",e.getKey())
                .tag("role-link",e.getValue())
                .closeTag();
            }
        }

        MultipartConfigElement multipartConfig = ((ServletHolder.Registration)s.getRegistration()).getMultipartConfig();
        if (multipartConfig != null)
        {
            out.openTag("multipart-config", origin(md, s.getName()+".servlet.multipart-config"));
            if (multipartConfig.getLocation() != null)
                out.tag("location", multipartConfig.getLocation());
            out.tag("max-file-size", Long.toString(multipartConfig.getMaxFileSize()));
            out.tag("max-request-size", Long.toString(multipartConfig.getMaxRequestSize()));
            out.tag("file-size-threshold", Long.toString(multipartConfig.getFileSizeThreshold()));
            out.closeTag();
        }

        out.closeTag();
    } 

    
    private void outholder(XmlAppendable out, MetaData md, FilterHolder holder) throws IOException
    {
        if (LOG.isDebugEnabled())
            out.openTag("filter",Collections.singletonMap("source",holder.getSource().toString()));
        else
            out.openTag("filter");
        
        String n = holder.getName();
        out.tag("filter-name",n);

        String ot = n + ".filter.";
        
        if (holder instanceof FilterHolder)
        {
            out.tag("filter-class",origin(md,ot + "filter-class"),holder.getClassName());
            out.tag("async-supported",origin(md,ot + "async-supported"),holder.isAsyncSupported()?"true":"false");
        }
        
        for (String p : holder.getInitParameters().keySet())
        {
            out.openTag("init-param",origin(md,ot + "init-param." + p))
            .tag("param-name",p)
            .tag("param-value",holder.getInitParameter(p))
            .closeTag();
        }

        out.closeTag();
    } 

    
    public Map<String, String> origin(MetaData md, String name)
    {
        if (!_generateOrigin)
            return Collections.emptyMap();
        if (name == null)
            return Collections.emptyMap();
        OriginInfo origin = md.getOriginInfo(name);
        if (LOG.isDebugEnabled()) LOG.debug("origin of "+name+" is "+origin);
        if (origin == null)
            return Collections.emptyMap();
        return Collections.singletonMap(_originAttribute,origin.toString()+":"+(_count++));
    } 

    }

    public void handleField(Class clazz, Field field)
    {
        Resource resource = (Resource)field.getAnnotation(Resource.class);
        if (resource != null)
        {
            if (Modifier.isStatic(field.getModifiers()))
            {
                Log.warn("Skipping Resource annotation on "+clazz.getName()+"."+field.getName()+": cannot be static");
                return;
            }

            if (Modifier.isFinal(field.getModifiers()))
            {
                Log.warn("Skipping Resource annotation on "+clazz.getName()+"."+field.getName()+": cannot be final");
                return;
            }

            String name = clazz.getCanonicalName()+"/"+field.getName();     
           
            name = (resource.name()!=null && !resource.name().trim().equals("")? resource.name(): name);
            String mappedName = (resource.mappedName()!=null && !resource.mappedName().trim().equals("")?resource.mappedName():null);
            Class type = field.getType();
            
            MetaData metaData = _context.getMetaData();
            if (metaData.getOriginDescriptor("resource-ref."+name+".injection") != null)
            {
                return;
            }

            InjectionCollection injections = (InjectionCollection)_context.getAttribute(InjectionCollection.INJECTION_COLLECTION);
            if (injections == null)
            {
                injections = new InjectionCollection();
                _context.setAttribute(InjectionCollection.INJECTION_COLLECTION, injections);
            }
            Injection injection = injections.getInjection(name, clazz, field);
            if (injection == null)
            {
                try
                {
                    boolean bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context, name, mappedName);
                    if (!bound)
                        bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context.getServer(), name, mappedName);
                    if (!bound)
                        bound =  org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(null, name, mappedName); 
                    if (!bound)
                    {
                        try
                        {
                            InitialContext ic = new InitialContext();
                            String nameInEnvironment = (mappedName!=null?mappedName:name);
                            ic.lookup("java:comp/env/"+nameInEnvironment);                               
                            bound = true;
                        }
                        catch (NameNotFoundException e)
                        {
                            bound = false;
                        }
                    }
                    if (bound)
                    { 
                        Log.debug("Bound "+(mappedName==null?name:mappedName) + " as "+ name);
                        injection = new Injection();
                        injection.setTarget(clazz, field, type);
                        injection.setJndiName(name);
                        injection.setMappingName(mappedName);
                        injections.add(injection); 
                        
                        metaData.setOrigin("resource-ref."+name+".injection");
                    }  
                    else if (!Util.isEnvEntryType(type))
                    {   

                        throw new IllegalStateException("No resource at "+(mappedName==null?name:mappedName));
                    }
                }
                catch (NamingException e)
                {
                    if (!Util.isEnvEntryType(type))
                        throw new IllegalStateException(e);
                }
            }
        }
    } 

Advertisement
Javadoc
MetaData All data associated with the configuration and deployment of a web application.
Advertisement