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:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

protected void write(Socket socket, byte[] data) throws IOException {
    LlpProtocol protocol = connector.getLlpProtocol();
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), connector.getBufferSize());
    protocol.write(bos, data);//  ww  w  .ja v  a2 s.  c o m
    bos.flush();
}

From source file:com.flagleader.builder.BuilderConfig.java

public static void jarExtracting(String paramString1, String paramString2) {
    int i1 = 2048;
    BufferedOutputStream localBufferedOutputStream = null;
    BufferedInputStream localBufferedInputStream = null;
    JarEntry localJarEntry = null;
    JarFile localJarFile = null;//from w w w  .  j a  v  a  2 s  .c  o  m
    Enumeration localEnumeration = null;
    try {
        localJarFile = new JarFile(paramString2);
        localEnumeration = localJarFile.entries();
        while (localEnumeration.hasMoreElements()) {
            localJarEntry = (JarEntry) localEnumeration.nextElement();
            if (localJarEntry.isDirectory()) {
                new File(paramString1 + localJarEntry.getName()).mkdirs();
            } else {
                localBufferedInputStream = new BufferedInputStream(localJarFile.getInputStream(localJarEntry));
                byte[] arrayOfByte = new byte[i1];
                FileOutputStream localFileOutputStream = new FileOutputStream(
                        paramString1 + localJarEntry.getName());
                localBufferedOutputStream = new BufferedOutputStream(localFileOutputStream, i1);
                int i2;
                while ((i2 = localBufferedInputStream.read(arrayOfByte, 0, i1)) != -1)
                    localBufferedOutputStream.write(arrayOfByte, 0, i2);
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
                localBufferedInputStream.close();
            }
        }
    } catch (Exception localException1) {
        localException1.printStackTrace();
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException2) {
            localException2.printStackTrace();
        }
    } finally {
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException3) {
            localException3.printStackTrace();
        }
    }
}

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

protected void write(Socket socket, MessageObject messageObject) throws Exception {
    byte[] data = messageObject.getEncodedData().getBytes(connector.getCharsetEncoding());
    LlpProtocol protocol = connector.getLlpProtocol();
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), connector.getBufferSize());
    protocol.write(bos, data);/*from  w  w w . j  a  va2s. c  o  m*/
    bos.flush();
}

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

public String exportLibrary() {
    LibraryTree lib = null;/*from www .  jav  a 2  s. co m*/
    List<LibraryTree> trees = null;
    trees = em.createQuery("select l from LibraryTree l where (l.name = 'mainlibrary') ").getResultList();
    if ((trees != null) && (trees.size() > 0)) {
        lib = trees.get(0);
    }

    if (lib != null) {
        // convert project-name to a filename, add date:
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_kkmmss");
        String filename = "RequirementsLibrary-" + formatter.format(new Date());

        String binarydataTempPath = OS.getTmpPath() + "RequirementsLibrary-" + System.currentTimeMillis() + "/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();

        LibraryExport exp = new LibraryExport();
        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());

                exp.exportToStream(lib, out);

                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);
        }

    } else {
        FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "No Library found, create one first.");
    }
    System.gc();
    return null;
}

From source file:eu.planets_project.pp.plato.application.AdminAction.java

/**
 * Renders the given exported XML-Document as HTTP response
 *//*from   w  w  w  . j  a  va 2  s. com*/
private String returnXMLExport(Document doc) {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_kkmmss");
    String timestamp = format.format(new Date(System.currentTimeMillis()));

    String filename = "export_" + timestamp + ".xml";
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + "\"");
    //response.setContentLength(xml.length());
    try {
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        XMLWriter writer = new XMLWriter(out, ProjectExporter.prettyFormat);
        writer.write(doc);
        writer.flush();
        writer.close();
        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();
    return null;
}

From source file:org.codehaus.mojo.jsimport.JsFileArtifactHandler.java

private List<File> expandWwwZipIntoTargetFolder(Artifact artifact, File wwwZipFile, File targetFolder,
        File workFolder) throws IOException {
    List<File> jsFiles = new ArrayList<File>();

    // FIXME: Need to consider scope here i.e. don't create a compile www-zip file for a test run.
    expansionFolder = new File(workFolder, "www-zip" + File.separator + wwwZipFile.getName());

    // Don't expand if it is already expanded.
    if (wwwZipFile.lastModified() > expansionFolder.lastModified()) {
        String gavPath = artifact.getGroupId().replace('.', File.separatorChar) + File.separator
                + artifact.getArtifactId() + File.separator + artifact.getVersion();
        File jsExpansionFolder = new File(expansionFolder, gavPath);

        FileInputStream fis = new FileInputStream(wwwZipFile);
        try {/*from   ww w . j  a  va  2 s .co m*/
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
            ZipEntry entry;
            boolean firstEntryProcessed = false;
            int rootFolderPrefixPosn = 0;
            while ((entry = zis.getNextEntry()) != null) {
                // Any non-js files are simply copied into the target folder. js files are copied to a temporary
                // folder as something else needs to put them into the target folder (there may be processing a js
                // file along the way). However we ignore minified files when inflating as by convention, we don't
                // want them as part of the project - projects can minify later.

                String entryName = entry.getName().substring(rootFolderPrefixPosn);
                File entryFile = null;
                if (!entryName.endsWith("js")) {
                    if (!entry.isDirectory()) {
                        entryFile = new File(targetFolder, entryName);
                    } else if (!firstEntryProcessed) {
                        // Its a directory and it is the first thing in the zip file. We don't want to bother with
                        // this directory when creating files as we're more interested in merging it into the
                        // existing target folder.
                        rootFolderPrefixPosn = entryName.length();
                    }
                } else if (!entryName.endsWith("-min.js")) {
                    entryFile = new File(jsExpansionFolder, entryName);
                    jsFiles.add(entryFile);
                }

                // If we have something interesting to inflate.
                if (entryFile != null) {
                    entryFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(entryFile);
                    BufferedOutputStream dest = null;
                    try {
                        int count;
                        final int bufferSize = 2048;
                        byte data[] = new byte[bufferSize];
                        dest = new BufferedOutputStream(fos, bufferSize);
                        while ((count = zis.read(data, 0, bufferSize)) != -1) {
                            dest.write(data, 0, count);
                        }
                        dest.flush();
                    } finally {
                        dest.close();
                    }
                }

                firstEntryProcessed = true;
            }
        } finally {
            fis.close();
        }

        // Override the directory's mod time as that will equal the time it was compressed initially. We're not
        // interested in that - we're interested to learn whether the source zip file is newer that the directory we
        // expand into.
        expansionFolder.setLastModified(wwwZipFile.lastModified());
    } else {
        // Nothing changed. Just return a list of files that were previously expanded.
        Collection<File> existingFiles = FileUtils.listFiles(expansionFolder, new String[] { "js" }, true);
        for (File file : existingFiles) {
            if (!file.getName().endsWith("-min.js")) {
                jsFiles.add(file);
            }
        }
    }

    return jsFiles;
}

From source file:org.apache.wookie.w3c.util.WidgetPackageUtils.java

/**
 * uses apache commons compress to unpack all the zip entries into a target folder
 * partly adapted from the examples on the apache commons compress site, and an
 * example of generic Zip unpacking. Note this iterates over the ZipArchiveEntry enumeration rather
 * than use the more typical ZipInputStream parsing model, as according to the doco it will
 * more reliably read the entries correctly. More info here: http://commons.apache.org/compress/zip.html
 * @param zipfile the Zip File to unpack
 * @param targetFolder the folder into which to unpack the Zip file
 * @throws IOException//from   w w w. j a v a  2 s  .c o  m
 */
@SuppressWarnings("unchecked")
public static void unpackZip(ZipFile zipfile, File targetFolder) throws IOException {
    targetFolder.mkdirs();
    BufferedOutputStream out = null;
    InputStream in = null;
    ZipArchiveEntry zipEntry;

    Enumeration entries = zipfile.getEntries();
    try {
        while (entries.hasMoreElements()) {
            zipEntry = (ZipArchiveEntry) entries.nextElement();
            // Don't add directories - use mkdirs instead
            if (!zipEntry.isDirectory()) {
                File outFile = new File(targetFolder, zipEntry.getName());

                // Ensure that the parent Folder exists
                if (!outFile.getParentFile().exists()) {
                    outFile.getParentFile().mkdirs();
                }
                // Read the entry
                in = new BufferedInputStream(zipfile.getInputStream(zipEntry));
                out = new BufferedOutputStream(new FileOutputStream(outFile));
                IOUtils.copy(in, out);
                // Restore time stamp
                outFile.setLastModified(zipEntry.getTime());

                // Close File
                out.close();
                // Close Stream
                in.close();
            }
        }

    }
    // We'll catch this exception to close the file otherwise it remains locked
    catch (IOException ex) {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        // And throw it again
        throw ex;
    }
}

From source file:dk.netarkivet.viewerproxy.ARCArchiveAccess.java

/**
 * Read an entire page body into some stream.
 *
 * @param content The stream to read the page from. Not closed afterwards.
 * @param out The stream to write the results to. Not closed afterwards.
 * @throws IOFailure If the underlying reads or writes fail
 */// w w w.  j a v  a 2s  .  c o m
private void readPage(InputStream content, OutputStream out) {
    BufferedInputStream page = new BufferedInputStream(content);
    BufferedOutputStream responseOut = new BufferedOutputStream(out);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[Constants.IO_BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = page.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
            responseOut.write(buffer, 0, bytesRead);
        }
        responseOut.flush();
        log.debug("pagecontents: ", new String(baos.toByteArray(), "UTF-8"));
    } catch (IOException e) {
        throw new IOFailure("Could not read or write data", e);
    }
}

From source file:info.guardianproject.iocipher.camera.VideoCameraActivity.java

@Override
public void onPictureTaken(final byte[] data, Camera camera) {
    File fileSecurePicture;/*from w  ww.j a  v a  2  s  . c o m*/
    try {

        overlayView.setBackgroundResource(R.color.flash);

        long mTime = System.currentTimeMillis();
        fileSecurePicture = new File(mFileBasePath, "secure_image_" + mTime + ".jpg");

        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileSecurePicture));
        out.write(data);
        out.flush();
        out.close();

        mResultList.add(fileSecurePicture.getAbsolutePath());

        Intent intent = new Intent("new-media");
        // You can also include some extra data.
        intent.putExtra("media", fileSecurePicture.getAbsolutePath());
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

        Intent intentResult = new Intent().putExtra(MediaStore.EXTRA_OUTPUT,
                mResultList.toArray(new String[mResultList.size()]));
        setResult(Activity.RESULT_OK, intentResult);

        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                overlayView.setBackgroundColor(Color.TRANSPARENT);
                resumePreview();
            }
        }, 100);

    } catch (Exception e) {
        e.printStackTrace();
        setResult(Activity.RESULT_CANCELED);

    }

}

From source file:com.life.wuhan.util.ImageDownloader.java

public void writeFile(String url, Bitmap bitmap) {

    String hashedUrl = getMd5(url);

    FileOutputStream fos;//ww  w  .  jav  a 2 s. com

    try {
        fos = mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
        return;
    }

    final BufferedOutputStream bos = new BufferedOutputStream(fos, 16384);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
    try {
        bos.flush();
        bos.close();
        fos.close();
    } catch (IOException e) {
    }
}