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:net.padlocksoftware.padlock.KeyManager.java

/**
 * Export the supplied Keypair to an output Stream.
 *
 * @param pair The KeyPair to export.  KeyPairs should only be pairs
 * created with the createKeyPair(int) method.
 *
 * @param stream The stream to write the KeyPair to.  Key streams contain both the
 * public and private keys and should be secured.
 *
 * @throws java.io.IOException For any Stream IO related exceptions
 * @throws java.lang.NullPointerException If either parameter is null
 * @since 2.0//from   w ww  . j av  a 2 s.  c o  m
 */
public static void exportKeyPair(KeyPair pair, OutputStream stream) throws IOException {
    if (pair == null) {
        throw new IllegalArgumentException("KeyPair may not be null");
    }

    if (stream == null) {
        throw new IllegalArgumentException("Stream may not be null");
    }

    //
    // Turn the keypair into properties
    //
    Properties p = new Properties();

    String pri = new String(Hex.encodeHex(pair.getPrivate().getEncoded()));
    String pub = new String(Hex.encodeHex((pair.getPublic().getEncoded())));
    p.setProperty("public", pub);
    p.setProperty("private", pri);

    p.store(stream, null);
    stream.flush();
    stream.close();

}

From source file:com.inmobi.conduit.distcp.tools.TestDistCp.java

private static void touchFile(String path) throws Exception {
    FileSystem fs;//from  w  w w  .  j a v a2 s  .c  o  m
    DataOutputStream outputStream = null;
    GzipCodec gzipCodec = ReflectionUtils.newInstance(GzipCodec.class, getConfigurationForCluster());
    Compressor gzipCompressor = CodecPool.getCompressor(gzipCodec);
    OutputStream compressedOut = null;
    try {
        fs = cluster.getFileSystem();
        final Path qualifiedPath = new Path(path).makeQualified(fs);
        final long blockSize = fs.getDefaultBlockSize() * 2;
        outputStream = fs.create(qualifiedPath, true, 0, (short) (fs.getDefaultReplication() * 2), blockSize);
        compressedOut = gzipCodec.createOutputStream(outputStream, gzipCompressor);
        compressedOut.write(new byte[FILE_SIZE]);
        compressedOut.write("\n".getBytes());
        compressedOut.flush();
        //outputStream.write(new byte[FILE_SIZE]);
        pathList.add(qualifiedPath);
    } finally {
        compressedOut.close();
        IOUtils.cleanup(null, outputStream);
        CodecPool.returnCompressor(gzipCompressor);
    }
}

From source file:Main.java

private static boolean CopyFile(Context context, String pathName) {

    boolean isCopyCompleted = false;

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {//  ww w  . j a v a2 s. c om
        inputStream = context.getResources().getAssets().open(pathName);
        File outFile = new File(context.getCacheDir(), pathName);
        if (!outFile.exists()) {
            outFile.createNewFile();
        }

        outputStream = new FileOutputStream(outFile);

        byte[] buffer = new byte[4096];
        int bytesRead;
        // read from is to buffer
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
            Log.v("", "data..." + bytesRead);
        }

        isCopyCompleted = true;
        inputStream.close();
        // flush OutputStream to write any buffered data to file
        outputStream.flush();
        outputStream.close();

    } catch (IOException e) {
        isCopyCompleted = false;
        e.printStackTrace();
    }
    return isCopyCompleted;

}

From source file:com.hernandez.rey.crypto.TripleDES.java

/**
 * Use the specified TripleDES key to decrypt bytes ready from the input stream and write them to the output stream.
 * This method uses uses Cipher directly to show how it can be done without CipherInputStream and CipherOutputStream.
 * //ww w. j ava  2  s  . c  o m
 * @param key the key for decryption
 * @param in
 * @param out
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws IOException
 * @throws IllegalBlockSizeException
 * @throws NoSuchPaddingException
 * @throws BadPaddingException
 */
public static void decrypt(final SecretKey key, final InputStream in, final OutputStream out)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, IllegalBlockSizeException,
        NoSuchPaddingException, BadPaddingException {
    // Create and initialize the decryption engine
    final Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.DECRYPT_MODE, key);

    // Read bytes, decrypt, and write them out.
    final byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(cipher.update(buffer, 0, bytesRead));
    }

    // Write out the final bunch of decrypted bytes
    out.write(cipher.doFinal());
    out.flush();
}

From source file:Files.java

/**
 * Copy a remote/local URL to a local file
 * /*from  w w w  . j  av a  2s .  com*/
 * @param src the remote or local URL
 * @param dest the local file
 * @throws IOException upon error
 */
public static void copy(URL src, File dest) throws IOException {
    System.out.println("Copying " + src + " -> " + dest);

    // Validate that the dest parent directory structure exists
    File dir = dest.getParentFile();
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new IOException("mkdirs failed for: " + dir.getAbsolutePath());
        }
    }
    // Remove any existing dest content
    if (dest.exists()) {
        if (!Files.delete(dest)) {
            throw new IOException("delete of previous content failed for: " + dest.getAbsolutePath());
        }
    }
    // Treat local and remote URLs the same
    // prepare streams, do the copy and flush
    InputStream in = new BufferedInputStream(src.openStream());
    OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
    Streams.copy(in, out);
    out.flush();
    out.close();
    in.close();
}

From source file:org.wso2.carbon.core.transports.util.XsdUtil.java

public static void printXsd(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configCtx, String serviceName, AxisService axisService) throws IOException {
    if (GhostDeployerUtils.isGhostService(axisService)) {
        // if the existing service is a ghost service, deploy the actual one
        axisService = GhostDeployerUtils.deployActualService(configCtx.getAxisConfiguration(), axisService);
    }/*w w w  .  j a va2  s.  com*/
    if (!RequestProcessorUtil.canExposeServiceMetadata(axisService)) {
        response.setError(HttpStatus.SC_FORBIDDEN,
                "Access to service metadata for service: " + serviceName + " has been forbidden");
        return;
    }
    OutputStream outputStream = response.getOutputStream();
    String contextRoot = request.getContextPath();
    if (axisService == null) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
        response.setError(HttpStatus.SC_NOT_FOUND);
        outputStream.write(
                ("<h4>Service " + serviceName + " is not found. Cannot display Schema.</h4>").getBytes());
        outputStream.flush();
        return;
    }

    if (!axisService.isActive()) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
        outputStream
                .write(("<h4>Service " + serviceName + " is inactive. Cannot display Schema.</h4>").getBytes());
        outputStream.flush();
        return;
    }

    //cater for named xsds - check for the xsd name
    String uri = request.getQueryString();
    if (request.getQueryString().endsWith(".xsd")) {
        String schemaName = uri.substring(uri.lastIndexOf('=') + 1);

        Map services = configCtx.getAxisConfiguration().getServices();
        AxisService service = (AxisService) services.get(serviceName);
        if (service != null) {
            //run the population logic just to be sure
            service.populateSchemaMappings();
            //write out the correct schema
            Map schemaTable = service.getSchemaMappingTable();
            XmlSchema schema = (XmlSchema) schemaTable.get(schemaName);

            if (schema == null) {
                int slashIndex = schemaName.lastIndexOf('/');
                int dotIndex = schemaName.lastIndexOf('.');
                if (slashIndex > 0) {
                    String schemaKey = schemaName.substring(slashIndex + 1, dotIndex);
                    schema = (XmlSchema) schemaTable.get(schemaKey);
                }
            }

            if (schema == null) {
                int dotIndex = schemaName.indexOf('.');
                if (dotIndex > 0) {
                    String schemaKey = schemaName.substring(0, dotIndex);
                    schema = (XmlSchema) schemaTable.get(schemaKey);
                }
            }
            //schema found - write it to the stream
            if (schema != null) {
                response.setStatus(HttpStatus.SC_OK);
                response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                schema.write(response.getOutputStream());
                return;
            } else {
                InputStream instream = service.getClassLoader()
                        .getResourceAsStream(DeploymentConstants.META_INF + "/" + schemaName);

                if (instream != null) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                    OutputStream outstream = response.getOutputStream();
                    boolean checkLength = true;
                    int length = Integer.MAX_VALUE;
                    int nextValue = instream.read();
                    if (checkLength) {
                        length--;
                    }
                    while (-1 != nextValue && length >= 0) {
                        outstream.write(nextValue);
                        nextValue = instream.read();
                        if (checkLength) {
                            length--;
                        }
                    }
                    outstream.flush();
                    return;
                } else {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int ret = service.printXSD(baos, schemaName);
                    if (ret > 0) {
                        baos.flush();
                        instream = new ByteArrayInputStream(baos.toByteArray());
                        response.setStatus(HttpStatus.SC_OK);
                        response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                        OutputStream outstream = response.getOutputStream();
                        boolean checkLength = true;
                        int length = Integer.MAX_VALUE;
                        int nextValue = instream.read();
                        if (checkLength) {
                            length--;
                        }
                        while (-1 != nextValue && length >= 0) {
                            outstream.write(nextValue);
                            nextValue = instream.read();
                            if (checkLength) {
                                length--;
                            }
                        }
                        outstream.flush();
                        return;
                    }
                }
            }
        }
    }

    axisService.populateSchemaMappings();
    Map schemaMappingtable = axisService.getSchemaMappingTable();
    String xsds = request.getParameter("xsd");
    if (xsds != null && xsds.trim().length() != 0) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
        XmlSchema schema = (XmlSchema) schemaMappingtable.get(xsds);
        if (schema == null) {
            int dotIndex = xsds.indexOf('.');
            if (dotIndex > 0) {
                String schemaKey = xsds.substring(0, dotIndex);
                schema = (XmlSchema) schemaMappingtable.get(schemaKey);
            }
        }
        if (schema != null) {
            //schema is there - pump it outs
            schema.write(new OutputStreamWriter(outputStream, "UTF8"));
            outputStream.flush();
            outputStream.close();
        } else if (xsds.endsWith(".xsd") && xsds.indexOf("..") == -1) {
            InputStream in = axisService.getClassLoader()
                    .getResourceAsStream(DeploymentConstants.META_INF + "/" + xsds);
            if (in != null) {
                outputStream.write(IOUtils.getStreamAsByteArray(in));
                outputStream.flush();
                outputStream.close();
            } else {
                response.setError(HttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            String msg = "Invalid schema " + xsds + " requested";
            throw new IOException(msg);
        }
        return;
    }

    ArrayList schemas = axisService.getSchema();
    if (schemas.size() == 1) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
        // Write to the output stream
        processSchema((XmlSchema) schemas.get(0), outputStream, contextRoot, request);

    } else {
        String idParam = request.getParameter("id");
        if (idParam != null) {
            XmlSchema schema = axisService.getSchema(Integer.parseInt(idParam));
            if (schema != null) {
                response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                processSchema(schema, outputStream, contextRoot, request);
            } else {
                response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                outputStream.write("<h4>Schema not found!</h4>".getBytes());
            }
        } else {
            /*String ipAddress = "http://" + NetworkUtils.getLocalHostname() + ":" +
                ServerManager.getInstance().getHttpPort();
            String version =
                ServerConfiguration.getInstance().getFirstProperty("Version");
            outputStream.write(("<html><head>" +
                "<title>WSO2 Web Services Application Server v" +
                version +
                "Management Console" +
                " - " +
                axisService.getName() +
                " Service Schema</title>" +
                "</head>" +
                "<body>" +
                "<b>Schemas for " +
                axisService.getName() +
                " service</b><br/><br/>").getBytes());
            if (schemas.size() != 0) {
            for (int i = 0; i < schemas.size(); i++) {
                String st = "<a href=\"" + ipAddress +
                        RequestProcessorUtil.getServiceContextPath(configCtx) + "/" +
                        axisService.getName() + "?xsd&id=" + i +
                        "&" + ServerConstants.HTTPConstants.ANNOTATION + "=true" + "\">Schema " + i +
                        "</a><br/>";
                outputStream.write(st.getBytes());
            }
            } else {
            outputStream.write("<p>No schemas found</p>".getBytes());
            }
            outputStream.write("</body></html>".getBytes());*/
        }
    }
}

From source file:com.serotonin.bacnet4j.util.sero.StreamUtils.java

public static void transfer(InputStream in, OutputStream out, long limit) throws IOException {
    byte[] buf = new byte[1024];
    int readcount;
    long total = 0;
    while ((readcount = in.read(buf)) != -1) {
        if (limit != -1) {
            if (total + readcount > limit)
                readcount = (int) (limit - total);
        }//from   w  w  w . j  a v a2 s.c om

        if (readcount > 0)
            out.write(buf, 0, readcount);

        total += readcount;
        if (limit != -1 && total >= limit)
            break;
    }
    out.flush();
}

From source file:org.frontcache.core.FCUtils.java

public static void writeResponse(InputStream zin, OutputStream out) throws Exception {
    byte[] bytes = new byte[1024];
    int bytesRead = -1;
    while ((bytesRead = zin.read(bytes)) != -1) {
        try {/*from  w ww .  jav  a 2s  .c  o m*/
            out.write(bytes, 0, bytesRead);
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        // doubles buffer size if previous read filled it
        if (bytesRead == bytes.length) {
            bytes = new byte[bytes.length * 2];
        }
    }
}

From source file:big.zip.java

/**
 * /*from   ww  w.  j a  va2 s . c  o  m*/
 * @param fileToCompress    The file that we want to compress
 * @param fileToOutput      The zip file containing the compressed file
 * @return  True if the file was compressed and created, false when something
 * went wrong
 */
public static boolean compress(final File fileToCompress, final File fileToOutput) {
    if (fileToOutput.exists()) {
        // do the first run to delete this file
        fileToOutput.delete();
        // did this worked?
        if (fileToOutput.exists()) {
            // something went wrong, the file is still here
            System.out.println("ZIP59 - Failed to delete output file: " + fileToOutput.getAbsolutePath());
            return false;
        }
    }
    // does our file to compress exist?
    if (fileToCompress.exists() == false) {
        // we have a problem here
        System.out.println("ZIP66 - Didn't found the file to compress: " + fileToCompress.getAbsolutePath());
        return false;
    }
    // all checks are done, now it is time to do the compressing
    try {
        final OutputStream outputStream = new FileOutputStream(fileToOutput);
        ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream("zip", outputStream);
        archive.putArchiveEntry(new ZipArchiveEntry(fileToCompress.getName()));
        // create the input file stream and copy it over to the archive
        FileInputStream inputStream = new FileInputStream(fileToCompress);
        IOUtils.copy(inputStream, archive);
        // close the archive
        archive.closeArchiveEntry();
        archive.flush();
        archive.close();
        // now close the input file stream
        inputStream.close();
        // and close the output file stream too
        outputStream.flush();
        outputStream.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ArchiveException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:cn.mdict.utils.IOUtil.java

public static boolean streamDuplicate(InputStream is, OutputStream os, int bufferSize,
        StatusReport statusReport) {/* w ww  .j a  v  a 2 s  .co  m*/
    is = new BufferedInputStream(is);
    os = new BufferedOutputStream(os);
    byte[] buffer = new byte[bufferSize];
    int length;
    int count = 0;
    boolean result = false;
    try {
        while (((statusReport == null) || !statusReport.isCanceled()) && (length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
            count += length;
            if (statusReport != null)
                statusReport.onProgressUpdate(count);
        }
        os.flush();
        result = true;
        if (statusReport != null) {
            if (statusReport.isCanceled())
                statusReport.onInterrupted();
            else
                statusReport.onComplete();
        }
    } catch (Exception e) {
        if (statusReport != null)
            statusReport.onError(e);
        else
            e.printStackTrace();
    } finally {
        forceClose(is);
        forceClose(os);
    }
    return result;
}