Search in sources :

Example 61 with Writer

use of java.io.Writer in project tomcat by apache.

the class TestDefaultServlet method testCustomErrorPageMissing.

/*
     * Test what happens if a custom 404 page is configured,
     * but its file is actually missing.
     */
@Test
public void testCustomErrorPageMissing() throws Exception {
    File appDir = new File(getTemporaryDirectory(), "MyApp");
    File webInf = new File(appDir, "WEB-INF");
    addDeleteOnTearDown(appDir);
    if (!webInf.mkdirs() && !webInf.isDirectory()) {
        fail("Unable to create directory [" + webInf + "]");
    }
    File webxml = new File(appDir, "WEB-INF/web.xml");
    try (FileOutputStream fos = new FileOutputStream(webxml);
        Writer w = new OutputStreamWriter(fos, "UTF-8")) {
        w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' " + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee " + " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'" + " version='2.4'>\n" + "<error-page>\n<error-code>404</error-code>\n" + "<location>/404-absent.html</location>\n</error-page>\n" + "</web-app>\n");
    }
    Tomcat tomcat = getTomcatInstance();
    String contextPath = "/MyApp";
    tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath());
    tomcat.start();
    TestCustomErrorClient client = new TestCustomErrorClient(tomcat.getConnector().getLocalPort());
    client.reset();
    client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.0" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());
}
Also used : Tomcat(org.apache.catalina.startup.Tomcat) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 62 with Writer

use of java.io.Writer in project tomcat by apache.

the class TestWsRemoteEndpoint method doTestWriter.

private void doTestWriter(Class<?> clazz, boolean useWriter, String testMessage) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");
    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    tomcat.start();
    Session wsSession;
    URI uri = new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC);
    if (Endpoint.class.isAssignableFrom(clazz)) {
        @SuppressWarnings("unchecked") Class<? extends Endpoint> endpointClazz = (Class<? extends Endpoint>) clazz;
        wsSession = wsContainer.connectToServer(endpointClazz, Builder.create().build(), uri);
    } else {
        wsSession = wsContainer.connectToServer(clazz, uri);
    }
    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties().get("endpoint");
    tep.setLatch(latch);
    AsyncHandler<?> handler;
    if (useWriter) {
        handler = new AsyncText(latch);
    } else {
        handler = new AsyncBinary(latch);
    }
    wsSession.addMessageHandler(handler);
    if (useWriter) {
        Writer w = wsSession.getBasicRemote().getSendWriter();
        for (int i = 0; i < 8; i++) {
            w.write(testMessage);
        }
        w.close();
    } else {
        OutputStream s = wsSession.getBasicRemote().getSendStream();
        for (int i = 0; i < 8; i++) {
            s.write(testMessage.getBytes(StandardCharsets.UTF_8));
        }
        s.close();
    }
    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    List<String> results = new ArrayList<>();
    if (useWriter) {
        @SuppressWarnings("unchecked") List<String> messages = (List<String>) handler.getMessages();
        results.addAll(messages);
    } else {
        // Take advantage of the fact that the message uses characters that
        // are represented as a single UTF-8 byte so won't be split across
        // binary messages
        @SuppressWarnings("unchecked") List<ByteBuffer> messages = (List<ByteBuffer>) handler.getMessages();
        for (ByteBuffer message : messages) {
            byte[] bytes = new byte[message.limit()];
            message.get(bytes);
            results.add(new String(bytes, StandardCharsets.UTF_8));
        }
    }
    int offset = 0;
    int i = 0;
    for (String result : results) {
        if (testMessage.length() == 0) {
            Assert.assertEquals(0, result.length());
        } else {
            // First may be a fragment
            Assert.assertEquals(SEQUENCE.substring(offset, S_LEN), result.substring(0, S_LEN - offset));
            i = S_LEN - offset;
            while (i + S_LEN < result.length()) {
                if (!SEQUENCE.equals(result.substring(i, i + S_LEN))) {
                    Assert.fail();
                }
                i += S_LEN;
            }
            offset = result.length() - i;
            if (!SEQUENCE.substring(0, offset).equals(result.substring(i))) {
                Assert.fail();
            }
        }
    }
}
Also used : AsyncText(org.apache.tomcat.websocket.TesterMessageCountClient.AsyncText) Tomcat(org.apache.catalina.startup.Tomcat) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) URI(java.net.URI) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) TesterAnnotatedEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterAnnotatedEndpoint) Endpoint(javax.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) ArrayList(java.util.ArrayList) List(java.util.List) DefaultServlet(org.apache.catalina.servlets.DefaultServlet) Context(org.apache.catalina.Context) WebSocketContainer(javax.websocket.WebSocketContainer) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) TesterProgrammaticEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint) TesterAnnotatedEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterAnnotatedEndpoint) Endpoint(javax.websocket.Endpoint) TesterEndpoint(org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint) AsyncBinary(org.apache.tomcat.websocket.TesterMessageCountClient.AsyncBinary) Writer(java.io.Writer) Session(javax.websocket.Session)

Example 63 with Writer

use of java.io.Writer in project zookeeper by apache.

the class AtomicFileWritingIdiomTest method testWriterSuccessNE.

@Test
public void testWriterSuccessNE() throws IOException {
    File target = new File(tmpdir, "target.txt");
    final File tmp = new File(tmpdir, "target.txt.tmp");
    target.delete();
    assertFalse("file should not exist", target.exists());
    new AtomicFileWritingIdiom(target, new WriterStatement() {

        @Override
        public void write(Writer os) throws IOException {
            os.write("after");
            assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
        }
    });
    assertFalse("tmp file should have been deleted", tmp.exists());
    // content changed
    assertEquals("after", getContent(target));
    target.delete();
}
Also used : WriterStatement(org.apache.zookeeper.common.AtomicFileWritingIdiom.WriterStatement) IOException(java.io.IOException) File(java.io.File) Writer(java.io.Writer) Test(org.junit.Test)

Example 64 with Writer

use of java.io.Writer in project zookeeper by apache.

the class AtomicFileWritingIdiomTest method testWriterFailure.

@Test
public void testWriterFailure() throws IOException {
    File target = new File(tmpdir, "target.txt");
    final File tmp = new File(tmpdir, "target.txt.tmp");
    createFile(target, "before");
    assertEquals("before", getContent(target));
    boolean exception = false;
    try {
        new AtomicFileWritingIdiom(target, new WriterStatement() {

            @Override
            public void write(Writer os) throws IOException {
                os.write("after");
                os.flush();
                assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
                throw new RuntimeException();
            }
        });
    } catch (RuntimeException ex) {
        exception = true;
    }
    assertFalse("tmp file should have been deleted", tmp.exists());
    assertTrue("should have raised an exception", exception);
    // content preserved
    assertEquals("before", getContent(target));
    target.delete();
}
Also used : WriterStatement(org.apache.zookeeper.common.AtomicFileWritingIdiom.WriterStatement) IOException(java.io.IOException) File(java.io.File) Writer(java.io.Writer) Test(org.junit.Test)

Example 65 with Writer

use of java.io.Writer in project crate by crate.

the class NodeSettingsTest method createConfigPath.

private String createConfigPath() throws IOException {
    File home = tmp.newFolder("crate");
    File config = tmp.newFolder("crate", "config");
    Settings pathSettings = Settings.builder().put("path.work", tmp.newFolder("crate", "work").getPath()).put("path.data", tmp.newFolder("crate", "data").getPath()).put("path.logs", tmp.newFolder("crate", "logs").getPath()).build();
    try (Writer writer = new FileWriter(Paths.get(config.getPath(), "crate.yml").toFile())) {
        Yaml yaml = new Yaml();
        yaml.dump(pathSettings.getAsMap(), writer);
    }
    return home.getPath();
}
Also used : FileWriter(java.io.FileWriter) File(java.io.File) Settings(org.elasticsearch.common.settings.Settings) FileWriter(java.io.FileWriter) Writer(java.io.Writer) Yaml(org.yaml.snakeyaml.Yaml)

Aggregations

Writer (java.io.Writer)1259 OutputStreamWriter (java.io.OutputStreamWriter)512 IOException (java.io.IOException)414 StringWriter (java.io.StringWriter)300 File (java.io.File)269 FileOutputStream (java.io.FileOutputStream)196 BufferedWriter (java.io.BufferedWriter)178 FileWriter (java.io.FileWriter)174 PrintWriter (java.io.PrintWriter)159 OutputStream (java.io.OutputStream)120 Test (org.junit.Test)109 InputStreamReader (java.io.InputStreamReader)71 ByteArrayOutputStream (java.io.ByteArrayOutputStream)64 BufferedReader (java.io.BufferedReader)62 Reader (java.io.Reader)62 HashMap (java.util.HashMap)59 Map (java.util.Map)59 ArrayList (java.util.ArrayList)58 InputStream (java.io.InputStream)54 Properties (java.util.Properties)39