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:it.cineca.pst.huborcid.web.rest.UploadOrcidEntityFileResource.java

@RequestMapping(value = "/uploadOrcidEntity/downloadExcelResult/{id}", method = RequestMethod.GET)
@Timed/*from  w  w w .j  a va2 s .com*/
public void getExcelResultUploadOrcidEntity(@PathVariable Long id, HttpServletResponse response) {
    try {
        ResultUploadOrcidEntity resultUploadOrcid = resultUploadOrcidEntityRepository.findOne(id);
        byte[] fileBytesResult = resultUploadOrcid.getFileResult();
        response.setContentType("application/data");
        OutputStream outs = response.getOutputStream();
        outs.write(fileBytesResult);
        outs.flush();
        outs.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void copyFolder(AssetManager assetManager, String source, String target) {
    // "Name" is the name of your folder!
    String[] files = null;//from   w w  w .j a v  a  2  s  .  com

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        // Checking file on assets subfolder
        try {
            files = assetManager.list(source);
        } catch (IOException e) {
            Log.e("ERROR", "Failed to get asset file list.", e);
        }
        // Analyzing all file on assets subfolder
        for (String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            // First: checking if there is already a target folder
            File folder = new File(target);
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }
            if (success) {
                // Moving all the files on external SD
                String sourceFile = source + "/" + filename;
                String targetFile = folder.getAbsolutePath() + "/" + filename;
                try {
                    in = assetManager.open(sourceFile);
                    out = new FileOutputStream(targetFile);
                    /*Log.i("WEBVIEW",
                      Environment.getExternalStorageDirectory()
                            + "/yourTargetFolder/" + name + "/"
                            + filename);*/
                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                } catch (IOException e) {
                    try {
                        assetManager.list(sourceFile);
                    } catch (IOException f) {
                        Log.e("ERROR", "Failed to copy asset file: " + filename, f);
                        continue;
                    }

                    copyFolder(assetManager, sourceFile, targetFile);
                }
            } else {
                // Do something else on failure
            }
        }
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
    } else {
        // Something else is wrong. It may be one of many other states, but
        // all we need
        // is to know is we can neither read nor write
    }
}

From source file:com.example.controller.ImageController.java

@RequestMapping(value = "/serve", method = RequestMethod.GET)
public void serve(HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session)
        throws ClassNotFoundException, SQLException, IOException {

    //int id = Integer.parseInt((String) request.getParameter("id"));
    Users us = (Users) session.getAttribute("user");
    String user = us.getUsername();

    byte[] image = MyImageDao.getImage(user).getImage().getBytes();
    ByteArrayInputStream bis = new ByteArrayInputStream(image);
    InputStream input = bis;//from   w  w  w . j a va 2  s  .c om
    OutputStream o = response.getOutputStream();
    response.setContentType("image/jpeg");
    o.write(image);
    o.flush();
    o.close();
    //  model.addAttribute("lenImg", MyImageDao.getImage(1).toString());

}

From source file:gallery.web.controller.pages.types.WallpaperRateType.java

@Override
public UrlBean execute(HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
        throws Exception {
    /** bind command */
    WallpaperRating command = new WallpaperRating();
    ServletRequestDataBinder binder = new ServletRequestDataBinder(command);
    binder.setRequiredFields(REQUIRED_FIELDS);

    binder.bind(request);// w  ww  .  ja  v  a  2s . c o  m
    BindingResult res = binder.getBindingResult();

    int error = '1';
    if (res.hasErrors()) {
        common.CommonAttributes.addErrorMessage("form_errors", request);
    } else {
        //correcting rating
        gallery.web.support.wallpaper.rating.Utils.correctRate(command);

        command.setIp(request.getRemoteAddr());
        if (wallpaperService.getRowCount("id", command.getId_photo()) == 1) {
            Object[] values = new Object[] { command.getId_photo(), command.getIp() };
            if (wallpaperRatingService.getRowCount(RATE_WALLPAPER_WHERE, values) > 0) {
                common.CommonAttributes.addErrorMessage("duplicate_ip", request);
            } else {
                wallpaperRatingService.save(command);
                common.CommonAttributes.addHelpMessage("operation_succeed", request);
                error = '0';
            }
        } else {
            common.CommonAttributes.addErrorMessage("not_exists.wallpaper", request);
        }
    }
    OutputStream os = response.getOutputStream();
    os.write(error);
    os.flush();

    return null;
}

From source file:io.confluent.kafkarest.tools.ProducerPerformance.java

@Override
protected void doIteration(PerformanceStats.Callback cb) {
    HttpURLConnection connection = null;
    try {/*from   w  w  w .j  av  a 2 s  .  c  o  m*/
        URL url = new URL(targetUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT);
        connection.setRequestProperty("Content-Length", requestEntityLength);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        OutputStream os = connection.getOutputStream();
        os.write(requestEntity);
        os.flush();
        os.close();

        int responseStatus = connection.getResponseCode();
        if (responseStatus >= 400) {
            InputStream es = connection.getErrorStream();
            ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class);
            es.close();
            throw new RuntimeException(String.format("Unexpected HTTP error status %d: %s", responseStatus,
                    errorMessage.getMessage()));
        }
        InputStream is = connection.getInputStream();
        while (is.read(buffer) > 0) {
            // Ignore output, just make sure we actually receive it
        }
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    cb.onCompletion(recordsPerIteration, bytesPerIteration);
}

From source file:no.uis.fsws.proxy.ProxySoapHeaderInterceptor.java

private void close(Message outMessage) throws IOException {
    OutputStream os = outMessage.getContent(OutputStream.class);
    os.flush();
    os.close();//from w  w  w.  j  a  va  2 s. c om
}

From source file:com.mmj.app.common.interceptor.ExportFileAnnotationInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    if (handler == null || response == null) {
        return;/*from   www  .  ja  va2 s . com*/
    }

    HandlerMethod hm = (HandlerMethod) handler;

    ExportWordFile exportWordFile = hm.getMethodAnnotation(ExportWordFile.class);
    // word,
    if (exportWordFile != null) {
        String wordName = exportWordFile.value();
        if (StringUtils.isEmpty(wordName)) {
            return;
        }
        String contentDis = "attachment;filename=" + wordName + ".doc";
        response.setHeader("content-disposition", contentDis);
        response.setContentType("application/msword;");
        response.setCharacterEncoding("UTF-8");
    }

    ExportExcelFile exportExcelFile = hm.getMethodAnnotation(ExportExcelFile.class);
    // excel,
    if (exportExcelFile != null) {
        String xlsName = exportExcelFile.value();
        if (StringUtils.isEmpty(xlsName)) {
            return;
        }
        List<?> list = (List<?>) modelAndView.getModel().get("list");
        String[] head = (String[]) modelAndView.getModel().get("head");
        modelAndView.clear();

        HSSFWorkbook workbook = ExcelUtils.defBuildExcel(list, xlsName, head);

        if (workbook == null) {
            try {
                response.getOutputStream().print("Not conform to the requirements of data");
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            return;
        }

        response.setHeader("content-disposition", "attachment;filename=" + xlsName + ".xls");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        //  response
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();
    }
}

From source file:org.restexpress.pipeline.HttpResponseWriterTest.java

@Test
public void testFileAccess() throws ClientProtocolException, IOException {
    RestExpressService restExpress = RestExpressService.newBuilder();
    NoopController controller = new NoopController();
    restExpress.uri(TEST_PATH, controller);
    restExpress.bind(TEST_PORT);/*from ww  w  . ja  v  a 2s  .co  m*/

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(TEST_URL);
    HttpResponse response = (HttpResponse) client.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
    File result = File.createTempFile("restexpress", "result");

    final Closer closer = Closer.create();
    try {
        // get a copy.

        final OutputStream out = closer.register(new FileOutputStream(result));
        response.getEntity().writeTo(out);

        out.flush();
    } catch (final Throwable e) {
        e.printStackTrace();
        if (result != null)
            result.delete();
        result = null;
    } finally {
        closer.close();
    }

    get.releaseConnection();

    final InputStream in = closer.register(new FileInputStream(result));
    ByteStreams.copy(in, System.out);
    closer.close();

}

From source file:com.kelveden.rastajax.servlet.DefaultJsonServlet.java

private void writeRepresentationToResponse(JsonNode representation, HttpServletResponse httpResponse)
        throws IOException {

    httpResponse.setContentType("application/json; charset=utf8");

    final OutputStream outputStream = httpResponse.getOutputStream();

    outputStream.write(representation.toString().getBytes("UTF-8"));
    outputStream.flush();
}

From source file:com.hurence.logisland.serializer.StringSerializer.java

@Override
public void serialize(OutputStream out, Record record) throws RecordSerializationException {

    try {//  w  ww .j a v a2  s .co m
        out.write(record.toString().getBytes());
        out.flush();
    } catch (IOException e) {
        logger.error("error while serializing", e);
    }

}