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.shootoff.session.io.JSONSessionWriter.java

@SuppressWarnings("unchecked")
@Override//from  w ww.  ja  v a  2s  .  com
public void visitEnd() {
    JSONObject session = new JSONObject();
    session.put("cameras", cameras);

    Writer file = null;

    try {
        file = new OutputStreamWriter(new FileOutputStream(sessionFile), "UTF-8");
        file.write(session.toJSONString());
        file.flush();
    } catch (IOException e) {
        logger.error("Error writing JSON session", e);
    } finally {
        try {
            if (file != null)
                file.close();
        } catch (IOException e) {
            logger.error("Error closing JSON session", e);
        }

    }
}

From source file:edu.vt.middleware.ldap.LdapSearch.java

/**
 * This will perform an LDAP search with the supplied query and return
 * attributes. The results will be written to the supplied <code>
 * Writer</code>./*from   www  . j ava 2 s  .  c  om*/
 *
 * @param  query  <code>String</code> to search for
 * @param  attrs  <code>String[]</code> to return
 * @param  writer  <code>Writer</code> to write to
 *
 * @throws  NamingException  if an error occurs while searching
 * @throws  IOException  if an error occurs while writing search results
 */
public void search(final String query, final String[] attrs, final Writer writer)
        throws NamingException, IOException {
    final LdapResult lr = this.beanFactory.newLdapResult();
    lr.addEntries(this.search(query, attrs));
    writer.write(lr.toString());
    writer.flush();
}

From source file:com.joliciel.talismane.languageDetector.DefaultLanguageDetectorProcessor.java

@Override
public void onNextText(String text, List<WeightedOutcome<Locale>> results, Writer writer) {
    try {/*from  w  w  w .j  a  va 2s  .  c o m*/
        if (writer == null)
            writer = out;

        writer.write(text + "\n");
        for (WeightedOutcome<Locale> result : results) {
            writer.write(result.getOutcome().toLanguageTag() + "\t" + result.getWeight() + "\n");
        }
        writer.flush();
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:edu.pitt.dbmi.ipm.service.EntityStreamingOutput.java

/**
 * Writes to stream.//from  w  ww .  j  a  v a  2 s . c o m
 */
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {

    byte[] buffer = new byte[1024];
    int read = -1;
    InputStream instream = null;

    try {

        instream = entity.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(instream));
        Writer writer = new BufferedWriter(new OutputStreamWriter(output));

        String line = null;
        while ((line = br.readLine()) != null) {
            line = line.replaceAll("\"", "");
            writer.write(line + "\n");
            writer.flush();
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {

        if (instream != null)
            instream.close();

        if (output != null)
            output.close();

        httpclient.getConnectionManager().shutdown();
    }

}

From source file:be.fedict.eid.pkira.blm.model.mail.MailTemplateBean.java

/**
 * {@inheritDoc}/*from  w  ww .j av a  2s  .c o  m*/
 */
@Override
public String createMailMessage(String templateName, Map<String, Object> parameters, String localeStr) {
    parameters.put("configuration", configurationEntryQuery.getAsMap());

    Locale locale = Locale.ENGLISH;
    try {
        locale = LocaleUtils.toLocale(localeStr);
    } catch (Exception e) {
        log.error("Invalid locale string: " + localeStr, e);
    }

    try {
        Writer out = new StringWriter();
        Template temp = configuration.getTemplate(templateName, locale);
        temp.process(parameters, out);
        out.flush();

        return out.toString();
    } catch (IOException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Error creating mail message", e);
        return null;
    } catch (TemplateException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Error creating mail message", e);
        return null;
    }
}

From source file:io.vertx.ext.shell.term.TelnetTermServerTest.java

@Test
public void testRead(TestContext context) throws IOException {
    Async async = context.async();//from   w  w w  .j av  a  2  s.c  o m
    startTelnet(context, term -> {
        term.stdinHandler(s -> {
            context.assertEquals("hello_from_client", s);
            async.complete();
        });
    });
    client.connect("localhost", server.actualPort());
    Writer writer = new OutputStreamWriter(client.getOutputStream());
    writer.write("hello_from_client");
    writer.flush();
}

From source file:android.security.cts.BrowserTest.java

/**
 * See Bug 6212665 for detailed information about this issue.
 *//*ww w .j ava2s . c om*/
public void testBrowserPrivateDataAccess() throws Throwable {

    // Create a list of all intents for http display. This includes all browsers.
    List<Intent> intents = createAllIntents(Uri.parse("http://www.google.com"));
    String action = "\"" + mWebServer.getBaseUri() + "/\"";
    // test each browser
    for (Intent intent : intents) {
        // reset state
        mWebServer.resetRequestState();
        // define target file, which is supposedly protected from this app
        String targetFile = "file://" + getTargetFilePath();
        String html = "<html><body>\n" + "  <form name=\"myform\" action=" + action + " method=\"post\">\n"
                + "  <input type='text' name='val'/>\n"
                + "  <a href=\"javascript :submitform()\">Search</a></form>\n" + "<script>\n"
                + "  var client = new XMLHttpRequest();\n" + "  client.open('GET', '" + targetFile + "');\n"
                + "  client.onreadystatechange = function() {\n" + "  if(client.readyState == 4) {\n"
                + "    myform.val.value = client.responseText;\n" + "    document.myform.submit(); \n"
                + "  }}\n" + "  client.send();\n" + "</script></body></html>\n";
        String filename = "jsfileaccess.html";
        // create a local HTML to access protected file
        FileOutputStream out = mContext.openFileOutput(filename, mContext.MODE_WORLD_READABLE);
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        writer.write(html);
        writer.flush();
        writer.close();

        String filepath = mContext.getFileStreamPath(filename).getAbsolutePath();
        Uri uri = Uri.parse("file://" + filepath);
        // do a file request
        intent.setData(uri);
        mContext.startActivity(intent);
        /*
         * Wait 5 seconds for the browser to contact the server, but
         * fail fast if we detect the bug
         */
        for (int j = 0; j < 5; j++) {
            // it seems that even when cross-origin policy prevents a file
            // access, browser is still doing a POST sometimes, but it just
            // sends the query part and no private data. Make sure this does not
            // cause a false alarm.
            if (mWebServer.getRequestEntities().size() > 0) {
                int len = 0;
                for (HttpEntity entity : mWebServer.getRequestEntities()) {
                    len += entity.getContentLength();
                }
                final int queryLen = "val=".length();
                assertTrue("Failed preventing access to private data", len <= queryLen);
            }
            Thread.sleep(1000);
        }
    }
}

From source file:org.fcrepo.http.api.responses.BaseHtmlProvider.java

@Override
public void writeTo(final Dataset rdf, final Class<?> type, final Type genericType,
        final Annotation[] annotations, final MediaType mediaType,
        final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException {

    LOGGER.debug("Writing an HTML response for: {}", rdf);
    LOGGER.trace("Attempting to discover our subject");
    final Node subject = getDatasetSubject(rdf);

    // add standard headers
    httpHeaders.put("Content-type", of((Object) TEXT_HTML));
    setCachingHeaders(httpHeaders, rdf, uriInfo);

    final Template nodeTypeTemplate = getTemplate(rdf, subject, annotations);

    final Context context = getContext(rdf, subject);

    // the contract of MessageBodyWriter<T> is _not_ to close the stream
    // after writing to it
    final Writer outWriter = new OutputStreamWriter(entityStream);
    nodeTypeTemplate.merge(context, outWriter);
    outWriter.flush();

}

From source file:org.apache.manifoldcf.scriptengine.ScriptParser.java

public static String convertToString(HttpResponse httpResponse) throws IOException {
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        InputStream is = entity.getContent();
        try {/*w  w  w  .  j a v  a2 s.  c o m*/
            Charset charSet;
            try {
                ContentType ct = ContentType.get(entity);
                if (ct == null)
                    charSet = StandardCharsets.UTF_8;
                else
                    charSet = ct.getCharset();
            } catch (ParseException e) {
                charSet = StandardCharsets.UTF_8;
            }
            char[] buffer = new char[65536];
            Reader r = new InputStreamReader(is, charSet);
            Writer w = new StringWriter();
            try {
                while (true) {
                    int amt = r.read(buffer);
                    if (amt == -1)
                        break;
                    w.write(buffer, 0, amt);
                }
            } finally {
                w.flush();
            }
            return w.toString();
        } finally {
            is.close();
        }
    }
    return "";
}

From source file:com.ikon.util.impexp.DbRepositoryChecker.java

/**
 * Read document contents./*from   w  w  w  . ja v a  2  s  .  co m*/
 */
private static ImpExpStats readDocument(String token, String docPath, boolean versions, Writer out,
        InfoDecorator deco) throws PathNotFoundException, AccessDeniedException, RepositoryException,
        DatabaseException, IOException {
    log.debug("readDocument({})", docPath);
    DocumentModule dm = ModuleManager.getDocumentModule();
    File fsPath = new File(Config.NULL_DEVICE);
    ImpExpStats stats = new ImpExpStats();
    Document doc = dm.getProperties(token, docPath);

    try {
        FileOutputStream fos = new FileOutputStream(fsPath);
        InputStream is = dm.getContent(token, docPath, false);
        IOUtils.copy(is, fos);
        IOUtils.closeQuietly(is);

        if (versions) { // Check version history
            for (Version ver : dm.getVersionHistory(token, docPath)) {
                is = dm.getContentByVersion(token, docPath, ver.getName());
                IOUtils.copy(is, fos);
                IOUtils.closeQuietly(is);
            }
        }

        IOUtils.closeQuietly(fos);
        out.write(deco.print(docPath, doc.getActualVersion().getSize(), null));
        out.flush();

        // Stats
        stats.setSize(stats.getSize() + doc.getActualVersion().getSize());
        stats.setDocuments(stats.getDocuments() + 1);

        FileLogger.info(BASE_NAME, "Checked document ''{0}''", docPath);
    } catch (RepositoryException e) {
        log.error(e.getMessage());
        stats.setOk(false);
        FileLogger.error(BASE_NAME, "RepositoryException ''{0}''", e.getMessage());
        out.write(deco.print(docPath, doc.getActualVersion().getSize(), e.getMessage()));
        out.flush();
    }

    return stats;
}