Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.dhatim.delivery.dom.serialize.SerializerTest.java

@Test
public void testSerailize() {
    MockExecutionContext executionContext = new MockExecutionContext();

    // Target a resource at the "document fragment" i.e. the root..

    // Don't write xxx but write its child elements
    SmooksResourceConfiguration configuration = new SmooksResourceConfiguration(
            SmooksResourceConfiguration.DOCUMENT_FRAGMENT_SELECTOR, "deviceX", "....");
    ((MockContentDeliveryConfig) executionContext.deliveryConfig).serializationUnits.addMapping(
            SmooksResourceConfiguration.DOCUMENT_FRAGMENT_SELECTOR, configuration,
            Configurator.configure(new AddAttributeSerializer(), configuration));

    // Don't write xxx but write its child elements
    configuration = new SmooksResourceConfiguration("xxx", "deviceX", "....");
    ((MockContentDeliveryConfig) executionContext.deliveryConfig).serializationUnits.addMapping("xxx",
            configuration, Configurator.configure(new RemoveTestSerializationUnit(), configuration));

    // write yyyy as a badly-formed empty element
    configuration = new SmooksResourceConfiguration("yyyy", "deviceX", "....");
    configuration.setParameter("wellformed", "false");
    ((MockContentDeliveryConfig) executionContext.deliveryConfig).serializationUnits.addMapping("yyyy",
            configuration, Configurator.configure(new EmptyElTestSerializationUnit(), configuration));

    /// write zzz as a well-formed empty element
    configuration = new SmooksResourceConfiguration("zzz", "deviceX", "....");
    ((MockContentDeliveryConfig) executionContext.deliveryConfig).serializationUnits.addMapping("zzz",
            configuration, Configurator.configure(new EmptyElTestSerializationUnit(), configuration));

    try {/*from ww w.  j  a va 2 s.  co m*/
        Document doc = XmlUtil.parseStream(getClass().getResourceAsStream("testmarkup.xxml"),
                XmlUtil.VALIDATION_TYPE.NONE, true);
        Serializer serializer = new Serializer(doc, executionContext);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(output);

        serializer.serailize(writer);
        writer.flush();
        byte[] actualBytes = output.toByteArray();
        log.debug(new String(actualBytes));
        boolean areEqual = CharUtils.compareCharStreams(getClass().getResourceAsStream("testmarkup.xxml.ser_1"),
                new ByteArrayInputStream(actualBytes));
        assertTrue("Unexpected Serialization result failure.", areEqual);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:com.norconex.importer.handler.transformer.AbstractCharStreamTransformer.java

@Override
protected final void transformApplicableDocument(String reference, InputStream input, OutputStream output,
        ImporterMetadata metadata, boolean parsed) throws ImporterHandlerException {

    try {/*from ww  w.j  a va2s  . c  o  m*/
        InputStreamReader is = new InputStreamReader(input, CharEncoding.UTF_8);
        OutputStreamWriter os = new OutputStreamWriter(output, CharEncoding.UTF_8);
        transformTextDocument(reference, is, os, metadata, parsed);
        os.flush();
    } catch (IOException e) {
        throw new ImporterHandlerException("Cannot transform character stream.", e);
    }
}

From source file:net.grinder.util.LogCompressUtils.java

/**
 * Compress multiple Files with the given encoding.
 *
 * @param logFiles     files to be compressed
 * @param fromEncoding log file encoding
 * @param toEncoding   compressed log file encoding
 * @return compressed file byte array/*from   www . j a  va2 s . c om*/
 */
public static byte[] compress(File[] logFiles, Charset fromEncoding, Charset toEncoding) {
    FileInputStream fis = null;
    InputStreamReader isr = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    OutputStreamWriter osw = null;
    if (toEncoding == null) {
        toEncoding = Charset.defaultCharset();
    }
    if (fromEncoding == null) {
        fromEncoding = Charset.defaultCharset();
    }
    try {
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        osw = new OutputStreamWriter(zos, toEncoding);
        for (File each : logFiles) {
            try {
                fis = new FileInputStream(each);
                isr = new InputStreamReader(fis, fromEncoding);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                char[] buffer = new char[COMPRESS_BUFFER_SIZE];
                int count;
                while ((count = isr.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    osw.write(buffer, 0, count);
                }
                osw.flush();
                zos.flush();
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compressing {} : {}", each.getAbsolutePath(), e.getMessage());
                LOGGER.debug("Details ", e);
            } finally {
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(fis);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compressing log : {} ", e.getMessage());
        LOGGER.debug("Details : ", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(osw);
    }
}

From source file:org.apache.olingo.fit.utils.XMLElement.java

public void setContent(final InputStream content) throws IOException {
    this.content.reset();

    final InputStreamReader reader = new InputStreamReader(content, Constants.ENCODING);
    final OutputStreamWriter writer = new OutputStreamWriter(this.content, Constants.ENCODING);
    IOUtils.copyLarge(reader, writer);//from   www.j ava  2s. c  o  m

    writer.flush();
    IOUtils.closeQuietly(reader);
    IOUtils.closeQuietly(writer);
    IOUtils.closeQuietly(content);
}

From source file:com.baqr.baqrcam.http.ModInternationalization.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//from ww  w  .j  a  va  2 s  . c  o  m

    final EntityTemplate body = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            writer.write(mJSON);
            writer.flush();
        }
    });

    response.setStatusCode(HttpStatus.SC_OK);
    body.setContentType("text/json; charset=UTF-8");
    response.setEntity(body);

}

From source file:net.facework.core.http.ModInternationalization.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//  w  w  w .j  a  v  a2  s  . c o  m

    final EntityTemplate body = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            writer.write(mJSON);
            writer.flush();
        }
    });

    response.setStatusCode(HttpStatus.SC_OK);
    body.setContentType("text/json; charset=UTF-8");
    response.setEntity(body);

}

From source file:io.logspace.hq.core.solr.event.SolrNativeQueryService.java

private InputStream serializeResponse(SolrParams params, QueryResponse response) throws IOException {
    LocalSolrQueryRequest solrQueryRequest = new LocalSolrQueryRequest(null, params);
    SolrQueryResponse solrQueryResponse = new SolrQueryResponse();
    solrQueryResponse.setAllValues(response.getResponse());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
    this.jsonResponseWriter.write(writer, solrQueryRequest, solrQueryResponse);
    writer.flush();

    return new ByteArrayInputStream(baos.toByteArray());
}

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.AkismetCommentValidator.java

public int validate(WeblogEntryComment comment, RollerMessages messages) {
    StringBuffer sb = new StringBuffer();
    sb.append("blog=").append(WebloggerFactory.getWeblogger().getUrlStrategy()
            .getWeblogURL(comment.getWeblogEntry().getWebsite(), null, true)).append("&");
    sb.append("user_ip=").append(comment.getRemoteHost()).append("&");
    sb.append("user_agent=").append(comment.getUserAgent()).append("&");
    sb.append("referrer=").append(comment.getReferrer()).append("&");
    sb.append("permalink=").append(comment.getWeblogEntry().getPermalink()).append("&");
    sb.append("comment_type=").append("comment").append("&");
    sb.append("comment_author=").append(comment.getName()).append("&");
    sb.append("comment_author_email=").append(comment.getEmail()).append("&");
    sb.append("comment_author_url=").append(comment.getUrl()).append("&");
    sb.append("comment_content=").append(comment.getContent());

    try {//from  www. j  a va2 s .c om
        URL url = new URL("http://" + apikey + ".rest.akismet.com/1.1/comment-check");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        conn.setRequestProperty("User_Agent", "Roller " + WebloggerFactory.getWeblogger().getVersion());
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8");
        conn.setRequestProperty("Content-length", Integer.toString(sb.length()));

        OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
        osr.write(sb.toString(), 0, sb.length());
        osr.flush();
        osr.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = br.readLine();
        if ("true".equals(response)) {
            messages.addError("comment.validator.akismetMessage");
            return 0;
        } else
            return 100;
    } catch (Exception e) {
        log.error("ERROR checking comment against Akismet", e);
    }
    return 0; // interpret error as spam: better safe than sorry? 
}

From source file:org.pentaho.chart.plugin.openflashchart.outputs.OpenFlashChartOutput.java

public OutputStream persistChart(OutputStream outputStream, IOutput.OutputTypes fileType, int width, int height)
        throws PersistenceException {
    if (outputStream == null) {
        outputStream = new ByteArrayOutputStream();
    }// ww  w  .  j av  a2 s .c  om
    try {
        outputStream.flush();
    } catch (IOException e1) {
        throw new PersistenceException(e1);
    }
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8"); //$NON-NLS-1$
        outputStreamWriter.write(chart.toString());
        outputStreamWriter.flush();
    } catch (UnsupportedEncodingException e) {
        throw new PersistenceException(e);
    } catch (OFCException e) {
        throw new PersistenceException(e);
    } catch (IOException e) {
        throw new PersistenceException(e);
    }
    return outputStream;
}

From source file:gov.medicaid.verification.BaseSOAPClient.java

/**
 * Invokes the web service using the request provided.
 *
 * @param serviceURL the end point reference
 * @param original the payload/*from w w  w . j a v  a 2  s. c o m*/
 * @return the response
 * @throws IOException for IO errors while executing the request
 * @throws TransformerException for any transformation errors
 */
protected String invoke(String serviceURL, String original) throws IOException, TransformerException {
    URL url = new URL(serviceURL);
    HttpURLConnection rc = (HttpURLConnection) url.openConnection();
    rc.setRequestMethod("POST");
    rc.setDoOutput(true);
    rc.setDoInput(true);
    rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

    System.out.println("before transform:" + original);
    String request = transform(requestXSLT, original);
    System.out.println("after transform:" + request);

    int len = request.length();
    rc.setRequestProperty("Content-Length", Integer.toString(len));
    rc.connect();
    OutputStreamWriter out = new OutputStreamWriter(rc.getOutputStream());
    out.write(request, 0, len);
    out.flush();

    InputStreamReader read;
    try {
        read = new InputStreamReader(rc.getInputStream());
    } catch (IOException e) {
        read = new InputStreamReader(rc.getErrorStream());
    }

    try {
        String response = IOUtils.toString(read);
        System.out.println("actual result:" + response);
        String transformedResponse = transform(responseXSLT, response);
        System.out.println("transformed result:" + transformedResponse);
        return transformedResponse;
    } finally {
        read.close();
        rc.disconnect();
    }
}