FilesystemResourcesObject extends HttpObject { @Override public Response get(Request req) { final String resource = req.path().valueFor("resource"); if(isNullOrEmpty(resource) || resource.endsWith("/")) return null; File path = new File(relativeTo, resource); if(!isBelow(path, relativeTo)){ return null; } if(path.exists() && path.isFile()){ return OK(Bytes(mimeTypeFor(resource), openStream(path))); }else{ return null; } } FilesystemResourcesObject(String pathPattern, File relativeTo); @Override Response get(Request req);  }
@Test public void retrievesFiles() { DirSpec fs = dir("my-filesystem", dir("misc-files", file("stuff.txt", "some stuff") )); File temp = fs.create(tempDir()); FilesystemResourcesObject testSubject = new FilesystemResourcesObject("/{resource*}", temp); MockRequest req = new MockRequest(testSubject, "/misc-files/stuff.txt"); Response result = testSubject.get(req); Assert.assertNotNull(result); Assert.assertEquals("some stuff", toString(result.representation())); }
@Test public void doesntServeFilesOutsideOfTheBaseDir() { DirSpec fs = dir("my-filesystem" , dir("public-data"), file("hidden.txt", "top secret data") ); File temp = fs.create(tempDir()); File pathToPublicData = new File(temp, "public-data"); FilesystemResourcesObject testSubject = new FilesystemResourcesObject("/{resource*}", pathToPublicData); MockRequest req = new MockRequest(testSubject, "/../hidden.txt"); Response result = testSubject.get(req); Assert.assertNull(result); }