Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

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

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:com.boundlessgeo.geoserver.json.JSONWrapper.java

/**
 * Encodes a wrapper as JSON./*from  ww w  . j a va 2s .c  o  m*/
 *
 * @param obj The wrapper.
 * @param out Target writer.
 *
 */
public static void write(Object value, Writer out) throws IOException {
    value = wrapOrSelf(value);
    if (value == null) {
        out.write("null");
        out.flush();
    } else if (value instanceof JSONWrapper) {
        ((JSONWrapper<?>) value).write(out);
    } else {
        JSONValue.writeJSONString(value, out);
    }
}

From source file:heigit.ors.util.FileUtility.java

public static void writeFile(String fileName, String encoding, String content) throws IOException {
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), encoding));
    out.append(content);//w  w  w  .ja  v  a 2 s.c om
    out.flush();
    out.close();
}

From source file:Main.java

/**
 * Copies characters from a reader to a writer. When the reading is done,
 * the reader is closed./*from  w w  w .  j a v a2 s . c o m*/
 * 
 * @param reader
 *            The reader.
 * @param writer
 *            The writer.
 * @throws IOException
 */
public static void copy(Reader reader, java.io.Writer writer) throws IOException {
    int charsRead;
    char[] buffer = new char[2048];

    while ((charsRead = reader.read(buffer)) > 0) {
        writer.write(buffer, 0, charsRead);
    }

    writer.flush();
    reader.close();
}

From source file:com.moss.posixfifosockets.PosixFifoSocket.java

public static PosixFifoSocket newClientConnection(PosixFifoSocketAddress address, int timeoutMillis)
        throws IOException {
    final Log log = LogFactory.getLog(PosixFifoSocket.class);

    if (!address.controlPipe().exists()) {
        throw new IOException("There is no server at " + address);
    }//from  w ww  .ja va2  s  .  co m

    File in;
    File out;
    File control;
    long id;
    do {
        id = r.nextLong();
        in = new File(address.socketsDir(), id + ".fifo.out");
        out = new File(address.socketsDir(), id + ".fifo.in");
        control = new File(address.socketsDir(), id + ".fifo.control");
    } while (out.exists() || in.exists());

    createFifo(in);
    createFifo(control);

    final String registrationString = "{" + id + "}";
    if (log.isDebugEnabled())
        log.debug("Sending registration " + registrationString);
    Writer w = new FileWriter(address.controlPipe());
    w.write(registrationString);
    w.flush();

    if (log.isDebugEnabled())
        log.debug("Sent Registration " + registrationString);

    PosixFifoSocket socket = new PosixFifoSocket(id, in, out);
    Reader r = new FileReader(control);

    StringBuilder text = new StringBuilder();
    for (int c = r.read(); c != -1 && c != '\n'; c = r.read()) {
        // READ UNTIL THE FIRST LINE BREAK
        text.append((char) c);
    }
    r.close();
    if (!control.delete()) {
        throw new RuntimeException("Could not delete file:" + control.getAbsolutePath());
    }
    if (!text.toString().equals("OK")) {
        throw new RuntimeException("Connection error: received \"" + text + "\"");
    }
    return socket;
}

From source file:Main.java

public static void formatXML(Document doc, Document xsl, Writer writer) throws Exception {
    DOMSource xmlSource = new DOMSource(doc);
    DOMSource xslSource = new DOMSource(xsl);
    formatXML(xmlSource, xslSource, writer);
    writer.flush();
}

From source file:com.ms.commons.test.tool.util.AutoImportProjectTaskUtil.java

@SuppressWarnings({ "unchecked", "deprecation" })
public static Task wrapAutoImportTask(final File project, final Task oldTask) {
    InputStream fis = null;//from   w  w  w . j a  v a 2 s . c  om
    try {
        fis = new BufferedInputStream(project.toURL().openStream());
        SAXBuilder b = new SAXBuilder();
        Document document = b.build(fis);

        List<Element> elements = XPath.selectNodes(document, "/project/build/dependencies/include");

        List<String> addList = new ArrayList<String>(importList);
        if (elements != null) {
            for (Element ele : elements) {
                String uri = ele.getAttribute("uri").getValue().trim().toLowerCase();
                if (importList.contains(uri)) {
                    addList.remove(uri);
                }
            }
        }

        if (addList.size() > 0) {
            System.err.println("Add projects:" + addList);

            List<Element> testElements = XPath.selectNodes(document,
                    "/project/build[@profile='TEST']/dependencies");
            Element testEle;
            if ((testElements == null) || (testElements.size() == 0)) {
                Element buildEle = new Element("build");
                buildEle.setAttribute("profile", "TEST");

                Element filesetsEle = new Element("filesets");
                filesetsEle.setAttribute("name", "java.resdirs");
                Element excludeEle = new Element("exclude");
                excludeEle.setAttribute("fileset", "java.configdir");
                filesetsEle.addContent(excludeEle);

                testEle = new Element("dependencies");

                buildEle.addContent(Arrays.asList(filesetsEle, testEle));

                ((Element) XPath.selectNodes(document, "/project").get(0)).addContent(buildEle);
            } else {
                testEle = testElements.get(0);
            }

            for (String add : addList) {
                Element e = new Element("include");
                e.setAttribute("uri", add);
                testEle.addContent(e);
            }

            String newF = project.getAbsolutePath() + ".new";

            XMLOutputter xmlOutputter = new XMLOutputter();
            Writer writer = new BufferedWriter(new FileWriter(newF));
            xmlOutputter.output(document, writer);
            writer.flush();
            FileUtil.closeCloseAbleQuitly(writer);

            final File newFile = new File(newF);
            return new Task() {

                public void finish() {
                    boolean hasError = false;
                    File backUpFile = new File(project.getAbsoluteFile() + ".backup");
                    try {
                        FileUtils.copyFile(project, backUpFile);
                        FileUtils.copyFile(newFile, project);

                        oldTask.finish();
                    } catch (Exception e) {
                        hasError = true;
                        e.printStackTrace();
                    } finally {
                        try {
                            FileUtils.copyFile(backUpFile, project);
                        } catch (IOException e) {
                            hasError = true;
                            e.printStackTrace();
                        }
                        newFile.delete();
                        backUpFile.delete();
                    }
                    if (hasError) {
                        System.exit(-1);
                    }
                }
            };
        }

        return oldTask;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        FileUtil.closeCloseAbleQuitly(fis);
    }
}

From source file:Main.java

public static void formatXML(Document doc, Reader xslStream, Writer writer) throws Exception {
    DOMSource xmlSource = new DOMSource(doc);
    StreamSource xslSource = new StreamSource(xslStream);
    formatXML(xmlSource, xslSource, writer);
    writer.flush();
}

From source file:com.spectralogic.ds3client.helpers.channels.WindowedSeekableByteChannel_Test.java

private static void writeToChannel(final String string, final SeekableByteChannel channel) throws IOException {
    final Writer writer = Channels.newWriter(channel, "UTF-8");
    writer.write(string);/*from   w  w w  . j  a va  2  s .com*/
    writer.flush();
}

From source file:com.alfaariss.oa.util.saml2.binding.soap11.SOAP11Utils.java

/**
 * Construct and send a SOAP Fault./* w  w w. j a  va2  s. c  om*/
 *
 * Constructs a SOAP Fault message and send it using the out transport of
 * the message context.
 * 
 * The followinf SOAP codes are send:
 * <dl>
 *  <dt>soap11:Client</dt>
 *      <dd>In case of a {@link RequestorEvent#REQUEST_INVALID}</dd>
 *  <dt>soap11:Server</dt>
 *      <dd>In case of other {@link RequestorEvent}s</dd>   
 * </dl>
 * 
 * @param messageContext The message context.
 * @param event The requestor event.
 * @throws OAException If sending fails due to internal error.
 */
public static void sendSOAPFault(
        SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> messageContext,
        RequestorEvent event) throws OAException {
    //DD SOAP HTTP server MUST return a "500 Internal Server Error" response and include a SOAP fault [saml-bindings-2.0-os r372]
    try {
        /** XMLObjectBuilderFactory */
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        //Build SOAP Envelope and Body
        EnvelopeBuilder envBuilder = (EnvelopeBuilder) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
        Envelope envelope = envBuilder.buildObject();

        BodyBuilder bodyBuilder = (BodyBuilder) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
        Body body = bodyBuilder.buildObject();

        //Build fault
        FaultCodeBuilder faultCodeBuilder = (FaultCodeBuilder) builderFactory
                .getBuilder(FaultCode.DEFAULT_ELEMENT_NAME);
        FaultCode code = faultCodeBuilder.buildObject(FaultCode.DEFAULT_ELEMENT_NAME);
        FaultStringBuilder faultStringBuilder = (FaultStringBuilder) builderFactory
                .getBuilder(FaultString.DEFAULT_ELEMENT_NAME);
        FaultString faultString = faultStringBuilder.buildObject(FaultString.DEFAULT_ELEMENT_NAME);
        switch (event) {
        case REQUEST_INVALID: {
            code.setValue(new QName(SOAPConstants.SOAP11_NS, "Client", SOAPConstants.SOAP11_PREFIX));
            faultString.setValue(event.name());
            break;
        }
        default: {
            code.setValue(new QName(SOAPConstants.SOAP11_NS, "Server", SOAPConstants.SOAP11_PREFIX));
            faultString.setValue(RequestorEvent.INTERNAL_ERROR.name());
            break;
        }
        }
        FaultBuilder faultBuilder = (FaultBuilder) builderFactory.getBuilder(Fault.DEFAULT_ELEMENT_NAME);
        Fault fault = faultBuilder.buildObject();

        fault.setCode(code);

        fault.setMessage(faultString);

        body.getUnknownXMLObjects().add(fault);
        envelope.setBody(body);

        //Marshall message
        messageContext.setOutboundMessage(envelope);
        Marshaller m = Configuration.getMarshallerFactory().getMarshaller(Envelope.DEFAULT_ELEMENT_NAME);
        m.marshall(envelope);

        //Send SOAP Fault
        HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport();
        HTTPTransportUtils.addNoCacheHeaders(outTransport);
        HTTPTransportUtils.setUTF8Encoding(outTransport);
        HTTPTransportUtils.setContentType(outTransport, "text/xml");
        outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security");

        outTransport.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), SAML2Constants.CHARSET);
        XMLHelper.writeNode(envelope.getDOM(), out);
        out.flush();
    } catch (UnsupportedEncodingException e) {
        _logger.error(SAML2Constants.CHARSET + " encoding error", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (IOException e) {
        _logger.error("I/O error while sending SOAP Fault", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (MarshallingException e) {
        _logger.error("Marshalling error while sending SOAP Fault", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.bigloupe.web.monitor.util.JSONUtil.java

/**
 * Writes object to the writer as JSON using Jackson and adds a new-line
 * before flushing./*from w  ww  .ja v a 2  s.c  om*/
 * 
 * @param writer
 *            the writer to write the JSON to
 * @param object
 *            the object to write as JSON
 * @throws IOException
 *             if the object can't be serialized as JSON or written to the
 *             writer
 */
public static void writeJson(Writer writer, Object object) throws IOException {
    ObjectMapper om = new ObjectMapper();
    om.enable(SerializationFeature.INDENT_OUTPUT);
    om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

    writer.write(om.writeValueAsString(object));
    writer.write("\n");
    writer.flush();
}