Example usage for java.nio.channels Channels newChannel

List of usage examples for java.nio.channels Channels newChannel

Introduction

In this page you can find the example usage for java.nio.channels Channels newChannel.

Prototype

public static WritableByteChannel newChannel(OutputStream out) 

Source Link

Document

Constructs a channel that writes bytes to the given stream.

Usage

From source file:com.flexive.shared.FxFileUtils.java

/**
 * Copy the content of an InputStream to a file
 *
 * @param expectedSize    expected size of the stream
 * @param sourceStream    source//  w ww.j a  v  a 2 s .c o  m
 * @param destinationFile destination
 * @return copy was successful and sizes match
 */
public static boolean copyStream2File(long expectedSize, InputStream sourceStream, File destinationFile) {
    ReadableByteChannel sourceChannel = null;
    FileChannel destinationChannel = null;
    try {
        sourceChannel = Channels.newChannel(sourceStream);
        destinationChannel = new FileOutputStream(destinationFile).getChannel();
        return copyNIOChannel(sourceChannel, destinationChannel) == expectedSize
                && destinationFile.length() == expectedSize;
    } catch (IOException e) {
        LOG.error(e, e);
        return false;
    } finally {
        try {
            if (sourceChannel != null)
                sourceChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
        try {
            if (destinationChannel != null)
                destinationChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

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 ava2  s .com
    }

    // 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:org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart.java

/**
 * Copy the ByteBuffer containing this part's binary data
 * to an output stream./* w  ww  . j a va  2s  .  co m*/
 * 
 * @param out
 * @throws IOException
 */
public void writeDataToOutputStream(OutputStream out) throws IOException {

    ByteBuffer buf = this.getBuffer();
    buf.rewind();

    // Fix for https://github.com/plutext/docx4j/issues/80
    // from http://stackoverflow.com/questions/579600/how-to-put-the-content-of-a-bytebuffer-into-an-outputstream
    WritableByteChannel channel = Channels.newChannel(out);
    channel.write(buf);
    buf.rewind();

}

From source file:com.vmware.photon.controller.deployer.deployengine.DockerProvisioner.java

public void createImageFromTar(String filePath, String imageName) {
    if (StringUtils.isBlank(imageName)) {
        throw new IllegalArgumentException("imageName field cannot be null or blank");
    }/* w w w.  j ava 2s  .  co m*/
    if (StringUtils.isBlank(filePath)) {
        throw new IllegalArgumentException("filePath field cannot be null or blank");
    }

    File tarFile = new File(filePath);
    try (FileInputStream fileInputStream = new FileInputStream(tarFile)) {
        FileChannel in = fileInputStream.getChannel();

        String endpoint = getImageLoadEndpoint();
        URL url = new URL(endpoint);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        WritableByteChannel out = Channels.newChannel(connection.getOutputStream());
        in.transferTo(0, tarFile.length(), out);
        in.close();
        out.close();

        int responseCode = connection.getResponseCode();
        if (!String.valueOf(responseCode).startsWith("2")) {
            throw new RuntimeException(
                    "Docker Endpoint cannot load image from tar. Failed with response code " + responseCode);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.glaf.core.util.FileUtils.java

public static byte[] getBytes(InputStream inputStream) {
    if (inputStream == null) {
        return null;
    }/*from   w  w  w . java 2s . c  o m*/
    ByteArrayOutputStream output = null;
    try {
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        ReadableByteChannel readChannel = Channels.newChannel(inputStream);
        output = new ByteArrayOutputStream(32 * 1024);
        WritableByteChannel writeChannel = Channels.newChannel(output);
        while ((readChannel.read(buffer)) > 0 || buffer.position() != 0) {
            buffer.flip();
            writeChannel.write(buffer);
            buffer.compact();
        }
        return output.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (output != null) {
            try {
                output.close();
                output = null;
            } catch (IOException ex) {
            }
        }
    }
}

From source file:org.alfresco.cacheserver.dropwizard.resources.CacheServerResource.java

@Path("/contentByNodeId/{nodeId}/{nodeVersion}")
@GET/*from w  w  w .j  a  v  a  2s . c om*/
public Response contentByNodeId(@PathParam("nodeId") String nodeId,
        @PathParam("nodeVersion") String nodeVersion, @Auth UserDetails user,
        @Context final HttpServletResponse httpResponse) {
    try {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("nodeId = " + nodeId);

        if (nodeId == null || nodeVersion == null) {
            throw new WebApplicationException(Response.Status.BAD_REQUEST);
        } else {
            UserContext.setUser(user);
            try {
                ContentReader content = localContentGetter.getContentByNodeId(nodeId, nodeVersion);
                if (content != null) {
                    ReadableByteChannel inputChannel = content.getChannel();
                    String mimeType = content.getMimeType();

                    StreamingOutput streamer = new StreamingOutput() {
                        @Override
                        public void write(final OutputStream output)
                                throws IOException, WebApplicationException {
                            final WritableByteChannel outputChannel = Channels.newChannel(output);
                            try {
                                fastChannelCopy(inputChannel, outputChannel);
                                //                                  inputChannel.read(outputChannel);
                            } finally {
                                // closing the channels
                                inputChannel.close();
                                outputChannel.close();
                            }
                        }
                    };
                    return Response.ok(streamer).type(mimeType).build();
                } else {
                    return Response.noContent().build();
                }
            } finally {
                UserContext.setUser(null);
            }
        }
    } catch (Exception e) {
        LOGGER.error("caught", e);
        return Response.serverError().build();
    }
}

From source file:edu.usc.pgroup.floe.client.FloeClient.java

/**
 * Download the file from the Coordinator's scratch folder.
 * Note: Filename should not be an absolute path or contain ".."
 *
 * @param fileName    name of the file to be downloaded from coordinator's
 *                    scratch./*from   w  w w. j  a va2s . co  m*/
 * @param outFileName (local) output file name.
 */
public final void downloadFileSync(final String fileName, final String outFileName) {
    if (!Utils.checkValidFileName(fileName)) {
        throw new IllegalArgumentException(
                "Filename is valid. Should not" + " contain .. and should not be an absolute path.");
    }

    int rfid = 0;
    WritableByteChannel outChannel = null;
    try {
        rfid = getClient().beginFileDownload(fileName);
        File outFile = new File(outFileName);
        File parent = outFile.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        outChannel = Channels.newChannel(new FileOutputStream(outFileName));
    } catch (TException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    }

    int written;
    try {
        do {
            ByteBuffer buffer = null;

            buffer = getClient().downloadChunk(rfid);

            written = outChannel.write(buffer);
            LOGGER.info(String.valueOf(written));
        } while (written != 0);
    } catch (TException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } finally {
        if (outChannel != null) {
            try {
                outChannel.close();
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.geowebcache.conveyor.ConveyorTile.java

/**
 * @deprecated as of 1.2.4a, use {@link #getBlob()}, keeping it for backwards compatibility as
 *             there are geoserver builds pegged at a given geoserver revision but building gwc
 *             from trunk. Ok to remove at 1.2.5
 *//*from   w  ww .j  av  a 2 s.c o  m*/
@Deprecated
public byte[] getContent() {
    Resource blob = getBlob();
    if (blob instanceof ByteArrayResource) {
        return ((ByteArrayResource) blob).getContents();
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream((int) blob.getSize());
    try {
        blob.transferTo(Channels.newChannel(out));
        return out.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.codelanx.playtime.update.UpdateHandler.java

/**
 * Downloads the latest jarfile for the {@link Plugin}
 *
 * @since 1.4.5//  w  ww.j  a v a 2  s .c o  m
 * @version 1.4.5
 *
 * @TODO Add zip file support
 * @return The download result
 */
public Result download() {
    Result back = Result.UPDATED;
    File updateLoc = this.plugin.getServer().getUpdateFolderFile();
    updateLoc.mkdirs();
    String url = (String) this.latest.get(this.DL_URL);
    File location = new File(updateLoc, this.file);
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;
    try {
        URL call = new URL(url);
        rbc = Channels.newChannel(call.openStream());
        fos = new FileOutputStream(location);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    } catch (MalformedURLException ex) {
        this.plugin.getLogger().log(Level.SEVERE, "Error finding plugin update to download!", ex);
        back = Result.ERROR_FILENOTFOUND;
    } catch (IOException ex) {
        this.plugin.getLogger().log(Level.SEVERE, "Error transferring plugin data!", ex);
        back = Result.ERROR_DOWNLOAD_FAILED;
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (rbc != null) {
                rbc.close();
            }
        } catch (IOException ex) {
            this.plugin.getLogger().log(Level.SEVERE, "Error closing streams/channels for download!", ex);
        }
    }
    return back;
}