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:net.nan21.dnet.core.web.controller.data.AbstractDsReadController.java

@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_PRINT)
@ResponseBody/*from  w ww  . j  a va 2s.  c  o m*/
public String print(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String filterString,
        @RequestParam(value = Constants.REQUEST_PARAM_ADVANCED_FILTER, required = false, defaultValue = "") String filterRulesString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = DEFAULT_RESULT_START) int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = DEFAULT_RESULT_SIZE) int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        @RequestParam(value = Constants.REQUEST_PARAM_EXPORT_INFO, required = true, defaultValue = "") String exportInfoString,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new String[] { resourceName, dataFormat, Constants.DS_ACTION_PRINT });
        }

        if (logger.isDebugEnabled()) {

            logger.debug("  --> request-filter: {} ", new String[] { filterString });
            logger.debug("  --> request-params: {} ", new String[] { paramString });
            logger.debug("  --> request-result-range: {} ",
                    new String[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_EXPORT, null);

        IDsService<M, F, P> service = this.findDsService(resourceName);

        IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json");

        F filter = marshaller.readFilterFromString(filterString);
        P params = marshaller.readParamsFromString(paramString);

        ExportInfo exportInfo = marshaller.readDataFromString(exportInfoString, ExportInfo.class);
        exportInfo.prepare(service.getModelClass());

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize)
                .addFilter(filter).addParams(params);

        if (orderBy != null && !orderBy.equals("")) {
            List<SortToken> sortTokens = marshaller.readListFromString(orderBy, SortToken.class);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        if (filterRulesString != null && !filterRulesString.equals("")) {
            List<FilterRule> filterRules = marshaller.readListFromString(filterRulesString, FilterRule.class);
            builder.addFilterRules(filterRules);
        }

        List<M> data = service.find(builder);

        File _tplDir = null;
        String _tplName = null;

        String _tpl = this.getSettings().getParam(SysParams_Core.CORE_PRINT_HTML_TPL);

        if (_tpl == null || "".equals(_tpl)) {
            _tpl = "print-template/print.ftl";
        }

        _tpl = Session.user.get().getWorkspace().getWorkspacePath() + "/" + _tpl;
        File _tplFile = new File(_tpl);

        _tplDir = _tplFile.getParentFile();
        _tplName = _tplFile.getName();

        if (!_tplFile.exists()) {

            // _tplDir = _tplFile.getParentFile();

            if (!_tplDir.exists()) {
                _tplDir.mkdirs();
            }

            Resource resource = new ClassPathResource("WEB-INF/freemarker/print.ftl");
            FileUtils.copyFile(resource.getFile(), _tplFile);

        }

        Configuration cfg = new Configuration();
        cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);
        cfg.setDirectoryForTemplateLoading(_tplDir);

        Map<String, Object> root = new HashMap<String, Object>();

        root.put("printer", new ModelPrinter());
        root.put("data", data);
        root.put("filter", filter);
        root.put("params", params);
        root.put("client", Session.user.get().getClient());

        Map<String, Object> reportConfig = new HashMap<String, Object>();
        reportConfig.put("logo", this.getSettings().getParam(SysParams_Core.CORE_LOGO_URL_REPORT));
        reportConfig.put("runBy", Session.user.get().getName());
        reportConfig.put("runAt", new Date());
        reportConfig.put("title", exportInfo.getTitle());
        reportConfig.put("orientation", exportInfo.getLayout());
        reportConfig.put("columns", exportInfo.getColumns());
        reportConfig.put("filter", exportInfo.getFilter());

        root.put("cfg", reportConfig);

        if (dataFormat.equals(Constants.DATA_FORMAT_HTML)) {
            response.setContentType("text/html; charset=UTF-8");
        }

        Template temp = cfg.getTemplate(_tplName);
        Writer out = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding());
        temp.process(root, out);
        out.flush();
        return null;
    } catch (Exception e) {

        e.printStackTrace();
        return null;
        // return this.handleException(e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:com.athenahealth.api.APIConnection.java

/**
 * Authenticate to the athenahealth API service.
 *///  ww w  .j a  v a 2 s . c  o  m
public void authenticate() throws AuthenticationException {
    try {
        // The URL to authenticate to is determined by the version of the API specified at
        // construction.
        URL url = new URL(path_join(getBaseURL(), auth_prefixes.get(version), "/token"));
        HttpURLConnection conn = openConnection(url);
        conn.setRequestMethod("POST");

        String auth = Base64.encodeBase64String((key + ":" + secret).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + auth);

        conn.setDoOutput(true);
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("grant_type", "client_credentials");

        Writer wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        wr.write(urlencode(parameters));
        wr.flush();
        wr.close();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

        JSONObject response = new JSONObject(sb.toString());
        token = response.get("access_token").toString();
    } catch (MalformedURLException mue) {
        throw new AuthenticationException("Error authenticating with server", mue);
    } catch (IOException ioe) {
        throw new AuthenticationException("Error authenticating with server", ioe);
    }
}

From source file:annis.gui.exporter.WekaExporter.java

@Override
public void convertText(String queryAnnisQL, int contextLeft, int contextRight, Set<String> corpora,
        String keysAsString, String argsAsString, WebResource annisResource, Writer out) {
    //this is a full result export

    try {//from  ww w.  ja  va 2s . c o  m
        WebResource res = annisResource.path("search").path("matrix")
                .queryParam("corpora", StringUtils.join(corpora, ",")).queryParam("q", queryAnnisQL);

        if (argsAsString.startsWith("metakeys=")) {
            res = res.queryParam("metakeys", argsAsString.substring("metakeys".length() + 1));
        }

        InputStream result = res.get(InputStream.class);

        try {
            int c;
            while ((c = result.read()) > -1) {
                out.write(c);
            }
        } finally {
            result.close();
        }

        out.flush();
    } catch (UniformInterfaceException ex) {
        log.error(null, ex);
    } catch (ClientHandlerException ex) {
        log.error(null, ex);
    } catch (IOException ex) {
        log.error(null, ex);
    }
}

From source file:com.android.email.mail.transport.Rfc822Output.java

/**
 * Write a single attachment and its payload
 *//*from w ww  .  j  av a 2s.c  o m*/
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment)
        throws IOException, MessagingException {
    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\"");
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    // Most attachments (real files) will send Content-Disposition.  The suppression option
    // is used when sending calendar invites.
    if ((attachment.mFlags & Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName
                + "\";" + "\n size=" + Long.toString(attachment.mSize));
    }
    writeHeader(writer, "Content-ID", attachment.mContentId);
    writer.append("\r\n");

    // Set up input stream and write it out via base64
    InputStream inStream = null;
    try {
        // Use content, if provided; otherwise, use the contentUri
        if (attachment.mContentBytes != null) {
            inStream = new ByteArrayInputStream(attachment.mContentBytes);
        } else {
            // try to open the file
            Uri fileUri = Uri.parse(attachment.mContentUri);
            inStream = context.getContentResolver().openInputStream(fileUri);
        }
        // switch to output stream for base64 text output
        writer.flush();
        Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE);
        // copy base64 data and close up
        IOUtils.copy(inStream, base64Out);
        base64Out.close();

        // The old Base64OutputStream wrote an extra CRLF after
        // the output.  It's not required by the base-64 spec; not
        // sure if it's required by RFC 822 or not.
        out.write('\r');
        out.write('\n');
        out.flush();
    } catch (FileNotFoundException fnfe) {
        // Ignore this - empty file is OK
    } catch (IOException ioe) {
        throw new MessagingException("Invalid attachment.", ioe);
    }
}

From source file:com.openkm.util.impexp.RepositoryExporter.java

/**
 * Performs a recursive repository content export with metadata
 *//*from  www  .  j  a  v  a2  s.  co  m*/
private static ImpExpStats exportDocumentsHelper(String token, String fldPath, File fs, boolean metadata,
        boolean history, Writer out, InfoDecorator deco)
        throws PathNotFoundException, AccessDeniedException, RepositoryException, IOException,
        DatabaseException, ParseException, NoSuchGroupException, MessagingException {
    log.debug("exportDocumentsHelper({}, {}, {}, {}, {}, {}, {})",
            new Object[] { token, fldPath, fs, metadata, history, out, deco });
    ImpExpStats stats = new ImpExpStats();
    DocumentModule dm = ModuleManager.getDocumentModule();
    FolderModule fm = ModuleManager.getFolderModule();
    MailModule mm = ModuleManager.getMailModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Gson gson = new Gson();
    String path = null;
    File fsPath = null;

    if (firstTime) {
        path = fs.getPath();
        fsPath = new File(path);
        firstTime = false;
    } else {
        String dirName = PathUtils.decodeEntities(PathUtils.getName(fldPath));

        // Repository path needs to be "corrected" under Windoze
        path = fs.getPath() + File.separator + dirName.replace(':', '_');
        fsPath = new File(path);
        fsPath.mkdirs();
        FileLogger.info(BASE_NAME, "Created folder ''{0}''", fsPath.getPath());

        if (out != null) {
            out.write(deco.print(fldPath, 0, null));
            out.flush();
        }
    }

    for (Iterator<Mail> it = mm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Mail mailChild = it.next();
        String mailName = PathUtils.decodeEntities(PathUtils.getName(mailChild.getPath()));

        // Repository path needs to be "corrected" under Windoze
        path = fsPath.getPath() + File.separator + mailName.replace(':', '_');
        ImpExpStats mailStats = exportMail(token, mailChild.getPath(), path + ".eml", metadata, out, deco);

        // Stats
        stats.setSize(stats.getSize() + mailStats.getSize());
        stats.setMails(stats.getMails() + mailStats.getMails());
    }

    for (Iterator<Document> it = dm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Document docChild = it.next();
        String fileName = PathUtils.decodeEntities(PathUtils.getName(docChild.getPath()));

        // Repository path needs to be "corrected" under Windoze
        path = fsPath.getPath() + File.separator + fileName.replace(':', '_');
        ImpExpStats docStats = exportDocument(token, docChild.getPath(), path, metadata, history, out, deco);

        // Stats
        stats.setSize(stats.getSize() + docStats.getSize());
        stats.setDocuments(stats.getDocuments() + docStats.getDocuments());
    }

    for (Iterator<Folder> it = fm.getChildren(token, fldPath).iterator(); it.hasNext();) {
        Folder fldChild = it.next();
        ImpExpStats tmp = exportDocumentsHelper(token, fldChild.getPath(), fsPath, metadata, history, out,
                deco);
        String dirName = PathUtils.decodeEntities(PathUtils.getName(fldChild.getPath()));

        // Repository path needs to be "corrected" under Windoze
        path = fsPath.getPath() + File.separator + dirName.replace(':', '_');

        // Metadata
        if (metadata) {
            FolderMetadata fmd = ma.getMetadata(fldChild);
            String json = gson.toJson(fmd);
            FileOutputStream fos = new FileOutputStream(path + Config.EXPORT_METADATA_EXT);
            IOUtils.write(json, fos);
            fos.close();
        }

        // Stats
        stats.setSize(stats.getSize() + tmp.getSize());
        stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
        stats.setFolders(stats.getFolders() + tmp.getFolders() + 1);
        stats.setOk(stats.isOk() && tmp.isOk());
    }

    log.debug("exportDocumentsHelper: {}", stats);
    return stats;
}

From source file:io.milton.cloud.server.web.templating.TextTemplater.java

public void writePage(String templatePath, Profile currentUser, RootFolder rootFolder, Context context,
        Writer writer) throws IOException {
    if (!templatePath.startsWith("/")) {
        templatePath = "/templates/apps/" + templatePath;
    }//from  ww  w.j a v  a2  s .c o  m
    Template template = engine.getTemplate(templatePath);
    Context datamodel = new VelocityContext(context);
    datamodel.put("rootFolder", rootFolder);
    Profile user = securityManager.getCurrentUser();
    if (user != null) {
        datamodel.put("user", user);
    }
    log.info("writePage: " + templatePath);
    template.merge(datamodel, writer);
    writer.flush();
}

From source file:com.tct.emailcommon.internet.Rfc822Output.java

/**
 * Write the body text.// w w  w.  j  a v  a  2 s.co  m
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer
 * @param out the output stream inside the writer (used for byte[] access)
 * @param bodyText Plain text and HTML versions of the original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String[] bodyText,
        List<Attachment> atts) throws IOException {
    boolean html = false;
    String text = bodyText[INDEX_BODY_TEXT];
    // TS: zheng.zou 2015-03-31 EMAIL BUGFIX-962573 MOD_S
    String htmlText = bodyText[INDEX_BODY_HTML];
    if (TextUtils.isEmpty(text) || !TextUtils.isEmpty(htmlText)) {
        // TS: zheng.zou 2015-03-31 EMAIL BUGFIX-962573 MOD_E
        text = bodyText[INDEX_BODY_HTML];
        html = true;
    }
    //TS: zhaotianyong 2015-04-13 EMAIL BUGFIX_962560 ADD_S
    if (atts != null && html) {
        for (Attachment att : atts) {
            text = AttachmentUtilities.refactorHtmlBody(text, att);
        }
    }
    //TS: zhaotianyong 2015-04-13 EMAIL BUGFIX_962560 ADD_E
    if (TextUtils.isEmpty(text)) {
        writer.write("\r\n"); // a truly empty message
    } else {
        // first multipart element is the body
        final String mimeType = "text/" + (html ? "html" : "plain");
        writeHeader(writer, "Content-Type", mimeType + "; charset=utf-8");
        writeHeader(writer, "Content-Transfer-Encoding", "base64");
        writer.write("\r\n");
        final byte[] textBytes = text.getBytes("UTF-8");
        writer.flush();
        out.write(Base64.encode(textBytes, Base64.CRLF));
    }
}

From source file:mil.dod.th.ose.junit4xmltestrunner.ant.XMLJUnitResultFormatter.java

/**
 * The whole test suite ended.//from   w  w w. jav  a  2 s  . c o m
 * 
 * @param results
 *      Results of the testing
 * @throws IOException
 *      Thrown if unable to write results to output stream 
 */
public void endTestSuite(final Result results) throws IOException {
    System.setOut(m_OldStdOut);
    System.setErr(m_OldStdErr);

    Logging.log(LogService.LOG_INFO, "%n############%n%s%ntests ran: %d, failures: %d%n############",
            m_RootElement.getAttribute(ATTR_NAME), results.getRunCount(), results.getFailureCount());

    setSystemOutput();
    setSystemError();

    m_RootElement.setAttribute(ATTR_TESTS, "" + results.getRunCount());
    m_RootElement.setAttribute(ATTR_FAILURES, "" + m_Failures);
    m_RootElement.setAttribute(ATTR_ERRORS, "" + m_Errors);
    m_RootElement.setAttribute(ATTR_TIME, "" + (results.getRunTime() / ONE_SECOND));
    if (m_Out != null) {
        Writer wri = null;
        try {
            wri = new BufferedWriter(new OutputStreamWriter(m_Out, "UTF8"));
            wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
            (new DOMElementWriter()).write(m_RootElement, wri, 0, "  ");
        } finally {
            if (wri != null) {
                try {
                    wri.flush();
                } catch (final IOException ex) {
                    // ignore
                }
            }
            if (m_Out != System.out && m_Out != System.err) {
                wri.close();
            }
        }
    }
}

From source file:io.cloudslang.lang.tools.build.ArgumentProcessorUtilsTest.java

@Test
public void testGetPropertiesFromFileThrowsException() throws URISyntaxException, IOException {
    InputStream fis = null;/*from  ww w . jav  a  2s.  c  om*/
    Writer outputWriter = null;
    File tempRunConfigFile = null;
    try {
        fis = new FileInputStream(
                new File(getResource("lang/tools/build/builder_run_configuration.properties").toURI()));
        Path tempRunConfig = Files.createTempFile("temp_run_config", ".properties");

        tempRunConfigFile = tempRunConfig.toFile();
        outputWriter = new PrintWriter(new FileWriter(tempRunConfigFile));
        IOUtils.copy(fis, outputWriter);
        outputWriter.flush();

        String absolutePath = tempRunConfigFile.getAbsolutePath();
        Properties propertiesFromFile = getPropertiesFromFile(absolutePath);
        assertEquals("false", propertiesFromFile.get(TEST_COVERAGE));
        assertEquals("sequential", propertiesFromFile.get(TEST_SUITES_RUN_UNSPECIFIED));
        assertEquals("!default,vmware-local,xml-local,images", propertiesFromFile.get(TEST_SUITES_TO_RUN));
        assertEquals("images", propertiesFromFile.get(TEST_SUITES_SEQUENTIAL));
        assertEquals("xml-local,vmware-local", propertiesFromFile.get(TEST_SUITES_PARALLEL));
        assertEquals("8", propertiesFromFile.get(TEST_PARALLEL_THREAD_COUNT));
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(outputWriter);
        FileUtils.deleteQuietly(tempRunConfigFile);
    }
}

From source file:com.ibm.soatf.component.ftp.FTPComponent.java

private File generateFile(File path, String fileName, String fileContent) throws FtpComponentException {
    File localFile = new File(path, Utils.insertTimestampToFilename(fileName, FlowExecutor.getActualRunDate()));

    if (localFile.exists()) {
        return localFile;
    }//www.j  a va 2 s  . com
    Writer writer = null;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(localFile), "utf-8"));
        writer.write(fileContent);
        writer.flush();
    } catch (IOException ex) {
        //TODO
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ex) {
                ;
            }
        }
    }
    return localFile;
}