Example usage for java.io Writer Writer

List of usage examples for java.io Writer Writer

Introduction

In this page you can find the example usage for java.io Writer Writer.

Prototype

protected Writer() 

Source Link

Document

Creates a new character-stream writer whose critical sections will synchronize on the writer itself.

Usage

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Handles the callback from the client; expects either an object or an array of objects
 * @param request/*ww  w. jav a2  s  . c  om*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void processRequest(Reader request, Writer response) throws ServletException, IOException {
    s_currentHandler.set(this);
    ObjectMapper objectMapper = tracker.getObjectMapper();
    try {
        if (log.isDebugEnabled()) {
            StringWriter sw = new StringWriter();
            char[] buffer = new char[32 * 1024];
            int length;
            while ((length = request.read(buffer)) > 0) {
                sw.write(buffer, 0, length);
            }
            log.debug("Received: " + sw.toString());
            request = new StringReader(sw.toString());
        }
        JsonParser jp = objectMapper.getJsonFactory().createJsonParser(request);
        if (jp.nextToken() == JsonToken.START_ARRAY) {
            while (jp.nextToken() != JsonToken.END_ARRAY)
                processCommand(jp);
        } else if (jp.getCurrentToken() == JsonToken.START_OBJECT)
            processCommand(jp);

        if (tracker.hasDataToFlush()) {
            Writer actualResponse = response;
            if (log.isDebugEnabled()) {
                final Writer tmp = response;
                actualResponse = new Writer() {
                    @Override
                    public void close() throws IOException {
                        tmp.close();
                    }

                    @Override
                    public void flush() throws IOException {
                        tmp.flush();
                    }

                    @Override
                    public void write(char[] arg0, int arg1, int arg2) throws IOException {
                        System.out.print(new String(arg0, arg1, arg2));
                        tmp.write(arg0, arg1, arg2);
                    }
                };
            }
            objectMapper.writeValue(actualResponse, tracker.getQueue());
        }

    } catch (ProxyTypeSerialisationException e) {
        log.fatal("Unable to serialise type information to client: " + e.getMessage(), e);

    } catch (ProxyException e) {
        handleException(response, objectMapper, e);

    } catch (Exception e) {
        log.error("Exception during callback: " + e.getMessage(), e);
        tracker.getQueue().queueCommand(CommandType.EXCEPTION, null, null,
                new ExceptionDetails(e.getClass().getName(), e.getMessage()));
        objectMapper.writeValue(response, tracker.getQueue());

    } finally {
        s_currentHandler.set(null);
    }
}

From source file:org.esigate.servlet.impl.ResponseCapturingWrapper.java

@Override
public PrintWriter getWriter() {
    LOG.debug("getWriter");
    if (outputStream != null) {
        throw new IllegalStateException("OutputStream already obtained");
    }/*  ww  w  . j  av  a  2s. c om*/
    if (writer == null) {
        internalWriter = new StringBuilderWriter(Parameters.DEFAULT_BUFFER_SIZE);
        writer = new PrintWriter(new Writer() {

            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                if (capture || bytesWritten < bufferSize) {
                    internalWriter.write(cbuf, off, len);
                } else {
                    responseWriter.write(cbuf, off, len);
                }
                bytesWritten++;
                if (bytesWritten == bufferSize) {
                    commit();
                }
            }

            @Override
            public void flush() throws IOException {
                commit();
            }

            @Override
            public void close() throws IOException {
                commit();
            }

            private void commit() throws IOException {
                if (!committed) {
                    capture = hasToCaptureOutput();
                    if (!capture) {
                        responseSender.sendHeaders(httpClientResponse, incomingRequest, response);
                        responseWriter = response.getWriter();
                        responseWriter.write(internalWriter.toString());
                    }
                    committed = true;
                }

            }

        });
    }
    return writer;
}

From source file:com.adaptris.core.MarshallingBaseCase.java

public void testMarshalToWriter_WithException() throws Exception {
    AdaptrisMarshaller marshaller = createMarshaller();
    Adapter adapter = createMarshallingObject();
    Writer fail = new Writer() {

        @Override/* w w w.  ja v  a2s  .  c  o  m*/
        public void write(char[] cbuf, int off, int len) throws IOException {
            throw new IOException("testMarshalToWriter_WithException");
        }

        @Override
        public void flush() throws IOException {
            throw new IOException("testMarshalToWriter_WithException");
        }

        @Override
        public void close() throws IOException {
        }
    };
    try (Writer out = fail) {
        marshaller.marshal(adapter, out);
        fail();
    } catch (CoreException e) {
        assertNotNull(e.getCause());
        // assertEquals(IOException.class, e.getCause().getClass());
        assertRootCause("testMarshalToWriter_WithException", e);
    }
}

From source file:Base64.java

/** Returns a {@link Writer}, that decodes its Base64 encoded
 * input and writes it to the given {@link OutputStream}.
 * Note, that the writers {@link Writer#close()} method will
 * <em>not</em> close the output stream <code>pStream</code>!
 * @param pStream Target output stream.//from www  .  ja  v  a  2  s .  co  m
 * @return An output stream, encoding its input in Base64 and writing
 * the output to the writer <code>pWriter</code>.
 */
public Writer newDecoder(final OutputStream pStream) {
    return new Writer() {
        private final Decoder decoder = new Decoder(1024) {
            protected void writeBuffer(byte[] pBytes, int pOffset, int pLen) throws IOException {
                pStream.write(pBytes, pOffset, pLen);
            }
        };

        public void close() throws IOException {
            flush();
        }

        public void flush() throws IOException {
            decoder.flush();
            pStream.flush();
        }

        public void write(char[] cbuf, int off, int len) throws IOException {
            decoder.write(cbuf, off, len);
        }
    };
}

From source file:sf.net.experimaestro.server.JsonRPCMethods.java

/**
 * Return a stream with the given ID/*from   w  w w.j  a v a  2 s.  c o  m*/
 */
private BufferedWriter getRequestStream(final String id) {
    BufferedWriter bufferedWriter = writers.get(id);
    if (bufferedWriter == null) {
        bufferedWriter = new BufferedWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                ImmutableMap<String, String> map = ImmutableMap.of("stream", id, "value",
                        new String(cbuf, off, len));
                mos.message(map);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
                throw new UnsupportedOperationException();
            }
        });
        writers.put(id, bufferedWriter);
    }
    return bufferedWriter;
}

From source file:org.eclipse.wb.internal.core.editor.errors.report2.CreateReportDialog.java

private void showError(final Throwable e) {
    Status status = new Status(IStatus.ERROR, DesignerPlugin.getDefault().toString(), IStatus.ERROR,
            Messages.CreateReportDialog_errorUseDetails, e);
    ErrorDialog dialog = new ErrorDialog(DesignerPlugin.getShell(), Messages.CreateReportDialog_errorTitle,
            Messages.CreateReportDialog_errorMessage, status, IStatus.ERROR) {
        private Clipboard clipboard;

        @Override/*from w  w w. j  a  v a  2 s .  c om*/
        protected List createDropDownList(Composite parent) {
            final List list = super.createDropDownList(parent);
            list.removeAll();
            // populate list using custom PrintWriter
            PrintWriter printWriter = new PrintWriter(new Writer() {
                @Override
                public void write(char[] cbuf, int off, int len) throws IOException {
                    if (len != 2 && !(cbuf[0] == '\r' || cbuf[0] == '\n')) {
                        list.add(StringUtils.replace(new String(cbuf, off, len), "\t", "    "));
                    }
                }

                @Override
                public void flush() throws IOException {
                }

                @Override
                public void close() throws IOException {
                }
            });
            e.printStackTrace(printWriter);
            // install own context menu
            Menu menu = list.getMenu();
            menu.dispose();
            Menu copyMenu = new Menu(list);
            MenuItem copyItem = new MenuItem(copyMenu, SWT.NONE);
            copyItem.setText(Messages.CreateReportDialog_copyAction);
            copyItem.addSelectionListener(new SelectionListener() {
                public void widgetSelected(@SuppressWarnings("hiding") SelectionEvent e) {
                    copyList(list);
                }

                public void widgetDefaultSelected(@SuppressWarnings("hiding") SelectionEvent e) {
                    copyList(list);
                }
            });
            list.setMenu(copyMenu);
            return list;
        }

        private void copyList(List list) {
            if (clipboard != null) {
                clipboard.dispose();
            }
            StringBuffer statusBuffer = new StringBuffer();
            for (int i = 0; i < list.getItemCount(); ++i) {
                statusBuffer.append(list.getItem(i));
                statusBuffer.append("\r\n");
            }
            clipboard = new Clipboard(list.getDisplay());
            clipboard.setContents(new Object[] { statusBuffer.toString() },
                    new Transfer[] { TextTransfer.getInstance() });
        }

        @Override
        public boolean close() {
            if (clipboard != null) {
                clipboard.dispose();
            }
            return super.close();
        }
    };
    dialog.open();
}