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.streamsets.pipeline.lib.generator.wholefile.WholeFileDataGenerator.java

@Override
public void write(Record record) throws IOException, DataGeneratorException {
    validateRecord(record);//from   w w w. j  a va  2  s.co  m
    FileRef fileRef = record.get(FileRefUtil.FILE_REF_FIELD_PATH).getValueAsFileRef();
    int bufferSize = fileRef.getBufferSize();
    boolean canUseDirectByteBuffer = fileRef.getSupportedStreamClasses().contains(ReadableByteChannel.class);
    if (canUseDirectByteBuffer) {
        //Don't have to close this here, because generate.close will call output stream close
        WritableByteChannel writableByteChannel = Channels.newChannel(outputStream); //NOSONAR
        try (ReadableByteChannel readableByteChannel = getReadableStream(fileRef, ReadableByteChannel.class)) {
            ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
            while ((readableByteChannel.read(buffer)) > 0) {
                //Flip to use the buffer from 0 to position.
                buffer.flip();
                while (buffer.hasRemaining()) {
                    writableByteChannel.write(buffer);
                }
                //Compact the buffer for reuse.
                buffer.clear();
            }
        }
    } else {
        byte[] b = new byte[bufferSize];
        try (InputStream stream = getReadableStream(fileRef, InputStream.class)) {
            IOUtils.copyLarge(stream, outputStream, b);
        }
    }
}

From source file:com.commonsware.android.qrck.SyncService.java

@SuppressWarnings("unchecked")
@Override//  w  w w .j  a  v a 2s.  c  o  m
protected void onHandleIntent(Intent intent) {
    ArrayList<String> visited = new ArrayList<String>();

    if (network.isNetworkAvailable()) {
        inProgress.set(true);
        broadcastStatus();

        try {
            URL jsonUrl = new URL(SYNC_URL);
            ReadableByteChannel rbc = Channels.newChannel(jsonUrl.openStream());
            FileOutputStream fos = openFileOutput(SYNC_LOCAL_FILE, 0);

            fos.getChannel().transferFrom(rbc, 0, 1 << 16);

            JSONObject json = AppUtils.load(this, SYNC_LOCAL_FILE);

            for (Iterator<String> i = json.keys(); i.hasNext();) {
                String title = i.next();
                String url = json.getString(title);
                Entry entry = new Entry(title, url);
                String filename = entry.getFilename();
                File imageFile = new File(getFilesDir(), filename);

                if (!imageFile.exists()) {
                    visited.add(filename);

                    URL imageUrl = new URL(jsonUrl, entry.getUrl());

                    rbc = Channels.newChannel(imageUrl.openStream());
                    fos = new FileOutputStream(imageFile);
                    fos.getChannel().transferFrom(rbc, 0, 1 << 16);
                }
            }

            String[] children = getFilesDir().list();

            if (children != null) {
                for (int i = 0; i < children.length; i++) {
                    String filename = children[i];

                    if (!SYNC_LOCAL_FILE.equals(filename) && !visited.contains(filename)) {
                        new File(getFilesDir(), filename).delete();
                    }
                }
            }
        } catch (Exception ex) {
            // TODO: let the UI know about this via broadcast
            Log.e(TAG, "Exception syncing", ex);
            AppUtils.cleanup(this);
        } finally {
            inProgress.set(false);
            broadcastStatus();
            syncCompleted();
        }
    }
}

From source file:com.github.cat.yum.store.base.RpmScan.java

private ReadableChannelWrapper getReadableChannel(InputStream inputStream) {
    return new ReadableChannelWrapper(Channels.newChannel(inputStream));
}

From source file:eu.betaas.taas.taasvmmanager.configuration.TaaSVMMAnagerConfiguration.java

private static void downloadBaseImages() {
    URL website;//  ww  w. ja  v a 2 s.  co  m
    ReadableByteChannel rbc;
    FileOutputStream fos;
    logger.info("Downloading default VM images.");
    try {
        website = new URL(baseImagesURL);
        rbc = Channels.newChannel(website.openStream());
        fos = new FileOutputStream(baseImagesPath);
        logger.info("Downloading base image from " + baseImagesURL);
        //new DownloadUpdater(baseComputeImageX86Path, baseImagesURL).start();
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    } catch (MalformedURLException e) {
        logger.error("Error downloading images: bad URL.");
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error("Error downloading images: IO exception.");
        logger.error(e.getMessage());
    }
    logger.info("Completed!");
}

From source file:org.spoutcraft.launcher.api.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/*  w ww  . j  av a  2s . c o  m*/
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        result = Result.FAILURE;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:org.richfaces.tests.qa.plugin.utils.files.SimpleExtractor.java

@Override
public void extract(File baseDir, File archive) throws IOException {
    if (archive.getAbsolutePath().endsWith("zip")) {
        getLog().info(MessageFormat.format("Extracting zip file <{0}> to directory <{1}>.",
                archive.getAbsolutePath(), baseDir));
        final ZipInputStream is = new ZipInputStream(new BufferedInputStream(new FileInputStream(archive)));
        ZipEntry entry;/*from w w w  .j a v  a2s. c  om*/
        while ((entry = is.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                final File file = new File(baseDir, entry.getName());
                if (file.exists()) {
                    file.delete();
                }
                Files.createParentDirs(file);
                Files.write(ByteStreams.toByteArray(is), file);
            }
        }
        is.close();
    } else if (archive.getAbsolutePath().endsWith("tar.bz2") || archive.getAbsolutePath().endsWith("tar.gz")) {
        getLog().info(MessageFormat.format("Extracting tar.bz2/tar.gz file <{0}> to directory <{1}>.",
                archive.getAbsolutePath(), baseDir));

        // unzip to tar
        File tarfile = new File(baseDir, "archive.tar");
        tarfile.delete();
        BZip2CompressorInputStream from = new BZip2CompressorInputStream(
                new BufferedInputStream(new FileInputStream(archive)));
        FileOutputStream to = new FileOutputStream(tarfile);
        to.getChannel().transferFrom(Channels.newChannel(from), 0, Long.MAX_VALUE);
        // untar
        final TarArchiveInputStream is = new TarArchiveInputStream(
                new BufferedInputStream(new FileInputStream(tarfile)));
        TarArchiveEntry entry;
        File file;
        while ((entry = is.getNextTarEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(baseDir, entry.getName());
                Files.createParentDirs(file);
                Files.write(ByteStreams.toByteArray(is), file);
            }
        }
        is.close();
        tarfile.delete();
    } else {
        throw new UnsupportedOperationException("Not supported file format " + archive.getName());
    }
    getLog().info(MessageFormat.format("Extracting of <{0}> completed.", archive.getAbsolutePath()));
}

From source file:org.spoutcraft.launcher.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;//from  w w w.  j a  v  a  2s .  c o m
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:org.cryptomator.frontend.webdav.jackrabbitservlet.DavFolder.java

private void addMemberFile(DavFile memberFile, InputStream inputStream) {
    try (ReadableByteChannel src = Channels.newChannel(inputStream);
            WritableFile dst = node.file(memberFile.getDisplayName()).openWritable()) {
        dst.truncate();// www  .j a  va  2s.com
        ByteStreams.copy(src, dst);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.sejda.io.BufferedCountingChannelWriter.java

/**
 * Writes everything that is read from the {@link InputStream} to the destination
 * /*from  w  ww  .ja  v  a2  s  .  c o  m*/
 * @param stream
 * @throws IOException
 */
public void write(InputStream stream) throws IOException {
    onNewLine = false;
    try (ReadableByteChannel readable = Channels.newChannel(stream)) {
        flush();
        while (readable.read(buffer) != -1) {
            flush();
        }
    }
}

From source file:org.apache.pulsar.functions.worker.Utils.java

public static void downloadFromHttpUrl(String destPkgUrl, FileOutputStream outputStream) throws IOException {
    URL website = new URL(destPkgUrl);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    outputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}