Example usage for java.nio.channels WritableByteChannel close

List of usage examples for java.nio.channels WritableByteChannel close

Introduction

In this page you can find the example usage for java.nio.channels WritableByteChannel close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this channel.

Usage

From source file:eu.ensure.aging.AgingSimulator.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file");
    options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file");
    options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)");

    Properties properties = new Properties();
    CommandLineParser parser = new PosixParser();
    try {/*from  ww  w.  j a  va 2 s.  c om*/
        CommandLine line = parser.parse(options, args);

        //
        if (line.hasOption("flip-bit-in-name")) {
            properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name"));
        } else {
            // On by default (if not explicitly de-activated above)
            properties.put("flip-bit-in-name", "true");
        }

        //
        if (line.hasOption("flip-bit-in-uname")) {
            properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname"));
        } else {
            properties.put("flip-bit-in-uname", "false");
        }

        //
        if (line.hasOption("update-checksum")) {
            properties.put("update-checksum", line.getOptionValue("update-checksum"));
        } else {
            properties.put("update-checksum", "false");
        }

        String[] fileArgs = line.getArgs();

        if (fileArgs.length < 1) {
            printHelp(options, System.err);
            System.exit(1);
        }

        String srcPath = fileArgs[0];

        File srcAIP = new File(srcPath);
        if (!srcAIP.exists()) {
            String info = "The source path does not locate a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (srcAIP.isDirectory()) {
            String info = "The source path locates a directory, not a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (!srcAIP.canRead()) {
            String info = "Cannot read source file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        boolean doReplace = false;
        File destAIP = null;

        if (fileArgs.length > 1) {
            String destPath = fileArgs[1];
            destAIP = new File(destPath);

            if (destAIP.exists()) {
                String info = "The destination path locates an existing file: " + destPath;
                System.err.println(info);
                System.exit(1);
            }
        } else {
            doReplace = true;
            try {
                destAIP = File.createTempFile("tmp-aged-aip-", ".tar");
            } catch (IOException ioe) {
                String info = "Failed to create temporary file: ";
                info += ioe.getMessage();
                System.err.println(info);
                System.exit(1);
            }
        }

        String info = "Age simulation\n";
        info += "  Reading from " + srcAIP.getName() + "\n";
        if (doReplace) {
            info += "  and replacing it's content";
        } else {
            info += "  Writing to " + destAIP.getName();
        }
        System.out.println(info);

        //
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcAIP));
            os = new BufferedOutputStream(new FileOutputStream(destAIP));

            simulateAging(srcAIP.getName(), is, os, properties);

        } catch (FileNotFoundException fnfe) {
            info = "Could not locate file: " + fnfe.getMessage();
            System.err.println(info);
        } finally {
            try {
                if (null != os)
                    os.close();
                if (null != is)
                    is.close();
            } catch (IOException ignore) {
            }
        }

        //
        if (doReplace) {
            File renamedOriginal = new File(srcAIP.getName() + "-backup");
            srcAIP.renameTo(renamedOriginal);

            ReadableByteChannel rbc = null;
            WritableByteChannel wbc = null;
            try {
                rbc = Channels.newChannel(new FileInputStream(destAIP));
                wbc = Channels.newChannel(new FileOutputStream(srcAIP));
                FileIO.fastChannelCopy(rbc, wbc);
            } catch (FileNotFoundException fnfe) {
                info = "Could not locate temporary output file: " + fnfe.getMessage();
                System.err.println(info);
            } catch (IOException ioe) {
                info = "Could not copy temporary output file over original AIP: " + ioe.getMessage();
                System.err.println(info);
            } finally {
                try {
                    if (null != wbc)
                        wbc.close();
                    if (null != rbc)
                        rbc.close();

                    destAIP.delete();
                } catch (IOException ignore) {
                }
            }
        }
    } catch (ParseException pe) {
        String info = "Failed to parse command line: " + pe.getMessage();
        System.err.println(info);
        printHelp(options, System.err);
        System.exit(1);
    }
}

From source file:com.intuit.tank.service.impl.v1.report.FileReader.java

/**
 * Gets a StreamingOutput from the passedin file from start to end or from beginning to end if start is greater than
 * end. if a negative number is passed, it will get the last n lines of the file. If 0 is passed it will return the
 * entire file./*w w  w .j a v a  2 s  . com*/
 * 
 * @param total
 * 
 * @return a StreamingOutput
 */
public static StreamingOutput getFileStreamingOutput(final File f, long total, String start) {

    long l = 0;
    if (start != null) {
        try {
            l = Long.parseLong(start);
            // num lines to get from end
            if (l < 0) {
                l = getStartChar(f, Math.abs(l), total);
            }
        } catch (Exception e) {
            LOG.error("Error parsing start " + start + ": " + e);
        }
    }
    final long to = l > total ? 0 : total;
    final long from = l;

    StreamingOutput streamer = new StreamingOutput() {
        @SuppressWarnings("resource")
        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {

            final FileChannel inputChannel = new FileInputStream(f).getChannel();
            final WritableByteChannel outputChannel = Channels.newChannel(output);
            try {
                inputChannel.transferTo(from, to, outputChannel);
            } finally {
                // closing the channels
                inputChannel.close();
                outputChannel.close();
            }
        }
    };
    LOG.debug("returning data from " + from + " - " + to + " of total " + total);
    return streamer;
}

From source file:IOUtilities.java

/**
 * Copy ALL available data from one stream into another
 * @param in//from w w  w.  j a  va 2  s.  c  om
 * @param out
 * @throws IOException
 */
public static void copy(InputStream in, OutputStream out) throws IOException {
    ReadableByteChannel source = Channels.newChannel(in);
    WritableByteChannel target = Channels.newChannel(out);

    ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
    while (source.read(buffer) != -1) {
        buffer.flip(); // Prepare the buffer to be drained
        while (buffer.hasRemaining()) {
            target.write(buffer);
        }
        buffer.clear(); // Empty buffer to get ready for filling
    }

    source.close();
    target.close();

}

From source file:org.wso2.carbon.identity.common.testng.MockInitialContextFactory.java

/**
 * Copies a resource inside a jar to external file within a directory.
 * Then returns the created file./*from www  .  ja v  a  2  s.  c o  m*/
 *
 * @param relativeFilePath
 * @param clazz
 * @return
 * @throws TestCreationException
 */
private static File copyTempFile(String relativeFilePath, Class clazz) throws TestCreationException {

    URL url = clazz.getClassLoader().getResource(relativeFilePath);
    if (url == null) {
        throw new TestCreationException("Could not find a resource on the classpath : " + relativeFilePath);
    }
    InputStream inputStream;
    try {
        inputStream = url.openStream();
        ReadableByteChannel inputChannel = Channels.newChannel(inputStream);
        File tempFile = File.createTempFile("tmp_", "_registry.sql");
        FileOutputStream fos = new FileOutputStream(tempFile);
        WritableByteChannel targetChannel = fos.getChannel();
        //Transfer data from input channel to output channel
        ((FileChannel) targetChannel).transferFrom(inputChannel, 0, Short.MAX_VALUE);
        inputStream.close();
        targetChannel.close();
        fos.close();
        return tempFile;
    } catch (IOException e) {
        throw new TestCreationException(
                "Could not copy the file content to temp file from : " + relativeFilePath);
    }
}

From source file:byps.BWire.java

/**
 * Writes a ByteBuffer to an OutputStream.
 * Closes the OutputStream.//www  .j  ava2 s .  com
 * @param buf
 * @param os
 * @throws IOException
 */
public static void bufferToStream(ByteBuffer buf, boolean gzip, OutputStream os) throws IOException {
    if (gzip) {
        os = new GZIPOutputStream(os);
    }

    WritableByteChannel wch = null;
    try {
        wch = Channels.newChannel(os);
        wch.write(buf);
    } finally {
        if (wch != null)
            wch.close();
    }
}

From source file:com.thinkberg.webdav.Util.java

public static long copyStream(final InputStream is, final OutputStream os) throws IOException {
    ReadableByteChannel rbc = Channels.newChannel(is);
    WritableByteChannel wbc = Channels.newChannel(os);

    int bytesWritten = 0;
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (rbc.read(buffer) != -1) {
        buffer.flip();//from w  w w  .j  a va2s . c o m
        bytesWritten += wbc.write(buffer);
        buffer.compact();
    }
    buffer.flip();
    while (buffer.hasRemaining()) {
        bytesWritten += wbc.write(buffer);
    }

    rbc.close();
    wbc.close();

    return bytesWritten;
}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;/* w  w  w  . j a va2 s  . c  o  m*/
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:com.pavlospt.rxfile.RxFile.java

private static File fileFromUri(Context context, Uri data) throws Exception {
    DocumentFile file = DocumentFile.fromSingleUri(context, data);
    String fileType = file.getType();
    String fileName = file.getName();
    File fileCreated;//from  w  w  w.  j  a va 2 s  .c o  m
    ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
            Constants.READ_MODE);
    InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
    logDebug("External cache dir:" + context.getExternalCacheDir());
    String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName;
    String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1);
    String mimeType = getMimeType(fileName);

    logDebug("From Google Drive guessed type: " + getMimeType(fileName));

    logDebug("Extension: " + fileExtension);

    if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) {
        filePath += "." + Constants.PDF_EXTENSION;
    }

    if (!createFile(filePath)) {
        return new File(filePath);
    }

    ReadableByteChannel from = Channels.newChannel(inputStream);
    WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath));
    fastChannelCopy(from, to);
    from.close();
    to.close();
    fileCreated = new File(filePath);
    logDebug("Path for made file: " + fileCreated.getAbsolutePath());
    return fileCreated;
}

From source file:com.xxxifan.devbox.library.rxfile.RxFile.java

private static File fileFromUri(Context context, Uri data) throws Exception {
    DocumentFile file = DocumentFile.fromSingleUri(context, data);
    String fileType = file.getType();
    String fileName = file.getName();
    File fileCreated;// w ww.  ja v  a2 s. c  o  m
    ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
            Constants.READ_MODE);
    InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
    Log.e(TAG, "External cache dir:" + context.getExternalCacheDir());
    String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName;
    String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1);
    String mimeType = getMimeType(fileName);

    Log.e(TAG, "From Drive guessed type: " + getMimeType(fileName));

    Log.e(TAG, "Extension: " + fileExtension);

    if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) {
        filePath += "." + Constants.PDF_EXTENSION;
    }

    if (!createFile(filePath)) {
        return new File(filePath);
    }

    ReadableByteChannel from = Channels.newChannel(inputStream);
    WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath));
    fastChannelCopy(from, to);
    from.close();
    to.close();
    fileCreated = new File(filePath);
    Log.e(TAG, "Path for made file: " + fileCreated.getAbsolutePath());
    return fileCreated;
}

From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java

/**
 * ??//  w w  w .j  av  a2  s.c  o m
 *
 * @param is
 * @return
 * @throws IOException
 */
public static String readStreamAsStr(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel dest = Channels.newChannel(bos);
    ReadableByteChannel src = Channels.newChannel(is);
    ByteBuffer bb = ByteBuffer.allocate(4096);

    while (src.read(bb) != -1) {
        bb.flip();
        dest.write(bb);
        bb.clear();
    }
    src.close();
    dest.close();

    return new String(bos.toByteArray(), Constants.ENCODING);
}