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:math.tools.Browse.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    if (table[jTable1.getSelectedRow()][3] == "Not Downloaded Yet") {
        System.out.println("downloading");
        FileOutputStream fos;//from   ww w .j  av  a2 s.c  o  m
        try {
            URL website = new URL("" + table[jTable1.getSelectedRow()][4]);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            fos = new FileOutputStream(System.getProperty("user.home") + "//MathHelper//tools//"
                    + table[jTable1.getSelectedRow()][0] + ".jar");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        } catch (IOException ex) {
            Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    try {
        Runtime.getRuntime().exec("java -jar " + System.getProperty("user.home") + "//MathHelper//tools//"
                + table[jTable1.getSelectedRow()][0] + ".jar");
    } catch (IOException ex) {
        Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.gobblin.example.githubjsontoparquet.EmbeddedGithubJsonToParquet.java

private void downloadFile(String fileUrl, Path destination) {
    if (destination.toFile().exists()) {
        Log.info(String.format("Skipping download for %s at %s because destination already exists", fileUrl,
                destination.toString()));
        return;/*from  w  w w  . j a  va  2  s .  c  o m*/
    }

    try {
        URL archiveUrl = new URL(fileUrl);
        ReadableByteChannel rbc = Channels.newChannel(archiveUrl.openStream());
        FileOutputStream fos = new FileOutputStream(String.valueOf(destination));
        Log.info(String.format("Downloading %s at %s", fileUrl, destination.toString()));
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        Log.info(String.format("Download complete for %s at %s", fileUrl, destination.toString()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.evilco.bot.powersweeper.platform.DriverManager.java

/**
 * Downloads all natives./* www.j a v a2  s.  c  o m*/
 */
public void downloadNatives() {
    getLogger().entry();

    // skip download if unneeded
    if (this.configuration.getDriver() != Driver.CHROME) {
        // debug
        getLogger().debug("Driver download is not required for " + this.configuration.getDriver().toString()
                + " driver implementation.");

        // exit
        getLogger().exit();
        return;
    }

    // check
    if (!this.configuration.isNativeDownloadEnabled()) {
        // log
        getLogger().info("Automatic download of driver natives is disabled.");

        // log possible error
        if (!this.getDriverNativeFile().exists())
            getLogger().warn("The native could not be found! Proceed with caution.");

        // exit
        getLogger().exit();
        return;
    }

    // check driver file
    if (this.getDriverNativeFile().exists()) {
        // log
        getLogger().info("Driver file seems to exist. Skipping download.");

        // exit
        getLogger().exit();
        return;
    }

    // log
    getLogger().info("Starting download of natives.");

    // get platform
    Platform platform = Platform.guessPlatform();
    boolean is64Bit = System.getProperty("os.arch").endsWith("64");

    // build download URL
    String filename = "potato";

    switch (platform) {
    case LINUX:
    case SOLARIS:
    case UNKNOWN:
        filename = "linux" + (is64Bit ? "64" : 32);
        break;
    case MAC_OS_X:
        filename = "mac32";
        break;
    case WINDOWS:
        filename = "win32";
        break;
    }

    // download and extract
    FileOutputStream outputStream = null;

    // ensure directory exists
    this.getDriverNativeFile().getParentFile().mkdirs();

    try {
        URL downloadURL = new URL(String.format(CHROME_DRIVER_URL, filename));

        // log
        getLogger().info("Downloading driver from " + downloadURL.toString() + " ...");

        // create file reference
        File zipFile = new File(this.getDriverNativeFile().getParentFile(), filename + ".zip");

        // start download
        ReadableByteChannel readableByteChannel = Channels.newChannel(downloadURL.openStream());
        outputStream = new FileOutputStream(zipFile);
        outputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);

        // extract zip contents
        this.extract(zipFile);

        // log
        getLogger().info("Finished native download.");

        // delete zip
        if (zipFile.delete())
            getLogger().info("Removed temporary archive.");
        else
            getLogger().warn("Could not remove temporary archive.");
    } catch (IOException ex) {
        getLogger().error("Could not download file from URL \"" + String.format(CHROME_DRIVER_URL, filename)
                + "\": " + ex.getMessage(), ex);
    } finally {
        if (outputStream != null)
            IOUtils.closeQuietly(outputStream);
    }

    // trace
    getLogger().exit();
}

From source file:net.flamefeed.ftb.modpackupdater.FileOperator.java

/**
 * Download remote file and save output to file system. Called from constructor,
 * so final to prevent being overridden.
 * // www.j  av a 2 s .c  o  m
 * @param path
 * A relative path to the file which will be downloaded. This determines both
 * the target URL and the local destination path. Example:
 * "mods/gregtechmod.zip"
 * 
 * @throws java.io.IOException
 */

public void downloadFile(String path) throws IOException {
    URL urlRemoteTarget = new URL(REMOTE_FILES_LOCATION + "/" + path);
    ReadableByteChannel in = Channels.newChannel(urlRemoteTarget.openStream());
    FileOutputStream out = new FileOutputStream(pathMinecraft + "/" + path);
    out.getChannel().transferFrom(in, 0, Long.MAX_VALUE);
}

From source file:com.slytechs.capture.StreamFactory.java

public InputCapture<? extends CapturePacket> newInput(final File file,
        final Filter<ProtocolFilterTarget> filter) throws IOException {

    final BufferedInputStream b = new BufferedInputStream(new FileInputStream(file));
    b.mark(1024); // Buffer first 1K of stream so we can rewind

    /*/*from  ww  w  .j  ava  2s  .c  o m*/
     * Check the stream, without decompression first
     */
    if (formatType(Channels.newChannel(b)) != null) {
        b.close();

        /*
         * This is a plain uncompressed file, open up a FileChannel. It will be
         * much faster
         */
        return newInput(new RandomAccessFile(file, "rw").getChannel(), filter);
    }

    /*
     * Try with gunziped stream, second
     */
    b.reset(); // Rewind
    if (formatType(Channels.newChannel(new GZIPInputStream(b))) != null) {
        b.close();

        /*
         * Now reopen the same file, but this time without the buffered
         * inputstream in the middle. Try to make things as efficient as possible.
         * TODO: implement much faster channel based GZIP decompression algorithm
         */
        return newInput(Channels.newChannel(new GZIPInputStream(new FileInputStream(file))), filter);
    }

    b.close();
    return factoryForOther.getFactory().newInput(new RandomAccessFile(file, "r").getChannel(), filter);

}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.FileContentReaderDynamic.java

@Override
protected ReadableByteChannel getDirectReadableChannel() throws ContentIOException {
    try {//  ww w.j  a  v a 2  s.  c o m
        // the file must exist
        if (!file.exists()) {
            throw new IOException("File does not exist: " + file);
        }
        // create the channel
        ReadableByteChannel channel = null;
        if (allowRandomAccess) {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); // won't create it
            channel = randomAccessFile.getChannel();
        } else {
            InputStream is = new FileInputStream(file);
            channel = Channels.newChannel(is);
        }
        // done
        if (logger.isDebugEnabled()) {
            logger.debug("Opened write channel to file: \n" + "   file: " + file + "\n" + "   random-access: "
                    + allowRandomAccess);
        }
        return channel;
    } catch (Throwable e) {
        throw new ContentIOException("Failed to open file channel: " + this, e);
    }
}

From source file:org.basinmc.maven.plugins.minecraft.AbstractArtifactMojo.java

/**
 * Fetches any resource from a remote HTTP server and writes it to a supplied channel.
 *///from  w  w  w . ja  va2  s  .c  om
protected void fetch(@Nonnull URI uri, @Nonnull @WillNotClose WritableByteChannel outputChannel)
        throws IOException {
    HttpClient client = HttpClients.createMinimal();

    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);

    StatusLine line = response.getStatusLine();

    if (line.getStatusCode() != 200) {
        throw new IOException(
                "Unexpected status code: " + line.getStatusCode() + " - " + line.getReasonPhrase());
    }

    try (InputStream inputStream = response.getEntity().getContent()) {
        try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) {
            ByteStreams.copy(inputChannel, outputChannel);
        }
    }
}

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

@Override
protected ReadableByteChannel getDirectReadableChannel() throws ContentIOException {
    try {/*from  ww w .  j a  v  a 2s.  c  om*/
        // the file must exist
        if (!file.exists()) {
            throw new IOException("File does not exist: " + file);
        }
        // create the channel
        ReadableByteChannel channel = null;
        if (allowRandomAccess) {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); // won't create it
            channel = randomAccessFile.getChannel();
        } else {
            InputStream is = new FileInputStream(file);
            channel = Channels.newChannel(is);
        }
        // done
        if (logger.isDebugEnabled()) {
            logger.debug("Opened read channel to file: \n" + "   file: " + file + "\n" + "   random-access: "
                    + allowRandomAccess);
        }
        return channel;
    } catch (Throwable e) {
        throw new ContentIOException("Failed to open file channel: " + this, e);
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.EncryptingContentWriterDecorator.java

public WritableByteChannel getWritableChannel() throws ContentIOException {
    logger.debug("[EncryptingContentWriterDecorator::getWritableChannel] BEGIN");

    try {/*from   w w  w .ja  v a2 s .com*/
        return Channels.newChannel(getContentOutputStream());
    } finally {
        logger.debug("[EncryptingContentWriterDecorator::getWritableChannel] END");
    }
}

From source file:org.forgerock.openidm.patch.Main.java

private static void storePatchBundle(File workingDir, File installDir, Map<String, Object> params)
        throws PatchException {

    URL url = getPatchLocation();

    // Download the patch file
    ReadableByteChannel channel = null;
    try {/*from w  w w  .ja v a 2  s . c  om*/
        channel = Channels.newChannel(url.openStream());
    } catch (IOException ex) {
        throw new PatchException("Failed to access the specified file " + url + " " + ex.getMessage(), ex);
    }

    String targetFileName = new File(url.getPath()).getName();
    File patchDir = new File(workingDir, "patch/bin");
    patchDir.mkdirs();
    File targetFile = new File(patchDir, targetFileName);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(targetFile);
    } catch (FileNotFoundException ex) {
        throw new PatchException("Error in getting the specified file to " + targetFile, ex);
    }

    try {
        fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);
        System.out.println("Downloaded to " + targetFile);
    } catch (IOException ex) {
        throw new PatchException("Failed to get the specified file " + url + " to: " + targetFile, ex);
    }
}