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(); }
private String loadExpectedSha1Sum(String testResourceSha1Sum) throws IOException { File sha1File = MavenTestingUtils.getTestResourceFile(testResourceSha1Sum); String contents = IO.readToString(sha1File); Pattern pat = Pattern.compile("^[0-9A-Fa-f]*"); Matcher mat = pat.matcher(contents); Assert.assertTrue("Should have found HEX code in SHA1 file: " + sha1File, mat.find()); return mat.group(); }
@Test public void testLoadAllModules() throws IOException { File homeDir = MavenTestingUtils.getTestResourceDir("usecases/home"); BaseHome basehome = new BaseHome(homeDir, homeDir); Modules modules = new Modules(); modules.registerAll(basehome); Assert.assertThat("Module count", modules.count(), is(28)); }
@BeforeClass public static void initSslEngine() throws Exception { File keystore = MavenTestingUtils.getTestResourceFile("keystore"); __sslCtxFactory.setKeyStorePath(keystore.getAbsolutePath()); __sslCtxFactory.setKeyStorePassword("storepwd"); __sslCtxFactory.setKeyManagerPassword("keypwd"); __sslCtxFactory.setEndpointIdentificationAlgorithm(""); __sslCtxFactory.start(); }
@Test public void testResolve_ServerHttp() throws IOException { File homeDir = MavenTestingUtils.getTestResourceDir("usecases/home"); BaseHome basehome = new BaseHome(homeDir, homeDir); // Register modules Modules modules = new Modules(); modules.registerAll(basehome); modules.buildGraph(); // Enable 2 modules modules.enable("server", TEST_SOURCE); modules.enable("http", TEST_SOURCE); // Collect active module list List<Module> active = modules.resolveEnabled(); // Assert names are correct, and in the right order List<String> expectedNames = new ArrayList<>(); expectedNames.add("base"); expectedNames.add("xml"); expectedNames.add("server"); expectedNames.add("http"); List<String> actualNames = new ArrayList<>(); for (Module actual : active) { actualNames.add(actual.getName()); } Assert.assertThat( "Resolved Names: " + actualNames, actualNames, contains(expectedNames.toArray())); // Assert Library List List<String> expectedLibs = new ArrayList<>(); expectedLibs.add("lib/jetty-util-${jetty.version}.jar"); expectedLibs.add("lib/jetty-io-${jetty.version}.jar"); expectedLibs.add("lib/jetty-xml-${jetty.version}.jar"); expectedLibs.add("lib/servlet-api-3.1.jar"); expectedLibs.add("lib/jetty-schemas-3.1.jar"); expectedLibs.add("lib/jetty-http-${jetty.version}.jar"); expectedLibs.add("lib/jetty-continuation-${jetty.version}.jar"); expectedLibs.add("lib/jetty-server-${jetty.version}.jar"); List<String> actualLibs = modules.normalizeLibs(active); Assert.assertThat("Resolved Libs: " + actualLibs, actualLibs, contains(expectedLibs.toArray())); // Assert XML List List<String> expectedXmls = new ArrayList<>(); expectedXmls.add("etc/jetty.xml"); expectedXmls.add("etc/jetty-http.xml"); List<String> actualXmls = modules.normalizeXmls(active); Assert.assertThat("Resolved XMLs: " + actualXmls, actualXmls, contains(expectedXmls.toArray())); }
@Slow @Test public void testProxyWithBigResponseContentWithSlowReader() throws Exception { prepareProxy(); // Create a 6 MiB file final int length = 6 * 1024; Path targetTestsDir = MavenTestingUtils.getTargetTestingDir().toPath(); Files.createDirectories(targetTestsDir); final Path temp = Files.createTempFile(targetTestsDir, "test_", null); byte[] kb = new byte[1024]; new Random().nextBytes(kb); try (OutputStream output = Files.newOutputStream(temp, StandardOpenOption.CREATE)) { for (int i = 0; i < length; ++i) output.write(kb); } prepareServer( new HttpServlet() { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try (InputStream input = Files.newInputStream(temp)) { IO.copy(input, response.getOutputStream()); } } }); Request request = client.newRequest("localhost", serverConnector.getLocalPort()).path("/proxy/test"); final CountDownLatch latch = new CountDownLatch(1); request.send( new BufferingResponseListener(2 * length * 1024) { @Override public void onContent(Response response, ByteBuffer content) { try { // Slow down the reader TimeUnit.MILLISECONDS.sleep(5); super.onContent(response, content); } catch (InterruptedException x) { response.abort(x); } } @Override public void onComplete(Result result) { Assert.assertFalse(result.isFailed()); Assert.assertEquals(200, result.getResponse().getStatus()); Assert.assertEquals(length * 1024, getContent().length); latch.countDown(); } }); Assert.assertTrue(latch.await(30, TimeUnit.SECONDS)); }
/* ------------------------------------------------------------ */ @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()); }
private void deleteFile(File file) throws IOException { if (OS.IS_WINDOWS) { // Windows doesn't seem to like to delete content that was recently created // Attempt a delete and if it fails, attempt a rename boolean deleted = file.delete(); if (!deleted) { File deletedDir = MavenTestingUtils.getTargetFile(".deleted"); FS.ensureDirExists(deletedDir); File dest = File.createTempFile(file.getName(), "deleted", deletedDir); boolean renamed = file.renameTo(dest); if (!renamed) System.err.println("WARNING: unable to move file out of the way: " + file.getName()); } } else { Assert.assertTrue("Deleting: " + file.getName(), file.delete()); } }
private void start(Authenticator authenticator, Handler handler) throws Exception { server = new Server(); File realmFile = MavenTestingUtils.getTestResourceFile("realm.properties"); LoginService loginService = new HashLoginService(realm, realmFile.getAbsolutePath()); server.addBean(loginService); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); Constraint constraint = new Constraint(); constraint.setAuthenticate(true); constraint.setRoles(new String[] {"*"}); ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/secure"); mapping.setConstraint(constraint); securityHandler.addConstraintMapping(mapping); securityHandler.setAuthenticator(authenticator); securityHandler.setLoginService(loginService); securityHandler.setStrict(false); securityHandler.setHandler(handler); start(securityHandler); }
@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)); }
/** * Copy a src/test/resource file into the server tree for eventual serving. * * @param filename the filename to look for in src/test/resources */ public void copyTestServerFile(String filename) throws IOException { File srcFile = MavenTestingUtils.getTestResourceFile(filename); File testFile = testdir.getFile(filename); IO.copy(srcFile, testFile); }
/** @throws java.lang.Exception */ @Before public void setUp() throws Exception { File testJettyHome = MavenTestingUtils.getTestResourceDir("jetty.home"); System.setProperty("jetty.home", testJettyHome.getAbsolutePath()); }
public void start() throws Exception { // Configure Server server = new Server(); if (ssl) { // HTTP Configuration HttpConfiguration http_config = new HttpConfiguration(); http_config.setSecureScheme("https"); http_config.setSecurePort(0); http_config.setOutputBufferSize(32768); http_config.setRequestHeaderSize(8192); http_config.setResponseHeaderSize(8192); http_config.setSendServerVersion(true); http_config.setSendDateHeader(false); sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath( MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath()); sslContextFactory.setKeyStorePassword("storepwd"); sslContextFactory.setKeyManagerPassword("keypwd"); sslContextFactory.setExcludeCipherSuites( "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); // SSL HTTP Configuration HttpConfiguration https_config = new HttpConfiguration(http_config); https_config.addCustomizer(new SecureRequestCustomizer()); // SSL Connector connector = new ServerConnector( server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); connector.setPort(0); } else { // Basic HTTP connector connector = new ServerConnector(server); connector.setPort(0); } server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); // Serve capture servlet context.addServlet(new ServletHolder(servlet), "/*"); // Start Server server.start(); // Establish the Server URI String host = connector.getHost(); if (host == null) { host = "localhost"; } int port = connector.getLocalPort(); serverUri = new URI(String.format("%s://%s:%d/", ssl ? "wss" : "ws", host, port)); // Some debugging if (LOG.isDebugEnabled()) { LOG.debug(server.dump()); } }