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.ontopia.persistence.rdbms.CSVExport.java

public void exportCSV(Writer writer, String table, String[] columns) throws SQLException, IOException {
    Statement stm = conn.createStatement();
    ResultSet rs = stm.executeQuery("select " + StringUtils.join(columns, ", ") + " from " + table);
    try {//from   w  w  w. j  ava  2s. c o m
        while (rs.next()) {
            for (int i = 1; i <= columns.length; i++) {
                if (i > 1)
                    writer.write(separator);
                writer.write('"');
                String value = rs.getString(i);
                if (value != null) {
                    writer.write(StringUtils.replace(value, "\"", "\\\""));
                }
                writer.write('"');
            }
            writer.write('\n');
        }
    } finally {
        rs.close();
        stm.close();
    }
    writer.flush();
}

From source file:fi.okm.mpass.shibboleth.profile.impl.BuildMetaRestResponse.java

/** {@inheritDoc} */
@Override/*from  ww  w .j  a  v a  2  s  . c o m*/
@Nonnull
public Event execute(@Nonnull final RequestContext springRequestContext) {
    ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this);
    final HttpServletRequest httpRequest = getHttpServletRequest();
    pushHttpResponseProperties();
    final HttpServletResponse httpResponse = getHttpServletResponse();

    try {
        final Writer out = new OutputStreamWriter(httpResponse.getOutputStream(), "UTF-8");

        if (!HttpMethod.GET.toString().equals(httpRequest.getMethod())) {
            log.warn("{}: Unsupported method attempted {}", getLogPrefix(), httpRequest.getMethod());
            out.append(makeErrorResponse(HttpStatus.SC_METHOD_NOT_ALLOWED,
                    httpRequest.getMethod() + " not allowed", "Only GET is allowed"));
        } else if (metaDTO != null) {
            final Gson gson = new Gson();
            out.append(gson.toJson(getMetaDTO()));
            httpResponse.setStatus(HttpStatus.SC_OK);
        } else {
            out.append(
                    makeErrorResponse(HttpStatus.SC_NOT_IMPLEMENTED, "Not implemented on the server side", ""));
        }
        out.flush();
    } catch (IOException e) {
        log.error("{}: Could not encode the JSON response", getLogPrefix(), e);
        httpResponse.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE);
        return ActionSupport.buildEvent(this, EventIds.IO_ERROR);
    }
    return ActionSupport.buildProceedEvent(this);
}

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

/**
 * Write a single attachment and its payload
 *///from   ww w.j a  v a 2  s  .  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));
    }
    if (attachment.mContentId != null) {
        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:brugerautorisation.server.BrugerProtocol.java

private void cmd(List<String> msg) {
    OutputStreamWriter out = null;
    Writer writer = null;
    try {/*from  w  w  w. ja v a2s.co m*/
        out = new OutputStreamWriter(server.getOutputStream());
        writer = new BufferedWriter(out);
        switch (msg.get(0).toLowerCase().replace("\n", "")) {
        case ("hello"):
            break;
        case ("login"):
            System.out.println("v");
            JSONObject json = new JSONObject(msg.get(1));
            JSONObject json_return = new JSONObject();
            try {
                Bruger b = ba.hentBruger(json.getString("username"), json.getString("password"));
                json_return.put("username", b.brugernavn);
            } catch (SOAPFaultException e) {
                json_return.put("error", e.getMessage());
            }
            writer.write(json_return.toString());
            writer.flush();
            //out.flush();
            break;
        case ("forgot_pass"):
            break;
        default:
            System.out.println("ikke fundet");
            break;
        }
    } catch (IOException ex) {
        Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            writer.close();
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

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

/**
 * Write a single attachment and its payload
 *//*from ww w . j  a va  2s. c  o  m*/
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment)
        throws IOException, MessagingException {
    //       String attachmentName = attachment.mFileName;
    String attachmentName = EncoderUtil.encodeAddressDisplayName(attachment.mFileName);

    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachmentName + "\"");

    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=\"" + attachmentName + "\";"
                + "\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:marytts.datatypes.MaryData.java

/**
 * Write our internal representation to writer <code>w</code>,
 * in the appropriate way as determined by our <code>type</code>.
 * Only XML and Text data can be written to a writer, audio data cannot.
 * "Helpers" needed to read the data, such as XML parser objects,
 * are created when they are needed.//from  w ww  .ja  va2 s .  c  om
 */
public void writeTo(Writer w) throws TransformerConfigurationException, FileNotFoundException,
        TransformerException, IOException, Exception {
    if (type.isUtterances())
        throw new IOException("Cannot write out utterance-based data type!");
    if (type.isXMLType()) {
        throw new IOException("Better write XML data to an OutputStream, not to a Writer");
    } else if (type.isTextType()) { // caution: XML types are text types!
        w.write(plainText);
        w.flush();
        logger.debug("Writing Text output:\n" + plainText);
    } else { // audio - cannot write this to a writer
        throw new Exception("Illegal attempt to write audio data to a character Writer");
    }
}

From source file:edu.lternet.pasta.portal.Harvester.java

/**
 *  Reads character data from the <code>StringBuffer</code> provided, and 
 *  writes it to the <code>Writer</code> provided, using a buffered write. 
 *
 *  @param  buffer              <code>StringBuffer</code> whose contents are 
 *                              to be written to the <code>Writer</code>
 *
 *  @param  writer              <code>java.io.Writer</code> where contents 
 *                              of StringBuffer are to be written
 *
 *  @param  closeWhenFinished   <code>boolean</code> value to indicate 
 *                              whether Reader should be closed when reading
 *                              finished
 *
 *  @return                     <code>StringBuffer</code> containing  
 *                              characters read from the <code>Reader</code>
 *
 *  @throws IOException if there are problems accessing or using the Writer.
 *///from  www .j ava  2 s.  c  o m
public void writeToWriter(StringBuffer buffer, Writer writer, boolean closeWhenFinished) throws IOException {
    if (writer == null) {
        throw new IOException("writeToWriter(): Writer is null");
    }

    char[] bufferChars = new char[buffer.length()];
    buffer.getChars(0, buffer.length(), bufferChars, 0);

    try {
        writer.write(bufferChars);
        writer.flush();
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (closeWhenFinished) {
            try {
                if (writer != null)
                    writer.close();
            } catch (IOException ce) {
                ce.printStackTrace();
            }
        }
    }
}

From source file:com.bsb.cms.commons.template.freemarker.FreemarkerGenerator.java

@Override
public void createFile(String ftlTemplateFile, Map<String, Object> dataMap, String filePath)
        throws TemplateRuntimeException {
    Writer out = null;

    try {//from w  w  w . j a  v  a 2s . c  om
        Template temp = getTemplate(ftlTemplateFile);

        FreemarkerUtils.getMap(dataMap);
        filePath = filePath.replace("\\", "/");
        String savePath = StringUtils.substringBeforeLast(filePath, "/");
        // String realPath = PublishUtils.getPublistHomeDir() + savePath;
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        out = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
        temp.process(dataMap, out); // Merge data model with template
    } catch (Exception e) {
        throw new TemplateRuntimeException(e.getMessage());
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    log.debug(">>>>create file:" + filePath);
}

From source file:com.scase.core.service.impl.StaticServiceImpl.java

@Transactional(readOnly = true)
public int build(String templatePath, String staticPath, Map<String, Object> model) {
    Assert.hasText(templatePath);//  ww  w .j  a  v a  2s . c om
    Assert.hasText(staticPath);

    FileOutputStream fileOutputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    Writer writer = null;
    try {
        freemarker.template.Template template = freeMarkerConfigurer.getConfiguration()
                .getTemplate(templatePath);
        File staticFile = new File(servletContext.getRealPath(staticPath));
        File staticDirectory = staticFile.getParentFile();
        if (!staticDirectory.exists()) {
            staticDirectory.mkdirs();
        }
        fileOutputStream = new FileOutputStream(staticFile);
        outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
        writer = new BufferedWriter(outputStreamWriter);
        template.process(model, writer);
        writer.flush();
        return 1;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(outputStreamWriter);
        IOUtils.closeQuietly(fileOutputStream);
    }
    return 0;
}

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

@Override
void write(Writer out) throws IOException {
    //this.raw().writeJSONString(out);
    if (raw == null) {
        out.write("null");
    } else {//from www .  ja v  a2  s  . c  om
        boolean first = true;
        Iterable<String> keys = keys();
        Iterator<String> iter = keys.iterator();

        out.write('{');
        while (iter.hasNext()) {
            if (first) {
                first = false;
            } else {
                out.write(',');
            }
            String key = iter.next();
            Object value = raw.get(key);

            out.write('\"');
            out.write(JSONObject.escape(key));
            out.write('\"');
            out.write(':');
            JSONWrapper.write(value, out);
        }
        out.write('}');
    }
    out.flush();
}