@Override public Resource getResource(String uriInContext) throws MalformedURLException { Resource resource = null; // Try to get regular resource resource = super.getResource(uriInContext); // If no regular resource exists check for access to /WEB-INF/lib or /WEB-INF/classes if ((resource == null || !resource.exists()) && uriInContext != null && _classes != null) { String uri = URIUtil.canonicalPath(uriInContext); if (uri == null) return null; try { // Replace /WEB-INF/classes with candidates for the classpath if (uri.startsWith(WEB_INF_CLASSES_PREFIX)) { if (uri.equalsIgnoreCase(WEB_INF_CLASSES_PREFIX) || uri.equalsIgnoreCase(WEB_INF_CLASSES_PREFIX + "/")) { // exact match for a WEB-INF/classes, so preferentially return the resource matching the // web-inf classes // rather than the test classes if (_classes != null) return Resource.newResource(_classes); else if (_testClasses != null) return Resource.newResource(_testClasses); } else { // try matching Resource res = null; int i = 0; while (res == null && (i < _webInfClasses.size())) { String newPath = uri.replace(WEB_INF_CLASSES_PREFIX, _webInfClasses.get(i).getPath()); res = Resource.newResource(newPath); if (!res.exists()) { res = null; i++; } } return res; } } else if (uri.startsWith(WEB_INF_LIB_PREFIX)) { // Return the real jar file for all accesses to // /WEB-INF/lib/*.jar String jarName = uri.replace(WEB_INF_LIB_PREFIX, ""); if (jarName.startsWith("/") || jarName.startsWith("\\")) jarName = jarName.substring(1); if (jarName.length() == 0) return null; File jarFile = _webInfJarMap.get(jarName); if (jarFile != null) return Resource.newResource(jarFile.getPath()); return null; } } catch (MalformedURLException e) { throw e; } catch (IOException e) { LOG.ignore(e); } } return resource; }
@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(); }
public List<File> initScanFiles() { List<File> scanList = new ArrayList<File>(); if (getDescriptor() != null) { try { Resource r = Resource.newResource(getDescriptor()); scanList.add(r.getFile()); } catch (IOException e) { throw new BuildException(e); } } if (getJettyEnvXml() != null) { try { Resource r = Resource.newResource(getJettyEnvXml()); scanList.add(r.getFile()); } catch (IOException e) { throw new BuildException("Problem configuring scanner for jetty-env.xml", e); } } if (getDefaultsDescriptor() != null) { try { if (!AntWebAppContext.WEB_DEFAULTS_XML.equals(getDefaultsDescriptor())) { Resource r = Resource.newResource(getDefaultsDescriptor()); scanList.add(r.getFile()); } } catch (IOException e) { throw new BuildException("Problem configuring scanner for webdefaults.xml", e); } } if (getOverrideDescriptor() != null) { try { Resource r = Resource.newResource(getOverrideDescriptor()); scanList.add(r.getFile()); } catch (IOException e) { throw new BuildException("Problem configuring scanner for webdefaults.xml", e); } } // add any extra classpath and libs List<File> cpFiles = getClassPathFiles(); if (cpFiles != null) scanList.addAll(cpFiles); // any extra scan targets @SuppressWarnings("unchecked") List<File> scanFiles = (List<File>) getScanTargetFiles(); if (scanFiles != null) scanList.addAll(scanFiles); return scanList; }
@Override public Resource getResource(String uriInContext) throws MalformedURLException { Resource resource = null; // Try to get regular resource // replacer.getAutoconfigTempDirectory().getAbsolutePath() try { resource = getAutoconfigResource(uriInContext); if (resource == null) { // resource = super.getResource(uriInContext); resource = getResourceFromMavenOrSuper(uriInContext); } } catch (Exception e) { logger.warn("find autoconfig resource error! " + uriInContext, e); } // If no regular resource exists check for access to /WEB-INF/lib or /WEB-INF/classes if ((resource == null || !resource.exists()) && uriInContext != null && webInfClasses != null) { String uri = URIUtil.canonicalPath(uriInContext); try { // Replace /WEB-INF/classes with real classes directory if (uri.startsWith(WEB_INF_CLASSES_PREFIX)) { Resource res = null; int i = 0; while (res == null && (i < webInfClasses.size())) { String newPath = uri.replace(WEB_INF_CLASSES_PREFIX, webInfClasses.get(i).getPath()); res = Resource.newResource(newPath); if (!res.exists()) { res = null; i++; } } return res; } // Return the real jar file for all accesses to // /WEB-INF/lib/*.jar else if (uri.startsWith(WEB_INF_LIB_PREFIX)) { String jarName = uri.replace(WEB_INF_LIB_PREFIX, ""); if (jarName.startsWith("/") || jarName.startsWith("\\")) jarName = jarName.substring(1); if (jarName.length() == 0) return null; File jarFile = webInfJarMap.get(jarName); if (jarFile != null) return Resource.newResource(jarFile.getPath()); return null; } } catch (MalformedURLException e) { throw e; } catch (IOException e) { Log.ignore(e); } } return resource; }
@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 public void testJarFile() throws Exception { String s = "jar:" + __userURL + "TestData/test.zip!/subdir/"; Resource r = Resource.newResource(s); Set<String> entries = new HashSet<>(Arrays.asList(r.list())); assertEquals(3, entries.size()); assertTrue(entries.contains("alphabet")); assertTrue(entries.contains("numbers")); assertTrue(entries.contains("subsubdir/")); File extract = File.createTempFile("extract", null); if (extract.exists()) extract.delete(); extract.mkdir(); extract.deleteOnExit(); r.copyTo(extract); Resource e = Resource.newResource(extract.getAbsolutePath()); entries = new HashSet<>(Arrays.asList(e.list())); assertEquals(3, entries.size()); assertTrue(entries.contains("alphabet")); assertTrue(entries.contains("numbers")); assertTrue(entries.contains("subsubdir/")); IO.delete(extract); s = "jar:" + __userURL + "TestData/test.zip!/subdir/subsubdir/"; r = Resource.newResource(s); entries = new HashSet<>(Arrays.asList(r.list())); assertEquals(2, entries.size()); assertTrue(entries.contains("alphabet")); assertTrue(entries.contains("numbers")); extract = File.createTempFile("extract", null); if (extract.exists()) extract.delete(); extract.mkdir(); extract.deleteOnExit(); r.copyTo(extract); e = Resource.newResource(extract.getAbsolutePath()); entries = new HashSet<>(Arrays.asList(e.list())); assertEquals(2, entries.size()); assertTrue(entries.contains("alphabet")); assertTrue(entries.contains("numbers")); IO.delete(extract); }
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); }
/** * 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 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); }
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(); }
/* ------------------------------------------------------------ */ @Test public void testEncoding() throws Exception { Resource r = Resource.newResource("/tmp/a file with,spe#ials/"); assertTrue(r.getURL().toString().indexOf("a%20file%20with,spe%23ials") > 0); assertTrue(r.getFile().toString().indexOf("a file with,spe#ials") > 0); r.delete(); assertFalse("File should have been deleted.", r.exists()); }
private Resource getFileAsResource(File dir, String file) { Resource r = null; try { File asFile = new File(dir, file); if (asFile.exists()) r = Resource.newResource(asFile); } catch (Exception e) { r = null; } return r; }
/** * Look for any web-fragment.xml fragments in META-INF of jars in WEB-INF/lib * * @throws Exception */ public void findWebFragments(final WebAppContext context, final MetaData metaData) throws Exception { @SuppressWarnings("unchecked") List<Resource> frags = (List<Resource>) context.getAttribute(FRAGMENT_RESOURCES); if (frags != null) { for (Resource frag : frags) { if (frag .isDirectory()) // tolerate the case where the library is a directory, not a jar. useful // for OSGi for example { metaData.addFragment( frag, Resource.newResource(frag.getURL() + "/META-INF/web-fragment.xml")); } else // the standard case: a jar most likely inside WEB-INF/lib { metaData.addFragment( frag, Resource.newResource("jar:" + frag.getURL() + "!/META-INF/web-fragment.xml")); } } } }
private List<Resource> getResources(ClassLoader aLoader) throws IOException { if (aLoader instanceof URLClassLoader) { List<Resource> _result = new ArrayList<Resource>(); URL[] _urls = ((URLClassLoader) aLoader).getURLs(); for (URL _url : _urls) { _result.add(Resource.newResource(_url)); } return _result; } return Collections.emptyList(); }
/* ------------------------------------------------------------ */ @Test public void testJarFileCopyToDirectoryTraversal() throws Exception { String s = "jar:" + __userURL + "TestData/extract.zip!/"; Resource r = Resource.newResource(s); assertTrue(r instanceof JarResource); JarResource jarResource = (JarResource) r; File destParent = File.createTempFile("copyjar", null); if (destParent.exists()) destParent.delete(); destParent.mkdir(); destParent.deleteOnExit(); File dest = new File(destParent.getCanonicalPath() + "/extract"); if (dest.exists()) dest.delete(); dest.mkdir(); dest.deleteOnExit(); jarResource.copyTo(dest); // dest contains only the valid entry; dest.getParent() contains only the dest directory assertEquals(1, dest.listFiles().length); assertEquals(1, dest.getParentFile().listFiles().length); FilenameFilter dotdotFilenameFilter = new FilenameFilter() { public boolean accept(File directory, String name) { return name.equals("dotdot.txt"); } }; assertEquals(0, dest.listFiles(dotdotFilenameFilter).length); assertEquals(0, dest.getParentFile().listFiles(dotdotFilenameFilter).length); FilenameFilter extractfileFilenameFilter = new FilenameFilter() { public boolean accept(File directory, String name) { return name.equals("extract-filenotdir"); } }; assertEquals(0, dest.listFiles(extractfileFilenameFilter).length); assertEquals(0, dest.getParentFile().listFiles(extractfileFilenameFilter).length); FilenameFilter currentDirectoryFilenameFilter = new FilenameFilter() { public boolean accept(File directory, String name) { return name.equals("current.txt"); } }; assertEquals(1, dest.listFiles(currentDirectoryFilenameFilter).length); assertEquals(0, dest.getParentFile().listFiles(currentDirectoryFilenameFilter).length); IO.delete(dest); assertFalse(dest.exists()); }
/* ------------------------------------------------------------ */ @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 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()); } } } }
/** * 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()); } } } }
@Override public void setWar(String path) { super.setWar(path); try { Resource war = Resource.newResource(path); if (war.exists() && war.isDirectory() && getDescriptor() == null) { Resource webXml = war.addPath("WEB-INF/web.xml"); setDescriptor(webXml.toString()); } } catch (IOException e) { throw new BuildException(e); } }
public Resource getJarFor(ServletContainerInitializer service) throws MalformedURLException, IOException { String loadingJarName = Thread.currentThread() .getContextClassLoader() .getResource(service.getClass().getName().replace('.', '/') + ".class") .toString(); int i = loadingJarName.indexOf(".jar"); if (i < 0) return null; // not from a jar loadingJarName = loadingJarName.substring(0, i + 4); loadingJarName = (loadingJarName.startsWith("jar:") ? loadingJarName.substring(4) : loadingJarName); return Resource.newResource(loadingJarName); }
/** * Parse the given class, optionally walking its inheritance hierarchy * * @param clazz * @param resolver * @param visitSuperClasses * @throws Exception */ public void parse(Class<?> clazz, ClassNameResolver resolver, boolean visitSuperClasses) throws Exception { Class<?> cz = clazz; while (cz != null) { if (!resolver.isExcluded(cz.getName())) { if (!isParsed(cz.getName()) || resolver.shouldOverride(cz.getName())) { String nameAsResource = cz.getName().replace('.', '/') + ".class"; URL resource = Loader.getResource(this.getClass(), nameAsResource, false); if (resource != null) { Resource r = Resource.newResource(resource); scanClass(r.getInputStream()); } } } if (visitSuperClasses) cz = cz.getSuperclass(); else cz = null; } }
public void matched(URI uri) throws Exception { LOG.debug("Search of {}", uri); if (uri.toString().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { InputStream in = Resource.newResource(uri).getInputStream(); if (in == null) return; JarInputStream jar_in = new JarInputStream(in); try { JarEntry entry = jar_in.getNextJarEntry(); while (entry != null) { processEntry(uri, entry); entry = jar_in.getNextJarEntry(); } } finally { jar_in.close(); } } }
public static void main(String[] args) { try { Resource serverResource = null; if (args == null || args.length == 0) { // 如果没有指定路径则默认使用本地classpath路径 serverResource = Resource.newClassPathResource(serverXmlPath); logger.info("没有系统启动配置文件,使用默认classpath下的文件serverXmlPath:classpath--->" + serverXmlPath); } else { // 绝对路径 serverXmlPath = args[0]; logger.info("使用输入参数配置文件,path:" + serverXmlPath); serverResource = Resource.newResource(serverXmlPath); } XmlConfiguration configuration = new XmlConfiguration(serverResource.getInputStream()); Server server = (Server) configuration.configure(); server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } }
/** * Glassfish jsp requires that we set up the list of system jars that have tlds in them. * * <p>This method is a little fragile, as it relies on knowing that the jstl jars are the only * ones in the system path that contain tlds. * * @return * @throws Exception */ private List<URL> getSystemJarsWithTlds() throws Exception { final List<URL> list = new ArrayList<URL>(); List<URI> artifactUris = new ArrayList<URI>(); Pattern pattern = Pattern.compile(tldJarNamePatterns); for (Iterator<Artifact> iter = pluginArtifacts.iterator(); iter.hasNext(); ) { Artifact pluginArtifact = iter.next(); artifactUris.add(Resource.newResource(pluginArtifact.getFile()).getURI()); } PatternMatcher matcher = new PatternMatcher() { public void matched(URI uri) throws Exception { // uri of system artifact matches pattern defining list of jars known to contain tlds list.add(uri.toURL()); } }; matcher.match(pattern, artifactUris.toArray(new URI[artifactUris.size()]), false); return list; }
public Resource getResourceFromMavenOrSuper(String uriContext) throws IOException { String relativePath = null; if (uriContext.startsWith(URIUtil.SLASH)) { relativePath = uriContext.substring(1); } else { relativePath = uriContext; } /** maven generated resource directory not exists */ if (mavenResourceTargetDirectory == null || !mavenResourceTargetDirectory.exists()) { return super.getResource(uriContext); } File targetFile = new File(mavenResourceTargetDirectory, relativePath); if (targetFile.exists()) { // get file from maven resource and ori resource String mavenResourcePath = targetFile.getAbsolutePath(); // maven generated resource file Resource oriResource = super.getResource(uriContext); // ori resource file File oriFile = oriResource.getFile(); if (Utils.isBinary(oriFile) || !Utils.hasPlaceholder(oriFile)) { // ignore the binary file return oriResource; } if (FileUtils.contentEquals(targetFile, oriFile)) { return oriResource; } else { if (oriFile.lastModified() >= targetFile.lastModified()) { return oriResource; } else { if (logger.isDebugEnabled()) logger.debug(uriContext + " maven replaced resource:" + mavenResourcePath); return Resource.newResource(mavenResourcePath); } } } return super.getResource(uriContext); }
private void startServer() throws Exception { jetty = new Server(0); final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); applicationContext.register(ConfigClass.class, getClass()); applicationContext.register(configurationClasses()); final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext)); final ServletContextHandler context = new ServletContextHandler(); context.setErrorHandler(null); // use Spring exception handler(s) context.setContextPath("/"); context.setBaseResource(Resource.newResource(new ClassPathResource("").getURI().toString())); context.setSessionHandler(new SessionHandler()); context.addServlet(servletHolder, "/"); jetty.setHandler(context); jetty.start(); }
public Resource getAutoconfigResource(String uriContext) throws IOException { String relativePath = null; // replacer.getAutoconfigTempDirectory() if (uriContext.startsWith(URIUtil.SLASH)) { relativePath = uriContext.substring(1); } else { relativePath = uriContext; } // path.startsWith(defaultWebAppSourceDirectory.getAbsolutePath()) if (autoconfigOutput.contains(relativePath)) { String resourcePath = autoconfigTempDirectory.getAbsolutePath() + File.separator + relativePath; if (logger.isDebugEnabled()) logger.debug(uriContext + " autoconfig replaced resource:" + resourcePath); return Resource.newResource(resourcePath); } return null; }
@Test public void testUncPathResourceFile() throws Exception { // This test is intended to run only on Windows platform assumeTrue(OS.IS_WINDOWS); String path = __userURL.toURI().getPath().replace('/', '\\') + "ResourceTest.java"; System.err.println(path); Resource resource = Resource.newResource(path, false); System.err.println(resource); assertTrue(resource.exists()); /* String uncPath = "\\\\127.0.0.1"+__userURL.toURI().getPath().replace('/','\\').replace(':','$')+"ResourceTest.java"; System.err.println(uncPath); Resource uncResource = Resource.newResource(uncPath, false); System.err.println(uncResource); assertTrue(uncResource.exists()); */ }
protected String getSystemClassPath(ClassLoader loader) throws Exception { StringBuilder classpath = new StringBuilder(); while (loader != null) { if (loader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) loader).getURLs(); if (urls != null) { for (int i = 0; i < urls.length; i++) { Resource resource = Resource.newResource(urls[i]); File file = resource.getFile(); if (file != null && file.exists()) { if (classpath.length() > 0) classpath.append(File.pathSeparatorChar); classpath.append(file.getAbsolutePath()); } } } } else if (loader instanceof AntClassLoader) { classpath.append(((AntClassLoader) loader).getClasspath()); } loader = loader.getParent(); } return classpath.toString(); }
@BeforeClass public static void startServer() throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(0); server.addConnector(connector); ContextHandlerCollection contexts = new ContextHandlerCollection(); File dir = MavenTestingUtils.getTargetTestingDir(ResourceHandlerRangeTest.class.getSimpleName()); FS.ensureEmpty(dir); File rangeFile = new File(dir, "range.txt"); try (FileWriter writer = new FileWriter(rangeFile)) { writer.append("0123456789"); writer.flush(); } ContextHandler contextHandler = new ContextHandler(); ResourceHandler contentResourceHandler = new ResourceHandler(); contextHandler.setBaseResource(Resource.newResource(dir.getAbsolutePath())); contextHandler.setHandler(contentResourceHandler); contextHandler.setContextPath("/"); contexts.addHandler(contextHandler); server.setHandler(contexts); server.start(); String host = connector.getHost(); if (host == null) { host = "localhost"; } int port = connector.getLocalPort(); serverUri = new URI(String.format("http://%s:%d/", host, port)); }