Example usage for java.io OutputStream flush

List of usage examples for java.io OutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:org.freshrss.easyrss.network.NetworkClient.java

public InputStream doPostStream(final String url, final String params) throws IOException, NetworkException {
    final HttpURLConnection conn = makeConnection(url);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    if (auth != null) {
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);
    }/*from  ww  w.j  a  v  a2s  .  c  om*/
    conn.setDoInput(true);
    conn.setDoOutput(true);
    final OutputStream output = conn.getOutputStream();
    output.write(params.getBytes());
    output.flush();
    output.close();

    conn.connect();
    try {
        final int resStatus = conn.getResponseCode();
        if (resStatus == HttpStatus.SC_UNAUTHORIZED) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        if (resStatus != HttpStatus.SC_OK) {
            throw new NetworkException("Invalid HTTP status " + resStatus + ": " + url + ".");
        }
    } catch (final IOException exception) {
        if (exception.getMessage() != null && exception.getMessage().contains("authentication")) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        throw exception;
    }
    return conn.getInputStream();
}

From source file:com.ikon.servlet.frontend.StaplingDownloadServlet.java

/**
 * //from   w  ww . j  a  v a  2s .  co m
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    String sgName = WebUtils.getString(request, "sgName");
    String groupName = sgName.substring(0, sgName.indexOf("?")) + "_" + sgName.charAt(sgName.length() - 1);
    String id = "" + groupName.charAt(groupName.length() - 1);
    int groupId = Integer.parseInt(id);
    File tmpZip = File.createTempFile("okm", ".zip");

    try {
        System.out.println("before zip");
        String archive = groupName + ".zip";
        response.setHeader("Content-disposition", "attachment; filename=\"" + archive + "\"");
        response.setContentType("application/zip");
        OutputStream out = response.getOutputStream();
        exportZip(groupId, out);
        out.flush();
        out.close();
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "RepositoryException: " + e.getMessage());
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        FileUtils.deleteQuietly(tmpZip);
    }
}

From source file:com.adaptris.core.services.Utf8BomRemoverTest.java

private AdaptrisMessage create(boolean includeBom) throws Exception {
    AdaptrisMessage msg = new DefaultMessageFactory().newMessage();
    OutputStream out = msg.getOutputStream();
    OutputStreamWriter writer = null;
    try {//from  w w w  .j av a  2s  .c o  m
        if (includeBom) {
            out.write(UTF_8_BOM);
            out.flush();
        }
        writer = new OutputStreamWriter(out);
        writer.write(PAYLOAD);
        writer.flush();
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(out);
    }

    return msg;
}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptResultServlet.java

@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    String fileName = request.getParameter("filename");
    String content = request.getParameter("content");

    if (fileName == null || fileName.length() == 0) {
        LOGGER.error("Parameter fileName is required");
        return;/*from w  w  w.  jav  a2s  .c o  m*/
    }

    response.setContentType("application/octet-stream"); // Your content type
    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

    InputStream input = IOUtils.toInputStream(content);

    int read = 0;
    byte[] bytes = new byte[BYTES_DOWNLOAD];
    OutputStream os = response.getOutputStream();

    while ((read = input.read(bytes)) != -1) {
        os.write(bytes, 0, read);
    }
    input.close();
    os.flush();
    os.close();
}

From source file:com.ibm.bluemix.samples.DownloadServlet.java

/**
 * Receives the clean text file or the analysis XML file from the database and returns it to the user
 * //from   w w  w . j  av a  2s. com
 * @param request
 *           contains the type of the requested file (text or XML) and the ID of the file in the database
 * @param response
 *           the file to be downloaded
 *           
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("Download Servlet");

    try {
        // Retrive file information and data
        JSONObject fileInfo = db.getFileInfo(request.getParameter("entry_id"));
        String contentType = null;
        String fileName = null;
        byte[] fileData = null;

        if (request.getParameter("type").equals("1")) {
            // Request for the original file
            fileData = db.getOriginalFile(request.getParameter("entry_id"));
            contentType = "text/plain";
            fileName = (String) fileInfo.get("file_name");
        } else {
            // Request for the output file
            fileData = db.getOutputFile(request.getParameter("entry_id"));
            contentType = "application/xml";
            fileName = (String) fileInfo.get("output_name");
        }

        // Set response headers
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        response.setContentType(contentType);
        response.setStatus(200);

        // Write data to output stream
        OutputStream responseOutput = response.getOutputStream();
        responseOutput.write(fileData, 0, fileData.length);
        responseOutput.flush();
        responseOutput.close();

    } catch (Exception e) {
        request.setAttribute("msg", e.getMessage());
        e.printStackTrace(System.err);
    }
}

From source file:course.cloud.computing.rest.ImageService.java

@GET
@Produces("image/jpeg")
public Response getImage() {

    InputStream imageStream = ImageService.class.getResourceAsStream("/smiley.jpg");
    if (imageStream == null) {
        return Response.serverError().build();
    }//w w w.j a va  2 s . c  om
    final byte[] image;
    try {
        image = IOUtils.toByteArray(imageStream);
    } catch (IOException e) {
        return Response.serverError().build();
    }

    return Response.ok().entity(new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            output.write(image);
            output.flush();
        }
    }).build();
}

From source file:course.cloud.computing.rest.ImageService.java

@GET
@Path("upload")
@Produces("text/html")
public Response uploadPage() {
    InputStream pageStream = ImageService.class.getResourceAsStream("/upload.html");
    if (pageStream == null) {
        return Response.serverError().build();
    }/*from   w  w w .  j a  v a 2s  .c o  m*/
    final byte[] page;
    try {
        page = IOUtils.toByteArray(pageStream);
    } catch (IOException e) {
        return Response.serverError().build();
    }

    return Response.ok().entity(new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {

            output.write(page);
            output.flush();
        }
    }).build();
}

From source file:com.cloudant.sync.datastore.RevisionHistoryHelper.java

/**
 * Add attachment entries to the _attachments dictionary of the revision
 * If the attachment should be inlined, then insert the attachment data as a base64 string
 * If it isn't inlined, set follows=true to show it will be included in the multipart/related
 *//*from w ww .  ja  v a2s  .c  o m*/
private static void addAttachments(List<? extends Attachment> attachments, Map<String, Object> outMap,
        PushAttachmentsInline inlinePreference, int minRevPos) {
    LinkedHashMap<String, Object> attsMap = new LinkedHashMap<String, Object>();
    outMap.put("_attachments", attsMap);
    for (Attachment att : attachments) {
        // we need to cast down to SavedAttachment, which we know is what the AttachmentManager gives us
        SavedAttachment savedAtt = (SavedAttachment) att;
        HashMap<String, Object> theAtt = new HashMap<String, Object>();
        try {
            // add the attachment if it's newer than the minimum revpos
            if (savedAtt.revpos > minRevPos) {
                if (!savedAtt.shouldInline(inlinePreference)) {
                    theAtt.put("follows", true);
                } else {
                    theAtt.put("follows", false);
                    // base64 encode this attachment
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    OutputStream bos = Base64OutputStreamFactory.get(baos);
                    InputStream fis = savedAtt.getInputStream();
                    try {
                        int bufSiz = 1024;
                        byte[] buf = new byte[bufSiz];
                        int n = 0;
                        do {
                            n = fis.read(buf);
                            if (n > 0) {
                                bos.write(buf, 0, n);
                            }
                        } while (n > 0);
                        // out of paranoia, close and flush - docs don't say what you have to
                        // do to

                        // ensure all base64 is written, but close seems to do the right
                        // thing with
                        // the apache codec implementation
                        bos.flush();
                        bos.close();
                        theAtt.put("data", new String(baos.toByteArray(), "UTF-8")); //base64 of data
                    } finally {
                        IOUtils.closeQuietly(fis);
                    }
                }
                theAtt.put("length", savedAtt.length);
                theAtt.put("encoded_length", savedAtt.encodedLength);
                theAtt.put("content_type", savedAtt.type);
                theAtt.put("revpos", savedAtt.revpos);
                if (savedAtt.encoding != Attachment.Encoding.Plain) {
                    theAtt.put("encoding", savedAtt.encoding.toString().toLowerCase());
                }
            } else {
                // if the revpos of the attachment is higher than the minimum, it's a stub
                theAtt.put("stub", true);
            }
        } catch (IOException ioe) {
            // if we can't read the file containing the attachment then skip it
            // (this should only occur if someone tampered with the attachments directory
            // or something went seriously wrong)
            logger.log(Level.WARNING, String.format("Error reading attachment %s", att), ioe);
            continue;
        }
        // now we are done, add the attachment to the map
        attsMap.put(att.name, theAtt);
    }
}

From source file:fyp.project.asyncTask.Http_GetPost.java

public void POST(String url, String val) throws IOException {
    HttpURLConnection urlConnection = null;
    try {//from  ww  w  . ja  v  a2 s  . c  o m
        URL url2 = new URL(url);
        urlConnection = (HttpURLConnection) url2.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setReadTimeout(5000);
        urlConnection.setConnectTimeout(10000);
        urlConnection.setDoOutput(true);
        String data = val;
        OutputStream out = urlConnection.getOutputStream();
        out.write(data.getBytes());
        out.flush();
        out.close();

        int responseCode = urlConnection.getResponseCode();
        if (responseCode == 200) {
            InputStream is = urlConnection.getInputStream();
            String result = convertInputStreamToString(is);
            webpage_output = result;

        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        urlConnection.disconnect();
    }

}

From source file:edu.wisc.my.portlets.dmp.web.CachingXsltView.java

@SuppressWarnings("unchecked")
@Override/*from ww  w  .j  ava  2  s .co  m*/
protected void doTransform(Map model, Source source, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final Map parameters = getParameters(model, request);
    final Serializable cacheKey = this.getCacheKey(model, source, parameters);

    String cachedData;
    synchronized (this.xsltResultCache) {
        cachedData = this.xsltResultCache.get(cacheKey);
        if (cachedData == null) {
            final StringWriter writer = new StringWriter();

            final String encoding = response.getCharacterEncoding();
            this.doTransform(source, parameters, new StreamResult(writer), encoding);

            cachedData = writer.getBuffer().toString();
            this.xsltResultCache.put(cacheKey, cachedData);
        }
    }

    if (useWriter()) {
        final PrintWriter writer = response.getWriter();
        writer.write(cachedData);
        writer.flush();
    } else {
        final OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(cachedData.getBytes());
        outputStream.flush();
    }
}