Search in sources :

Example 1 with FileOutputStream

use of java.io.FileOutputStream in project jetty.project by eclipse.

the class ResourceCacheTest method testResourceCache.

@Test
public void testResourceCache() throws Exception {
    final Resource directory;
    File[] files = new File[10];
    String[] names = new String[files.length];
    CachedContentFactory cache;
    for (int i = 0; i < files.length; i++) {
        files[i] = File.createTempFile("R-" + i + "-", ".txt");
        files[i].deleteOnExit();
        names[i] = files[i].getName();
        try (OutputStream out = new FileOutputStream(files[i])) {
            for (int j = 0; j < (i * 10 - 1); j++) out.write(' ');
            out.write('\n');
        }
    }
    directory = Resource.newResource(files[0].getParentFile().getAbsolutePath());
    cache = new CachedContentFactory(null, directory, new MimeTypes(), false, false, CompressedContentFormat.NONE);
    cache.setMaxCacheSize(95);
    cache.setMaxCachedFileSize(85);
    cache.setMaxCachedFiles(4);
    assertTrue(cache.getContent("does not exist", 4096) == null);
    assertTrue(cache.getContent(names[9], 4096) instanceof ResourceHttpContent);
    assertTrue(cache.getContent(names[9], 4096).getIndirectBuffer() != null);
    HttpContent content;
    content = cache.getContent(names[8], 4096);
    assertTrue(content != null);
    assertEquals(80, content.getContentLengthValue());
    assertEquals(0, cache.getCachedSize());
    if (OS.IS_LINUX) {
        // Initially not using memory mapped files
        content.getDirectBuffer();
        assertEquals(80, cache.getCachedSize());
        // with both types of buffer loaded, this is too large for cache
        content.getIndirectBuffer();
        assertEquals(0, cache.getCachedSize());
        assertEquals(0, cache.getCachedFiles());
        cache = new CachedContentFactory(null, directory, new MimeTypes(), true, false, CompressedContentFormat.NONE);
        cache.setMaxCacheSize(95);
        cache.setMaxCachedFileSize(85);
        cache.setMaxCachedFiles(4);
        content = cache.getContent(names[8], 4096);
        content.getDirectBuffer();
        assertEquals(cache.isUseFileMappedBuffer() ? 0 : 80, cache.getCachedSize());
    // with both types of buffer loaded, this is not too large for cache because
    // mapped buffers don't count, so we can continue
    }
    content.getIndirectBuffer();
    assertEquals(80, cache.getCachedSize());
    assertEquals(1, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[1], 4096);
    assertEquals(80, cache.getCachedSize());
    content.getIndirectBuffer();
    assertEquals(90, cache.getCachedSize());
    assertEquals(2, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[2], 4096);
    content.getIndirectBuffer();
    assertEquals(30, cache.getCachedSize());
    assertEquals(2, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[3], 4096);
    content.getIndirectBuffer();
    assertEquals(60, cache.getCachedSize());
    assertEquals(3, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[4], 4096);
    content.getIndirectBuffer();
    assertEquals(90, cache.getCachedSize());
    assertEquals(3, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[5], 4096);
    content.getIndirectBuffer();
    assertEquals(90, cache.getCachedSize());
    assertEquals(2, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[6], 4096);
    content.getIndirectBuffer();
    assertEquals(60, cache.getCachedSize());
    assertEquals(1, cache.getCachedFiles());
    Thread.sleep(200);
    try (OutputStream out = new FileOutputStream(files[6])) {
        out.write(' ');
    }
    content = cache.getContent(names[7], 4096);
    content.getIndirectBuffer();
    assertEquals(70, cache.getCachedSize());
    assertEquals(1, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[6], 4096);
    content.getIndirectBuffer();
    assertEquals(71, cache.getCachedSize());
    assertEquals(2, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[0], 4096);
    content.getIndirectBuffer();
    assertEquals(72, cache.getCachedSize());
    assertEquals(3, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[1], 4096);
    content.getIndirectBuffer();
    assertEquals(82, cache.getCachedSize());
    assertEquals(4, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[2], 4096);
    content.getIndirectBuffer();
    assertEquals(32, cache.getCachedSize());
    assertEquals(4, cache.getCachedFiles());
    Thread.sleep(200);
    content = cache.getContent(names[3], 4096);
    content.getIndirectBuffer();
    assertEquals(61, cache.getCachedSize());
    assertEquals(4, cache.getCachedFiles());
    Thread.sleep(200);
    cache.flushCache();
    assertEquals(0, cache.getCachedSize());
    assertEquals(0, cache.getCachedFiles());
    cache.flushCache();
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) Resource(org.eclipse.jetty.util.resource.Resource) ResourceHttpContent(org.eclipse.jetty.http.ResourceHttpContent) MimeTypes(org.eclipse.jetty.http.MimeTypes) File(java.io.File) HttpContent(org.eclipse.jetty.http.HttpContent) ResourceHttpContent(org.eclipse.jetty.http.ResourceHttpContent) Test(org.junit.Test)

Example 2 with FileOutputStream

use of java.io.FileOutputStream in project jetty.project by eclipse.

the class AbstractProxySerializationTest method testProxySerialization.

@Test
public void testProxySerialization() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int scavengePeriod = 10;
    DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
    cacheFactory.setEvictionPolicy(SessionCache.NEVER_EVICT);
    SessionDataStoreFactory storeFactory = createSessionDataStoreFactory();
    ((AbstractSessionDataStoreFactory) storeFactory).setGracePeriodSec(scavengePeriod);
    TestServer server = new TestServer(0, 20, scavengePeriod, cacheFactory, storeFactory);
    ServletContextHandler context = server.addContext(contextPath);
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("proxy-serialization.jar");
    File testDir = MavenTestingUtils.getTargetTestingDir("proxy-serialization");
    testDir.mkdirs();
    File extractedJar = new File(testDir, "proxy-serialization.jar");
    extractedJar.createNewFile();
    IO.copy(is, new FileOutputStream(extractedJar));
    URLClassLoader loader = new URLClassLoader(new URL[] { extractedJar.toURI().toURL() }, Thread.currentThread().getContextClassLoader());
    context.setClassLoader(loader);
    context.addServlet("TestServlet", servletMapping);
    customizeContext(context);
    try {
        server.start();
        int port = server.getPort();
        HttpClient client = new HttpClient();
        client.start();
        try {
            ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            String sessionCookie = response.getHeaders().get("Set-Cookie");
            assertTrue(sessionCookie != null);
            // Mangle the cookie, replacing Path with $Path, etc.
            sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
            //stop the context to be sure the sesssion will be passivated
            context.stop();
            //restart the context
            context.start();
            // Make another request using the session id from before
            Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=test");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        } finally {
            client.stop();
        }
    } finally {
        server.stop();
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) InputStream(java.io.InputStream) Request(org.eclipse.jetty.client.api.Request) FileOutputStream(java.io.FileOutputStream) URLClassLoader(java.net.URLClassLoader) HttpClient(org.eclipse.jetty.client.HttpClient) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File) Test(org.junit.Test)

Example 3 with FileOutputStream

use of java.io.FileOutputStream in project jetty.project by eclipse.

the class AbstractWebAppObjectInSessionTest method testWebappObjectInSession.

@Test
public void testWebappObjectInSession() throws Exception {
    String contextName = "webappObjectInSessionTest";
    String contextPath = "/" + contextName;
    String servletMapping = "/server";
    File targetDir = new File(System.getProperty("basedir"), "target");
    File warDir = new File(targetDir, contextName);
    warDir.mkdir();
    File webInfDir = new File(warDir, "WEB-INF");
    webInfDir.mkdir();
    // Write web.xml
    File webXml = new File(webInfDir, "web.xml");
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<web-app xmlns=\"http://java.sun.com/xml/ns/j2ee\"\n" + "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "         xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\"\n" + "         version=\"2.4\">\n" + "\n" + "</web-app>";
    FileWriter w = new FileWriter(webXml);
    w.write(xml);
    w.close();
    File classesDir = new File(webInfDir, "classes");
    classesDir.mkdir();
    String packageName = WebAppObjectInSessionServlet.class.getPackage().getName();
    File packageDirs = new File(classesDir, packageName.replace('.', File.separatorChar));
    packageDirs.mkdirs();
    String resourceName = WebAppObjectInSessionServlet.class.getSimpleName() + ".class";
    Resource resource = Resource.newResource(getClass().getResource(resourceName));
    //File sourceFile = new File(getClass().getClassLoader().getResource(resourceName).toURI());
    File targetFile = new File(packageDirs, resourceName);
    //copy(sourceFile, targetFile);
    IO.copy(resource.getInputStream(), new FileOutputStream(targetFile));
    resourceName = WebAppObjectInSessionServlet.class.getSimpleName() + "$" + WebAppObjectInSessionServlet.TestSharedStatic.class.getSimpleName() + ".class";
    resource = Resource.newResource(getClass().getResource(resourceName));
    //sourceFile = new File(getClass().getClassLoader().getResource(resourceName).toURI());
    targetFile = new File(packageDirs, resourceName);
    //copy(sourceFile, targetFile);
    IO.copy(resource.getInputStream(), new FileOutputStream(targetFile));
    DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
    cacheFactory.setEvictionPolicy(SessionCache.NEVER_EVICT);
    SessionDataStoreFactory storeFactory = createSessionDataStoreFactory();
    ((AbstractSessionDataStoreFactory) storeFactory).setGracePeriodSec(TestServer.DEFAULT_SCAVENGE_SEC);
    TestServer server1 = new TestServer(0, TestServer.DEFAULT_MAX_INACTIVE, TestServer.DEFAULT_SCAVENGE_SEC, cacheFactory, storeFactory);
    server1.addWebAppContext(warDir.getCanonicalPath(), contextPath).addServlet(WebAppObjectInSessionServlet.class.getName(), servletMapping);
    try {
        server1.start();
        int port1 = server1.getPort();
        TestServer server2 = new TestServer(0, TestServer.DEFAULT_MAX_INACTIVE, TestServer.DEFAULT_SCAVENGE_SEC, cacheFactory, storeFactory);
        server2.addWebAppContext(warDir.getCanonicalPath(), contextPath).addServlet(WebAppObjectInSessionServlet.class.getName(), servletMapping);
        try {
            server2.start();
            int port2 = server2.getPort();
            HttpClient client = new HttpClient();
            client.start();
            try {
                // Perform one request to server1 to create a session
                Request request = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping + "?action=set");
                request.method(HttpMethod.GET);
                ContentResponse response = request.send();
                assertEquals(HttpServletResponse.SC_OK, response.getStatus());
                String sessionCookie = response.getHeaders().get("Set-Cookie");
                assertTrue(sessionCookie != null);
                // Mangle the cookie, replacing Path with $Path, etc.
                sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
                // Perform a request to server2 using the session cookie from the previous request
                Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
                request2.method(HttpMethod.GET);
                request2.header("Cookie", sessionCookie);
                ContentResponse response2 = request2.send();
                assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
            } finally {
                client.stop();
            }
        } finally {
            server2.stop();
        }
    } finally {
        server1.stop();
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) FileWriter(java.io.FileWriter) Resource(org.eclipse.jetty.util.resource.Resource) Request(org.eclipse.jetty.client.api.Request) FileOutputStream(java.io.FileOutputStream) HttpClient(org.eclipse.jetty.client.HttpClient) File(java.io.File) Test(org.junit.Test)

Example 4 with FileOutputStream

use of java.io.FileOutputStream in project jetty.project by eclipse.

the class DataSourceLoginServiceTest method setUp.

@BeforeClass
public static void setUp() throws Exception {
    _docRoot = MavenTestingUtils.getTargetTestingDir("loginservice-test");
    FS.ensureDirExists(_docRoot);
    File content = new File(_docRoot, "input.txt");
    FileOutputStream out = new FileOutputStream(content);
    out.write(_content.getBytes("utf-8"));
    out.close();
    //clear previous runs
    File scriptFile = MavenTestingUtils.getTestResourceFile("droptables.sql");
    int result = DatabaseLoginServiceTestServer.runscript(scriptFile);
    //ignore result as derby spits errors for dropping tables that dont exist
    //create afresh
    scriptFile = MavenTestingUtils.getTestResourceFile("createdb.sql");
    result = DatabaseLoginServiceTestServer.runscript(scriptFile);
    assertThat("runScript result", result, is(0));
    _testServer = new DatabaseLoginServiceTestServer();
    _testServer.setResourceBase(_docRoot.getAbsolutePath());
    _testServer.setLoginService(configureLoginService());
    _testServer.start();
    _baseUri = _testServer.getBaseUri();
}
Also used : FileOutputStream(java.io.FileOutputStream) File(java.io.File) BeforeClass(org.junit.BeforeClass)

Example 5 with FileOutputStream

use of java.io.FileOutputStream in project jetty.project by eclipse.

the class JdbcLoginServiceTest method setUp.

@BeforeClass
public static void setUp() throws Exception {
    _docRoot = MavenTestingUtils.getTargetTestingDir("loginservice-test");
    FS.ensureDirExists(_docRoot);
    File content = new File(_docRoot, "input.txt");
    try (FileOutputStream out = new FileOutputStream(content)) {
        out.write(_content.getBytes("utf-8"));
    }
    //drop any tables that might have existed
    File scriptFile = MavenTestingUtils.getTestResourceFile("droptables.sql");
    int result = DatabaseLoginServiceTestServer.runscript(scriptFile);
    //ignore result, if the tables dont already exist, derby spits out an error
    //create the tables afresh
    scriptFile = MavenTestingUtils.getTestResourceFile("createdb.sql");
    result = DatabaseLoginServiceTestServer.runscript(scriptFile);
    assertThat("runScript result", result, is(0));
    File jdbcRealmFile = MavenTestingUtils.getTestResourceFile("jdbcrealm.properties");
    LoginService loginService = new JDBCLoginService(__realm, jdbcRealmFile.getAbsolutePath());
    _testServer = new DatabaseLoginServiceTestServer();
    _testServer.setResourceBase(_docRoot.getAbsolutePath());
    _testServer.setLoginService(loginService);
    _testServer.start();
    _baseUri = _testServer.getBaseUri();
}
Also used : FileOutputStream(java.io.FileOutputStream) JDBCLoginService(org.eclipse.jetty.security.JDBCLoginService) File(java.io.File) JDBCLoginService(org.eclipse.jetty.security.JDBCLoginService) LoginService(org.eclipse.jetty.security.LoginService) BeforeClass(org.junit.BeforeClass)

Aggregations

FileOutputStream (java.io.FileOutputStream)13621 File (java.io.File)8194 IOException (java.io.IOException)6088 FileInputStream (java.io.FileInputStream)2601 OutputStream (java.io.OutputStream)2572 InputStream (java.io.InputStream)2044 BufferedOutputStream (java.io.BufferedOutputStream)1737 FileNotFoundException (java.io.FileNotFoundException)1506 OutputStreamWriter (java.io.OutputStreamWriter)1420 Test (org.junit.Test)1096 ZipEntry (java.util.zip.ZipEntry)718 BufferedWriter (java.io.BufferedWriter)661 ArrayList (java.util.ArrayList)635 ZipOutputStream (java.util.zip.ZipOutputStream)629 BufferedInputStream (java.io.BufferedInputStream)599 ByteArrayOutputStream (java.io.ByteArrayOutputStream)545 PrintWriter (java.io.PrintWriter)526 Properties (java.util.Properties)498 HashMap (java.util.HashMap)481 DataOutputStream (java.io.DataOutputStream)472