Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

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

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:org.codelabor.system.file.web.struts.action.FileUploadAction.java

public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServlet().getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;//  w ww . j  av  a2s.c o m
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    response.setContentType(fileDTO.getContentType());

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
    return null;
}

From source file:eu.scape_project.hawarp.webarchive.PayloadContent.java

private byte[] inputStreamToByteArray() {
    try {//from w  ww  . jav a2 s. c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedInputStream buffis = new BufferedInputStream(inputStream);
        BufferedOutputStream buffos = new BufferedOutputStream(baos);
        byte[] tempBuffer = new byte[8192];
        int bytesRead;
        boolean firstByteArray = true;
        while ((bytesRead = buffis.read(tempBuffer)) != -1) {
            buffos.write(tempBuffer, 0, bytesRead);
            if (doPayloadIdentification && firstByteArray && tempBuffer != null && bytesRead > 0) {
                identified = identifyPayloadType(tempBuffer);
            }
            firstByteArray = false;
        }
        //buffis.close();
        buffos.flush();
        buffos.close();

        return baos.toByteArray();
    } catch (IOException ex) {
        LOG.error("Error while trying to read payload content", ex);
        this.error = true;
        return null;
    }
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

protected void write(Socket socket, String data) throws Exception {
    LlpProtocol protocol = connector.getLlpProtocol();
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), connector.getBufferSize());
    protocol.write(bos, data.getBytes(connector.getCharsetEncoding()));
    bos.flush();
}

From source file:gl.iglou.scenegraph.MatModeInterface.java

public void SaveSnapshot(View v) {

    snapshotIndicator.setVisibility(View.VISIBLE);

    new Thread() {
        public void run() {
            try {
                String iconsStoragePath = Environment.getExternalStorageDirectory() + "/SCENEGRAPH/Snapshots/";
                File sdIconStorageDir = new File(iconsStoragePath);
                Time now = new Time();
                now.setToNow();/*  w w w  . j av  a 2  s .  c om*/
                String pic_name = SceneData.GetSceneName() + "_" + now.format("%Y_%m_%d_%H_%M_%S");

                //create storage directories, if they don't exist
                sdIconStorageDir.mkdirs();
                String path = sdIconStorageDir.toString() + "/" + pic_name + ".png";

                try {

                    FileOutputStream fileOutputStream = new FileOutputStream(path);

                    BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

                    //choose another format if PNG doesn't suit you
                    GLView.mBitmap.compress(CompressFormat.PNG, 100, bos);

                    bos.flush();
                    bos.close();

                    snapshotToast.setText(path);
                    snapshotToast.show();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            HideSnapshot();
                        }
                    });

                } catch (FileNotFoundException e) {
                    Log.w("TAG", "Error saving image file: " + e.getMessage());
                } catch (IOException e) {
                    Log.w("TAG", "Error saving image file: " + e.getMessage());
                }
            } catch (Exception e) {
                Log.w("TAG", "Error saving image file: " + e.getMessage());
            }

        }
    }.start();
}

From source file:com.cars.manager.utils.imageChooser.threads.MediaProcessorThread.java

protected void processGooglePhotosMedia(String path, String extension) throws Exception {
    if (Config.DEBUG) {
        Log.i(TAG, "Google photos Started");
        Log.i(TAG, "URI: " + path);
        Log.i(TAG, "Extension: " + extension);
    }//from w  ww  .  ja v  a2 s  . co m
    String retrievedExtension = checkExtension(Uri.parse(path));
    if (retrievedExtension != null && !TextUtils.isEmpty(retrievedExtension)) {
        extension = "." + retrievedExtension;
    }
    try {

        filePath = FileUtils.getDirectory(foldername) + File.separator
                + Calendar.getInstance().getTimeInMillis() + extension;

        ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver()
                .openFileDescriptor(Uri.parse(path), "r");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

        InputStream inputStream = new FileInputStream(fileDescriptor);

        BufferedInputStream reader = new BufferedInputStream(inputStream);

        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] buf = new byte[2048];
        int len;
        while ((len = reader.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        outStream.flush();
        outStream.close();
        inputStream.close();
        process();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    if (Config.DEBUG) {
        Log.i(TAG, "Picasa Done");
    }
}

From source file:com.haru.ui.image.workers.MediaProcessorThread.java

protected void processGooglePhotosMedia(String path, String extension) throws Exception {
    if (/* TODO: DEBUG */ true) {
        Log.i(TAG, "Google photos Started");
        Log.i(TAG, "URI: " + path);
        Log.i(TAG, "Extension: " + extension);
    }//from  w ww . j a  va  2 s  . co  m
    String retrievedExtension = checkExtension(Uri.parse(path));
    if (retrievedExtension != null && !TextUtils.isEmpty(retrievedExtension)) {
        extension = "." + retrievedExtension;
    }
    try {

        filePath = foldername + File.separator + Calendar.getInstance().getTimeInMillis() + extension;

        ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver()
                .openFileDescriptor(Uri.parse(path), "r");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

        InputStream inputStream = new FileInputStream(fileDescriptor);

        BufferedInputStream reader = new BufferedInputStream(inputStream);

        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] buf = new byte[2048];
        int len;
        while ((len = reader.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        outStream.flush();
        outStream.close();
        inputStream.close();
        process();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    if (/* TODO: DEBUG */ true) {
        Log.i(TAG, "Picasa Done");
    }
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public void getCaptcha(String image) {

    try {/*from  w  w  w.ja  va 2s . c om*/
        URL obj = new URL(image);

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.addRequestProperty("Connection", "keep-alive");

        con.getResponseCode();
        tokenCookie = con.getHeaderField("Set-Cookie");

        // creating the input stream from google image
        BufferedInputStream in = new BufferedInputStream(con.getInputStream());
        // my local file writer, output stream
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Captcha.png"));
        // until the end of data, keep saving into file.
        int i;
        while ((i = in.read()) != -1) {
            out.write(i);
        }
        out.flush();
        in.close();
        out.close();
        con.disconnect();
    } catch (MalformedURLException e) {

    } catch (IOException e) {
        // TODO: handle exception
    }

}

From source file:eu.planets_project.pp.plato.action.project.XmlAction.java

public String export() {
    if (selectedPlan != null) {
        // convert project-name to a filename, add date:
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_kkmmss");

        String planName = selectedPlan.getPlanProperties().getName();

        if ((planName == null) || "".equals(planName)) {
            planName = "export";
        }/* www . j a v  a2 s  .c  o m*/
        String normalizedPlanName = FileUtils.makeFilename(planName);
        String filename = normalizedPlanName + "-" + formatter.format(new Date());

        String binarydataTempPath = OS.getTmpPath() + normalizedPlanName + System.currentTimeMillis() + "/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();
        try {
            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                    .getExternalContext().getResponse();
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + ".xml\"");
            // the length of the resulting XML file is unknown due to formatting: response.setContentLength(xml.length());
            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

                projectExport.exportComplete(selectedPlan.getPlanProperties().getId(), out, binarydataTempPath);

                out.flush();
                out.close();

            } catch (IOException e) {
                FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                        "An error occured while generating the export file.");
                log.error("Could not open response-outputstream: ", e);
            }
            FacesContext.getCurrentInstance().responseComplete();
        } finally {
            OS.deleteDirectory(binarydataTempDir);
        }

    }
    System.gc();
    return null;
}

From source file:com.symbian.driver.remoting.master.MasterRemoteImpl.java

/**
 * get package file from client remotely in multiple calls
 * @return/*from w w  w. j  a va2s . co  m*/
 */
private boolean getRemoteFile(TestJob job) {
    //lookup client remote inteface
    String clientName = job.getRegistrationId();
    ClientRemote clientRemote = ClientRegister.getClient(clientName);

    String remoteFileName = job.getSourceFolder() + File.separator + job.getTestPackageName();
    String targetFile = job.getTagetFolder() + File.separator + job.getTestPackageName();

    //read file from remote in multiple calls to avoid OutOfMem if pass large file in memory at once. 
    BufferedOutputStream out = null;
    try {
        File testpackage = new File(targetFile);
        out = new BufferedOutputStream(new FileOutputStream(testpackage));
        byte[] data = null;
        long pos = 0;
        while ((data = clientRemote.readFile(remoteFileName, pos, TRANSFER_LENGTH)) != null) {

            out.write(data, 0, data.length);
            out.flush();
            pos += data.length;
        }
        LOGGER.log(Level.INFO, "received remote file:" + remoteFileName);
        LOGGER.log(Level.INFO, "  saved to :" + targetFile + " file size:" + testpackage.length());
        return true;
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Master: Unable to retrive remote package file " + job.getId() + ".", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
            }
            out = null;
        }
    }

    return false;
}

From source file:com.naryx.tagfusion.cfm.tag.net.ftp.cfFTPData.java

public void downloadFile(File fileLocal, String remoteFile) {
    if (!ftpclient.isConnected()) {
        errorText = "not connected";
        succeeded = false;//from w  w w .  j  av a  2 s . c o m
        return;
    }

    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    try {

        ftpclient.setAutodetectUTF8(true);

        fos = new FileOutputStream(fileLocal);
        bos = new BufferedOutputStream(fos);
        ftpclient.retrieveFile(remoteFile, bos);
        bos.flush();
        bos.close();

        errorCode = ftpclient.getReplyCode();
        succeeded = FTPReply.isPositiveCompletion(errorCode);

    } catch (Exception e) {
        errorCode = ftpclient.getReplyCode();
        errorText = e.getMessage();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
        setStatusData();
    }
}