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:io.spring.initializr.generator.ProjectGenerator.java

private File downloadExternalStructure(String urlStr, File file) throws IOException {
    URL url = new URL(urlStr);
    String filename = FilenameUtils.getBaseName(urlStr) + "." + FilenameUtils.getExtension(urlStr);
    log.info("Filename: " + filename);
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    File f = new File(file, filename);
    FileOutputStream fos = new FileOutputStream(f);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();/*from  ww w .j  a v a  2 s  .  co m*/
    rbc.close();
    return f;
}

From source file:org.alfresco.repo.content.filestore.SpoofedTextContentReader.java

@Override
protected ReadableByteChannel getDirectReadableChannel() throws ContentIOException {
    try {/* w  w w .j  a v  a2  s .co  m*/
        // Interpret the URL to generate the text
        InputStream textStream = textGenerator.getInputStream(seed, size, words);
        ReadableByteChannel textChannel = Channels.newChannel(textStream);
        // done
        if (logger.isDebugEnabled()) {
            logger.debug("Opened read channel to random text for URL: " + getContentUrl());
        }
        return textChannel;
    } catch (Throwable e) {
        throw new ContentIOException("Failed to read channel: " + this, e);
    }
}

From source file:org.tinymediamanager.scraper.http.Url.java

/**
 * Download an Url to a file via NIO FileChannel (synchron)
 * /*  w ww .  ja  va 2  s  .  c o m*/
 * @param file
 * @return successful or not
 */
public boolean download(File file) {
    try {
        InputStream is = getInputStream();
        if (is == null) {
            return false;
        }
        ReadableByteChannel rbc = Channels.newChannel(is);
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        return true;
    } catch (IOException e) {
        LOGGER.error("Error downloading " + this.url);
    } catch (InterruptedException ignored) {
        if (call != null) {
            call.cancel();
        }
    }
    return false;
}

From source file:io.crate.frameworks.mesos.CrateExecutor.java

private boolean fetchAndExtractUri(URI uri) {
    boolean success;
    try {/*  w ww .j av a 2  s .  c  o  m*/
        URL download = uri.toURL();
        String fn = new File(download.getFile()).getName();
        File tmpFile = new File(fn);
        if (!tmpFile.exists()) {
            if (tmpFile.createNewFile()) {
                LOGGER.debug("Fetch: {} -> {}", download, tmpFile);
                ReadableByteChannel rbc = Channels.newChannel(download.openStream());
                FileOutputStream stream = new FileOutputStream(tmpFile);
                stream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
        } else {
            LOGGER.debug("tarball already downloaded");
        }
        success = extractFile(tmpFile);
    } catch (IOException e) {
        e.printStackTrace();
        success = false;
    }
    return success;
}

From source file:com.skcraft.launcher.launch.JavaRuntimeFetcher.java

private void copyFile(InputStream source, File destination, String status, long length) {
    ReadableByteChannel byteChannel = null;
    FileOutputStream outputStream = null;
    try {//  ww w . ja va  2 s  .c  om
        if (destination.getParentFile().mkdirs()) {
            log.log(Level.INFO, "Creating dir: {0}", destination.getParentFile());
        }

        if (destination.createNewFile()) {
            log.log(Level.INFO, "Creating file: {0}", destination);
        }

        byteChannel = Channels.newChannel(source);
        outputStream = new FileOutputStream(destination);

        if (length < 0) {
            getProgress().set(status, -1);
            outputStream.getChannel().transferFrom(byteChannel, 0, Long.MAX_VALUE);
        } else {
            long position = 0;
            long increment = length / 100L;
            while (position < length) {
                outputStream.getChannel().transferFrom(byteChannel, position, increment);
                position += increment;

                double progress = (double) position / (double) length;
                getProgress().set(status, progress);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        Closer.close(byteChannel);
        Closer.close(outputStream);
    }
}

From source file:de.lmu.ifi.dbs.jfeaturelib.utils.Extractor.java

/**
 * reads the shipped properties file and copies it into the current execution directory
 *///from  w  ww  .j  a v  a 2  s  .  c om
private void unpackProperties() {
    try {
        try (InputStream is = LibProperties.class.getResourceAsStream("/" + LibProperties.BASE_FILE.getName());
                FileChannel dst = new FileOutputStream(LibProperties.BASE_FILE).getChannel()) {
            dst.transferFrom(Channels.newChannel(is), 0, Integer.MAX_VALUE);
            log.info("wrote jfeaturelib.properties");
        }
        try (InputStream is = LibProperties.class.getResourceAsStream("/log4j.properties");
                FileChannel dst = new FileOutputStream("log4j.properties").getChannel()) {
            dst.transferFrom(Channels.newChannel(is), 0, Integer.MAX_VALUE);
            log.info("wrote log4j.properties");
        }
    } catch (IOException ex) {
        log.warn("The properties could not be extracted. Please see the log for more information.", ex);
    }
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

protected CryptoOutputStream getCryptoOutputStream(ByteArrayOutputStream baos, Cipher cipher, int bufferSize,
        byte[] iv, boolean withChannel) throws IOException {
    if (withChannel) {
        return new CryptoOutputStream(Channels.newChannel(baos), cipher, bufferSize, key, iv);
    } else {//from  w w w .ja  va2 s . co m
        return new CryptoOutputStream(baos, cipher, bufferSize, key, iv);
    }
}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

private void replaceFile(final Path file, final URL url) throws IOException {
    //Create the file
    SeekableByteChannel sbc = null;
    try {//from  ww w. j av  a  2  s  . c  o m
        //Creates a new Readable Byte channel from URL
        final ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        //Create the file
        sbc = Files.newByteChannel(file, FILE_REPLACE_OPTIONS);

        //Clears the buffer
        buffer.clear();

        //Read input Channel
        while (rbc.read(buffer) != -1) {
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            sbc.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear()
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
            sbc.write(buffer);
        }
    } finally {
        if (sbc != null) {
            sbc.close();
        }
    }
}

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

private void copyDefaultConfigsIfNotExists(Class callerClass) {

    URL carbonXmlUrl = callerClass.getClassLoader().getResource("repository/conf/carbon.xml");
    boolean needToCopyCarbonXml = false;
    if (carbonXmlUrl == null) {
        needToCopyCarbonXml = true;//from   www  .j  a v  a  2  s.  c om
    } else {
        File file = new File(carbonXmlUrl.getPath());
        needToCopyCarbonXml = !file.exists();
    }
    if (needToCopyCarbonXml) {
        try {
            //Copy default identity xml into temp location and use it.
            URL url = CarbonBasedTestListener.class.getClassLoader().getResource("repository/conf/carbon.xml");
            InputStream inputStream = url.openStream();
            ReadableByteChannel inputChannel = Channels.newChannel(inputStream);

            Path tmpDirPath = Paths.get(System.getProperty("java.io.tmpdir"), "tests",
                    callerClass.getSimpleName());
            Path repoConfPath = Paths.get(tmpDirPath.toUri().getPath(), "repository", "conf");
            Path carbonXMLPath = repoConfPath.resolve("carbon.xml");
            Path carbonXML = Files.createFile(carbonXMLPath);
            FileOutputStream fos = new FileOutputStream(carbonXML.toFile());
            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();
            System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH, tmpDirPath.toString());
        } catch (IOException e) {
            log.error("Failed to copy carbon.xml", e);
        }
    } else {
        try {
            System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH,
                    Paths.get(carbonXmlUrl.toURI()).getParent().toString());
        } catch (URISyntaxException e) {
            log.error("Failed to copy path for carbon.xml", e);
        }
    }

}

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

public static File extractFileFromPkg(String destPkgUrl) throws IOException, URISyntaxException {
    if (destPkgUrl.startsWith(org.apache.pulsar.common.functions.Utils.FILE)) {
        URL url = new URL(destPkgUrl);
        File file = new File(url.toURI());
        if (!file.exists()) {
            throw new IOException(destPkgUrl + " does not exists locally");
        }//from  ww  w. j  av  a2 s.c om
        return file;
    } else if (destPkgUrl.startsWith("http")) {
        URL website = new URL(destPkgUrl);
        File tempFile = File.createTempFile("function", ".tmp");
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.getChannel().transferFrom(rbc, 0, 10);
        }
        if (tempFile.exists()) {
            tempFile.delete();
        }
        return tempFile;
    } else {
        throw new IllegalArgumentException(
                "Unsupported url protocol " + destPkgUrl + ", supported url protocols: [file/http/https]");
    }
}