/** * Set up the execution classpath for Jasper. * * <p>Put everything in the classesDirectory and all of the dependencies on the classpath. * * @returns a list of the urls of the dependencies * @throws Exception */ private List<URL> setUpWebAppClassPath() throws Exception { // add any classes from the webapp List<URL> urls = new ArrayList<URL>(); String classesDir = classesDirectory.getCanonicalPath(); classesDir = classesDir + (classesDir.endsWith(File.pathSeparator) ? "" : File.separator); urls.add(Resource.toURL(new File(classesDir))); if (getLog().isDebugEnabled()) getLog().debug("Adding to classpath classes dir: " + classesDir); // add the dependencies of the webapp (which will form WEB-INF/lib) for (Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); ) { Artifact artifact = (Artifact) iter.next(); // Include runtime and compile time libraries if (!Artifact.SCOPE_TEST.equals(artifact.getScope()) && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) { String filePath = artifact.getFile().getCanonicalPath(); if (getLog().isDebugEnabled()) getLog().debug("Adding to classpath dependency file: " + filePath); urls.add(Resource.toURL(artifact.getFile())); } } return urls; }
/** * Look for jars in WEB-INF/lib * * @param context * @return the list of jar resources found within context * @throws Exception */ protected List<Resource> findJars(WebAppContext context) throws Exception { List<Resource> jarResources = new ArrayList<Resource>(); Resource web_inf = context.getWebInf(); if (web_inf == null || !web_inf.exists()) return null; Resource web_inf_lib = web_inf.addPath("/lib"); if (web_inf_lib.exists() && web_inf_lib.isDirectory()) { String[] files = web_inf_lib.list(); for (int f = 0; files != null && f < files.length; f++) { try { Resource file = web_inf_lib.addPath(files[f]); String fnlc = file.getName().toLowerCase(Locale.ENGLISH); int dot = fnlc.lastIndexOf('.'); String extension = (dot < 0 ? null : fnlc.substring(dot)); if (extension != null && (extension.equals(".jar") || extension.equals(".zip"))) { jarResources.add(file); } } catch (Exception ex) { LOG.warn(Log.EXCEPTION, ex); } } } return jarResources; }
/** * Parse a single entry in a jar file * * @param jar * @param entry * @param resolver * @throws Exception */ protected void parseJarEntry(URI jar, JarEntry entry, final ClassNameResolver resolver) throws Exception { if (jar == null || entry == null) return; // skip directories if (entry.isDirectory()) return; String name = entry.getName(); // check file is a valid class file name if (isValidClassFileName(name) && isValidClassFilePath(name)) { String shortName = name.replace('/', '.').substring(0, name.length() - 6); if ((resolver == null) || (!resolver.isExcluded(shortName) && (!isParsed(shortName) || resolver.shouldOverride(shortName)))) { Resource clazz = Resource.newResource("jar:" + jar + "!/" + name); if (LOG.isDebugEnabled()) { LOG.debug("Scanning class from jar {}", clazz); } ; scanClass(clazz.getInputStream()); } } }
/* ------------------------------------------------------------ */ private HttpContent load(String pathInContext, Resource resource) throws IOException { Content content = null; if (resource == null || !resource.exists()) return null; // Will it fit in the cache? if (!resource.isDirectory() && isCacheable(resource)) { // Create the Content (to increment the cache sizes before adding the content content = new Content(pathInContext, resource); // reduce the cache to an acceptable size. shrinkCache(); // Add it to the cache. Content added = _cache.putIfAbsent(pathInContext, content); if (added != null) { content.invalidate(); content = added; } return content; } return new HttpContent.ResourceAsHttpContent( resource, _mimeTypes.getMimeByExtension(resource.toString()), getMaxCachedFileSize(), _etags); }
/** * Parse a resource that is a jar file. * * @param jarResource * @param resolver * @throws Exception */ public void parseJar(Resource jarResource, final ClassNameResolver resolver) throws Exception { if (jarResource == null) return; URI uri = jarResource.getURI(); if (jarResource.toString().endsWith(".jar")) { if (LOG.isDebugEnabled()) { LOG.debug("Scanning jar {}", jarResource); } ; // treat it as a jar that we need to open and scan all entries from InputStream in = jarResource.getInputStream(); if (in == null) return; JarInputStream jar_in = new JarInputStream(in); try { JarEntry entry = jar_in.getNextJarEntry(); while (entry != null) { parseJarEntry(uri, entry, resolver); entry = jar_in.getNextJarEntry(); } } finally { jar_in.close(); } } }
@Before public void setUp() throws Exception { Resource configRes = Resource.newClassPathResource("/org/eclipse/jetty/monitor/jetty-monitor-service.xml"); XmlConfiguration xmlConfig = new XmlConfiguration(configRes.getURL()); xmlConfig.configure(); }
/** * Check to see if the ServletContainerIntializer loaded via the ServiceLoader came from a jar * that is excluded by the fragment ordering. See ServletSpec 3.0 p.85. * * @param context * @param sci * @return true if excluded */ public boolean isFromExcludedJar( WebAppContext context, ServletContainerInitializer sci, Resource sciResource) throws Exception { if (sci == null) throw new IllegalArgumentException("ServletContainerInitializer null"); if (context == null) throw new IllegalArgumentException("WebAppContext null"); if (LOG.isDebugEnabled()) LOG.debug("Checking {} for jar exclusion", sci); // A ServletContainerInitializer that came from the container's classpath cannot be excluded by // an ordering // of WEB-INF/lib jars if (isFromContainerClassPath(context, sci)) return false; List<Resource> orderedJars = context.getMetaData().getOrderedWebInfJars(); // If no ordering, nothing is excluded if (context.getMetaData().getOrdering() == null) return false; // there is an ordering, but there are no jars resulting from the ordering, everything excluded if (orderedJars.isEmpty()) return true; if (sciResource == null) return false; // not from a jar therefore not from WEB-INF so not excludable URI loadingJarURI = sciResource.getURI(); boolean found = false; Iterator<Resource> itor = orderedJars.iterator(); while (!found && itor.hasNext()) { Resource r = itor.next(); found = r.getURI().equals(loadingJarURI); } return !found; }
public void doStart() { try { TaskLog.logWithTimestamp("Starting web application " + this.getDescriptor()); if (jettyEnvXml != null && jettyEnvXml.exists()) envConfiguration.setJettyEnvXml(Resource.toURL(jettyEnvXml)); ClassLoader parentLoader = this.getClass().getClassLoader(); if (parentLoader instanceof AntClassLoader) parentLoader = new AntURLClassLoader((AntClassLoader) parentLoader); setClassLoader(new WebAppClassLoader(parentLoader, this)); if (attributes != null && attributes.getAttributes() != null) { for (Attribute a : attributes.getAttributes()) setAttribute(a.getName(), a.getValue()); } // apply a context xml file if one was supplied if (contextXml != null) { XmlConfiguration xmlConfiguration = new XmlConfiguration(Resource.toURL(contextXml)); TaskLog.log("Applying context xml file " + contextXml); xmlConfiguration.configure(this); } super.doStart(); } catch (Exception e) { TaskLog.log(e.toString()); } }
@Override public Resource getJarFor(ServletContainerInitializer service) throws MalformedURLException, IOException { Resource resource = super.getJarFor(service); // TODO This is not correct, but implemented like this to be bug for bug compatible // with previous implementation that could only handle actual jars and not bundles. if (resource != null && !resource.toString().endsWith(".jar")) return null; return resource; }
public File findWorkDirectory(WebAppContext context) throws IOException { if (context.getBaseResource() != null) { Resource web_inf = context.getWebInf(); if (web_inf != null && web_inf.exists()) { return new File(web_inf.getFile(), "work"); } } return null; }
/* ------------------------------------------------------------ */ boolean isValid() { if (_lastModified == _resource.lastModified() && _length == _resource.length()) { _lastAccessed = System.currentTimeMillis(); return true; } if (this == _cache.remove(_key)) invalidate(); return false; }
/* ------------------------------------------------------------ */ @Override public String toString() { return String.format( "%s %s %d %s %s", _resource, _resource.exists(), _resource.lastModified(), _contentType, _lastModifiedBytes); }
/** * Get the resource list as a HTML directory listing. * * @param base The base URL * @param parent True if the parent directory should be included * @return String of HTML */ public String getListHTML(String base, boolean parent) throws IOException { base = URIUtil.canonicalPath(base); if (base == null || !isDirectory()) return null; String[] ls = list(); if (ls == null) return null; Arrays.sort(ls); String decodedBase = URIUtil.decodePath(base); String title = "Directory: " + deTag(decodedBase); StringBuilder buf = new StringBuilder(4096); buf.append("<HTML><HEAD>"); buf.append("<LINK HREF=\"") .append("jetty-dir.css") .append("\" REL=\"stylesheet\" TYPE=\"text/css\"/><TITLE>"); buf.append(title); buf.append("</TITLE></HEAD><BODY>\n<H1>"); buf.append(title); buf.append("</H1>\n<TABLE BORDER=0>\n"); if (parent) { buf.append("<TR><TD><A HREF=\""); buf.append(URIUtil.addPaths(base, "../")); buf.append("\">Parent Directory</A></TD><TD></TD><TD></TD></TR>\n"); } String encodedBase = hrefEncodeURI(base); DateFormat dfmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); for (int i = 0; i < ls.length; i++) { Resource item = addPath(ls[i]); buf.append("\n<TR><TD><A HREF=\""); String path = URIUtil.addPaths(encodedBase, URIUtil.encodePath(ls[i])); buf.append(path); if (item.isDirectory() && !path.endsWith("/")) buf.append(URIUtil.SLASH); // URIUtil.encodePath(buf,path); buf.append("\">"); buf.append(deTag(ls[i])); buf.append(" "); buf.append("</A></TD><TD ALIGN=right>"); buf.append(item.length()); buf.append(" bytes </TD><TD>"); buf.append(dfmt.format(new Date(item.lastModified()))); buf.append("</TD></TR>"); } buf.append("</TABLE>\n"); buf.append("</BODY></HTML>\n"); return buf.toString(); }
/** * Start Jetty web server * * @param version of bigloupe-chart * @return * @throws Exception */ private Server startWebServer(String version) throws Exception { if (!cmd.hasOption(OPTION_NO_WEBSERVER)) { applyOptionWithWebServer(); Server server = new Server(getPortWebServer()); WebAppContext root = new WebAppContext(); root.setContextPath("/"); if (cmd.hasOption(OPTION_WEBSERVER_WEBROOT)) { String webRoot = cmd.getOptionValue(OPTION_WEBSERVER_WEBROOT); Resource resource = FileResource.newResource(webRoot); root.setBaseResource(resource); } else { String webFiles = "bigloupe-chart-" + version + "-webapp.war"; File fileWebApp = new File(webFiles); if (!fileWebApp.exists()) { if (version.equals("'undefined'")) { Resource resource = FileResource.newResource("src/main/webapp"); root.setBaseResource(resource); root.setDefaultsDescriptor("./etc/webdefault.xml"); logger.info( "Embedded webServer started with base resource " + resource.getFile().getAbsolutePath()); } else { logger.info(webFiles + " file not available"); logger.info("Embedded webServer will be not started"); return null; } } else { root.setWar(fileWebApp.getAbsolutePath()); } } File tmp = new File("tmp"); if (!tmp.exists()) tmp.mkdir(); root.setTempDirectory(tmp); ContextHandlerCollection contexts = new ContextHandlerCollection(); Handler handlerHawtIO = addWebApplicationHawtIO(); if (handlerHawtIO != null) contexts.setHandlers(new Handler[] {root, handlerHawtIO}); else contexts.setHandlers(new Handler[] {root}); server.setHandler(contexts); server.start(); addWebServerJMXSupport(server); return server; } else { applyOptionWithoutWebServer(); return null; } }
/** * Overriden method which, contrary to the original implementation in the parent class, add * directly the web-fragment.xml resource to the MetaData, instead of re-creating it with a forced * jar prefix. */ @Override @SuppressWarnings("unchecked") public void findWebFragments(final WebAppContext context, final MetaData metaData) throws Exception { List<Resource> frags = (List<Resource>) context.getAttribute(FRAGMENT_RESOURCES); if (frags != null) { for (Resource frag : frags) { Resource parentResource = Util.chop(frag.getURL(), "/META-INF/web-fragment.xml"); metaData.addFragment(parentResource, frag); } } }
@Test public void testStandardTestWar() throws Exception { PreconfigureStandardTestWar.main(new String[] {}); WebDescriptor descriptor = new WebDescriptor( Resource.newResource( "./target/test-standard-preconfigured/WEB-INF/quickstart-web.xml")); descriptor.setValidating(true); descriptor.parse(); Node node = descriptor.getRoot(); assertThat(node, Matchers.notNullValue()); System.setProperty("jetty.home", "target"); // war file or dir to start String war = "target/test-standard-preconfigured"; // optional jetty context xml file to configure the webapp Resource contextXml = Resource.newResource("src/test/resources/test.xml"); Server server = new Server(0); QuickStartWebApp webapp = new QuickStartWebApp(); webapp.setAutoPreconfigure(true); webapp.setWar(war); webapp.setContextPath("/"); // apply context xml file if (contextXml != null) { // System.err.println("Applying "+contextXml); XmlConfiguration xmlConfiguration = new XmlConfiguration(contextXml.getURL()); xmlConfiguration.configure(webapp); } server.setHandler(webapp); server.start(); URL url = new URL( "http://127.0.0.1:" + server.getBean(NetworkConnector.class).getLocalPort() + "/test/dump/info"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); assertEquals(200, connection.getResponseCode()); assertThat( IO.toString((InputStream) connection.getContent()), Matchers.containsString("Dump Servlet")); server.stop(); }
/** * Parse the given classes * * @param classNames * @param resolver * @throws Exception */ public void parse(List<String> classNames, ClassNameResolver resolver) throws Exception { for (String s : classNames) { if ((resolver == null) || (!resolver.isExcluded(s) && (!isParsed(s) || resolver.shouldOverride(s)))) { s = s.replace('.', '/') + ".class"; URL resource = Loader.getResource(this.getClass(), s, false); if (resource != null) { Resource r = Resource.newResource(resource); scanClass(r.getInputStream()); } } } }
/* ------------------------------------------------------------ */ @Test public void testJarFileLastModified() throws Exception { String s = "jar:" + __userURL + "TestData/test.zip!/subdir/numbers"; ZipFile zf = new ZipFile( MavenTestingUtils.getProjectFile( "src/test/resources/org/eclipse/jetty/util/resource/TestData/test.zip")); long last = zf.getEntry("subdir/numbers").getTime(); Resource r = Resource.newResource(s); assertEquals(last, r.lastModified()); }
/** * Parse a given class * * @param className * @param resolver * @throws Exception */ public void parse(String className, ClassNameResolver resolver) throws Exception { if (className == null) return; if (!resolver.isExcluded(className)) { if (!isParsed(className) || resolver.shouldOverride(className)) { className = className.replace('.', '/') + ".class"; URL resource = Loader.getResource(this.getClass(), className, false); if (resource != null) { Resource r = Resource.newResource(resource); scanClass(r.getInputStream()); } } } }
@Test public void testJarFileIsContainedIn() throws Exception { String s = "jar:" + __userURL + "TestData/test.zip!/subdir/"; Resource r = Resource.newResource(s); Resource container = Resource.newResource(__userURL + "TestData/test.zip"); assertTrue(r instanceof JarFileResource); JarFileResource jarFileResource = (JarFileResource) r; assertTrue(jarFileResource.isContainedIn(container)); container = Resource.newResource(__userURL + "TestData"); assertFalse(jarFileResource.isContainedIn(container)); }
/** Test a class path resource for existence. */ @Test public void testClassPathResourceClassAbsolute() { final String classPathName = "/org/eclipse/jetty/util/resource/Resource.class"; Resource resource = Resource.newClassPathResource(classPathName); assertTrue(resource != null); // A class path cannot be a directory assertFalse("Class path cannot be a directory.", resource.isDirectory()); // A class path must exist assertTrue("Class path resource does not exist.", resource.exists()); }
/** Test a class path resource for existence. */ @Test public void testClassPathResourceClassRelative() { final String classPathName = "Resource.class"; Resource resource = Resource.newClassPathResource(classPathName); assertTrue(resource != null); // A class path cannot be a directory assertFalse("Class path cannot be a directory.", resource.isDirectory()); // A class path must exist assertTrue("Class path resource does not exist.", resource.exists()); }
protected void applyMetaInfContextXml(Resource rootResource) throws Exception { if (_bundle == null) return; if (_webApp == null) return; ClassLoader cl = Thread.currentThread().getContextClassLoader(); LOG.debug("Context classloader = " + cl); try { Thread.currentThread().setContextClassLoader(_webApp.getClassLoader()); // TODO replace this with getting the InputStream so we don't cache in URL // find if there is a META-INF/context.xml file URL contextXmlUrl = _bundle.getEntry("/META-INF/jetty-webapp-context.xml"); if (contextXmlUrl == null) return; // Apply it just as the standard jetty ContextProvider would do LOG.info("Applying " + contextXmlUrl + " to " + _webApp); XmlConfiguration xmlConfiguration = new XmlConfiguration(contextXmlUrl); HashMap properties = new HashMap(); properties.put("Server", getDeploymentManager().getServer()); properties.put(OSGiWebappConstants.JETTY_BUNDLE_ROOT, rootResource.toString()); properties.put( OSGiServerConstants.JETTY_HOME, getDeploymentManager().getServer().getAttribute(OSGiServerConstants.JETTY_HOME)); xmlConfiguration.getProperties().putAll(properties); xmlConfiguration.configure(_webApp); } finally { Thread.currentThread().setContextClassLoader(cl); } }
private static Handler resourceHandler() { ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setBaseResource(Resource.newClassPathResource("/web", false, false)); resourceHandler.setWelcomeFiles(new String[] {"index.html"}); resourceHandler.setMinMemoryMappedContentLength(-1); return resourceHandler; }
/* ------------------------------------------------------------ */ public InputStream getInputStream() throws IOException { Buffer indirect = getIndirectBuffer(); if (indirect != null && indirect.array() != null) return new ByteArrayInputStream(indirect.array(), indirect.getIndex(), indirect.length()); return _resource.getInputStream(); }
/** Test a class path resource for directories. */ @Test public void testClassPathResourceDirectory() throws Exception { final String classPathName = "/"; Resource resource = Resource.newClassPathResource(classPathName); assertTrue(resource != null); // A class path must be a directory assertTrue("Class path must be a directory.", resource.isDirectory()); assertTrue("Class path returned file must be a directory.", resource.getFile().isDirectory()); // A class path must exist assertTrue("Class path resource does not exist.", resource.exists()); }
private void addDependencies(final MavenProject project, final JettyWebAppContext webAppConfig) throws Exception { List<File> dependencyFiles = new ArrayList<File>(); List<Resource> overlays = new ArrayList<Resource>(); for (Artifact artifact : project.getArtifacts()) { if (artifact.getType().equals("war")) { overlays.add(Resource.newResource("jar:" + artifact.getFile().toURL().toString() + "!/")); } else if ((!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) && (!Artifact.SCOPE_TEST.equals(artifact.getScope()))) { File dependencyFile = artifact.getFile(); if (dependencyFile == null || !dependencyFile.exists()) { String coordinates = String.format( "%s:%s:%s", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); LOG.log( Level.WARNING, "Dependency '" + coordinates + "' does not exist in repository. Skipping!"); continue; } dependencyFiles.add(artifact.getFile()); } } webAppConfig.setOverlays(overlays); webAppConfig.setWebInfLib(dependencyFiles); }
/* ------------------------------------------------------------ */ protected ByteBuffer getDirectBuffer(Resource resource) { // Only use file mapped buffers for cached resources, otherwise too much virtual memory // commitment for // a non shared resource. Also ignore max buffer size try { if (_useFileMappedBuffer && resource.getFile() != null && resource.length() < Integer.MAX_VALUE) return BufferUtil.toMappedBuffer(resource.getFile()); return BufferUtil.toBuffer(resource, true); } catch (IOException | IllegalArgumentException e) { LOG.warn(e); return null; } }
Data(String url, boolean exists, boolean dir, String content) throws Exception { this.test = url; this.exists = exists; this.dir = dir; this.content = content; resource = Resource.newResource(url); }
public static void main(String[] args) throws Exception { // Create the Server object and a corresponding ServerConnector and then set the port for the // connector. In // this example the server will listen on port 8090. If you set this to port 0 then when the // server has been // started you can called connector.getLocalPort() to programmatically get the port the server // started on. Server server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(8090); server.setConnectors(new Connector[] {connector}); // Create a Context Handler and ResourceHandler. The ContextHandler is getting set to "/" path // but this could // be anything you like for builing out your url. Note how we are setting the ResourceBase using // our jetty // maven testing utilities to get the proper resource directory, you needn't use these, // you simply need to supply the paths you are looking to serve content from. ContextHandler context0 = new ContextHandler(); context0.setContextPath("/"); ResourceHandler rh0 = new ResourceHandler(); rh0.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir0"))); context0.setHandler(rh0); // Rinse and repeat the previous item, only specifying a different resource base. ContextHandler context1 = new ContextHandler(); context1.setContextPath("/"); ResourceHandler rh1 = new ResourceHandler(); rh1.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir1"))); context1.setHandler(rh1); // Create a ContextHandlerCollection and set the context handlers to it. This will let jetty // process urls // against the declared contexts in order to match up content. ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] {context0, context1}); server.setHandler(contexts); // Start things up! By using the server.join() the server thread will join with the current // thread. // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more // details. server.start(); System.err.println(server.dump()); server.join(); }