Example usage for java.io FileOutputStream getChannel

List of usage examples for java.io FileOutputStream getChannel

Introduction

In this page you can find the example usage for java.io FileOutputStream getChannel.

Prototype

public FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file output stream.

Usage

From source file:org.cloudata.core.commitlog.pipe.CommitLogFileChannel.java

synchronized void init() throws IOException {
    if (channel != null) {
        return;/* ww  w  .j av  a2s . c o m*/
    }

    FileOutputStream fos = null;

    //NStopWatch watch = new NStopWatch();
    try {
        fos = new FileOutputStream(logFileFullPath, true);
        //watch.stopAndReportIfExceed(LOG);
    } catch (FileNotFoundException e) {
        if (parentDir.exists() == false && parentDir.mkdirs() == false && parentDir.exists() == false) {
            throw new IOException("Making directory to " + parentDir.getAbsolutePath() + " is fail");
        }

        fos = new FileOutputStream(logFileFullPath, true);
        //watch.stopAndReportIfExceed(LOG);
    }

    channel = fos.getChannel();

    fos = new FileOutputStream(indexFileFullPath, true);
    //watch.stopAndReportIfExceed(LOG);

    indexChannel = fos.getChannel();

    numPipes.incrementAndGet();
    fileChannelCuller.append(this);
}

From source file:org.cytoscape.app.internal.net.WebQuerier.java

/**
 * Given the unique app name used by the app store, query the app store for the 
 * download URL and download the app to the given directory.
 * //from w  w  w.j  a  va  2 s  . c  om
 * If a file with the same name exists in the directory, it is overwritten.
 * 
 * @param appName The unique app name used by the app store
 * @param version The desired version, or <code>null</code> to obtain the latest release
 * @param directory The directory used to store the downloaded file
 * @param taskMonitor 
 */
public File downloadApp(WebApp webApp, String version, File directory, DownloadStatus status)
        throws AppDownloadException {

    List<WebApp.Release> compatibleReleases = getCompatibleReleases(webApp);

    if (compatibleReleases.size() > 0) {
        WebApp.Release releaseToDownload = null;

        if (version != null) {
            for (WebApp.Release compatibleRelease : compatibleReleases) {

                // Check if the desired version is found in the list of available versions
                if (compatibleRelease.getReleaseVersion()
                        .matches("(^\\s*|.*,)\\s*" + version + "\\s*(\\s*$|,.*)")) {
                    releaseToDownload = compatibleRelease;
                }
            }

            if (releaseToDownload == null) {
                throw new AppDownloadException("No release with the requested version " + version
                        + " was found for the requested app " + webApp.getFullName());
            }
        } else {
            releaseToDownload = compatibleReleases.get(compatibleReleases.size() - 1);
        }

        URL downloadUrl = null;
        try {
            downloadUrl = new URL(currentAppStoreUrl + releaseToDownload.getRelativeUrl());
        } catch (MalformedURLException e) {
            throw new AppDownloadException("Unable to obtain URL for version " + version
                    + " of the release for " + webApp.getFullName());
        }

        if (downloadUrl != null) {
            try {

                // Prepare to download
                URLConnection connection = streamUtil.getURLConnection(downloadUrl);
                InputStream inputStream = connection.getInputStream();
                long contentLength = connection.getContentLength();
                ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);

                File outputFile;
                try {
                    // Replace spaces with underscores
                    String outputFileBasename = webApp.getName().replaceAll("\\s", "_");

                    // Append version information
                    outputFileBasename += "-v" + releaseToDownload.getReleaseVersion();

                    // Strip disallowed characters
                    outputFileBasename = OUTPUT_FILENAME_DISALLOWED_CHARACTERS.matcher(outputFileBasename)
                            .replaceAll("");

                    // Append extension
                    outputFileBasename += ".jar";

                    // Output file has same name as app, but spaces and slashes are replaced with hyphens
                    outputFile = new File(directory.getCanonicalPath() + File.separator + outputFileBasename);

                    if (outputFile.exists()) {
                        outputFile.delete();
                    }

                    outputFile.createNewFile();

                    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                    try {
                        FileChannel fileChannel = fileOutputStream.getChannel();

                        long currentDownloadPosition = 0;
                        long bytesTransferred;

                        TaskMonitor taskMonitor = status.getTaskMonitor();
                        do {
                            bytesTransferred = fileChannel.transferFrom(readableByteChannel,
                                    currentDownloadPosition, 1 << 14);
                            if (status.isCanceled()) {
                                outputFile.delete();
                                return null;
                            }
                            currentDownloadPosition += bytesTransferred;
                            if (contentLength > 0) {
                                double progress = (double) currentDownloadPosition / contentLength;
                                taskMonitor.setProgress(progress);
                            }
                        } while (bytesTransferred > 0);
                    } finally {
                        fileOutputStream.close();
                    }
                } finally {
                    readableByteChannel.close();
                }
                return outputFile;
            } catch (IOException e) {
                throw new AppDownloadException(
                        "Error while downloading app " + webApp.getFullName() + ", " + e.getMessage());
            }
        }
    } else {
        throw new AppDownloadException(
                "No available releases were found for the app " + webApp.getFullName() + ".");
    }
    return null;
}

From source file:org.forgerock.openidm.maintenance.upgrade.UpdateManagerImpl.java

/**
 * Fetch the zip file from the URL and write it to the local filesystem.
 *
 * @param url//from ww w .j  a  v a2s . c om
 * @return
 * @throws UpdateException
 */
private Path readZipFile(URL url) throws UpdateException {

    // Download the patch file
    final ReadableByteChannel channel;
    try {
        channel = Channels.newChannel(url.openStream());
    } catch (IOException ex) {
        throw new UpdateException("Failed to access the specified file " + url + " " + ex.getMessage(), ex);
    }

    String workingDir = "";
    final String targetFileName = new File(url.getPath()).getName();
    final File patchDir = ARCHIVE_PATH.toFile();
    patchDir.mkdirs();
    final File targetFile = new File(patchDir, targetFileName);
    final FileOutputStream fos;
    try {
        fos = new FileOutputStream(targetFile);
    } catch (FileNotFoundException ex) {
        throw new UpdateException("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 UpdateException("Failed to get the specified file " + url + " to: " + targetFile, ex);
    }

    return targetFile.toPath();
}

From source file:com.stfalcon.contentmanager.ContentManager.java

private void handleMediaContent(final Intent data) {
    pickContentListener.onStartContentLoading();

    new Thread(new Runnable() {
        public void run() {
            try {
                Uri contentVideoUri = data.getData();
                FileInputStream in = (FileInputStream) activity.getContentResolver()
                        .openInputStream(contentVideoUri);
                if (targetFile == null) {
                    targetFile = createFile(savedContent);
                }//from  w  w w.  ja va2s.c  om
                FileOutputStream out = new FileOutputStream(targetFile);
                FileChannel inChannel = in.getChannel();
                FileChannel outChannel = out.getChannel();
                inChannel.transferTo(0, inChannel.size(), outChannel);

                in.close();
                out.close();

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        pickContentListener.onContentLoaded(Uri.fromFile(targetFile), savedContent.toString());
                    }
                });
            } catch (final Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        pickContentListener.onError(e.getMessage());
                    }
                });
            }
        }
    }).start();
}

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

/**
 * Extracts a driver archive.//from  w ww  . j  av a  2  s .  com
 * @param file The archive file.
 * @throws IOException
 */
protected void extract(File file) throws IOException {
    // get input stream
    ZipInputStream inputStream = new ZipInputStream(new FileInputStream(file));
    FileOutputStream outputStream = null;

    try {
        // initialize variable
        ZipEntry entry;

        // copy all files
        while ((entry = inputStream.getNextEntry()) != null) {
            // log
            getLogger().info(
                    "Extracting file " + entry.getName() + " from driver archive " + file.getName() + ".");

            // create file reference
            File outputFile = new File(this.getDriverNativeFile().getParentFile(), entry.getName());

            // ensure parent exists
            outputFile.getParentFile().mkdirs();

            // copy file
            ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
            outputStream = new FileOutputStream(outputFile);
            outputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);

            // close stream
            outputStream.close();
            outputStream = null;
        }
    } finally {
        if (inputStream != null)
            IOUtils.closeQuietly(inputStream);
        if (outputStream != null)
            IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.apache.cordova.core.FileUtils.java

/**
 * Moved this code into it's own method so moveTo could use it when the move is across file systems
 *//* www.  j ava2s  .  c  om*/
private void copyAction(File srcFile, File destFile) throws FileNotFoundException, IOException {
    FileInputStream istream = new FileInputStream(srcFile);
    FileOutputStream ostream = new FileOutputStream(destFile);
    FileChannel input = istream.getChannel();
    FileChannel output = ostream.getChannel();

    try {
        input.transferTo(0, input.size(), output);
    } finally {
        istream.close();
        ostream.close();
        input.close();
        output.close();
    }
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriter.java

/**
 * Helper method for opening output source at given file position
 *//*from  w w  w. j  a  v a 2  s  . c o  m*/
private void open(long position) {

    File file;
    FileOutputStream os = null;
    FileChannel fileChannel = null;

    try {
        file = resource.getFile();
        FileUtils.setUpOutputFile(file, restarted, false, overwriteOutput);
        Assert.state(resource.exists(), "Output resource must exist");
        os = new FileOutputStream(file, true);
        fileChannel = os.getChannel();
        channel = os.getChannel();
        setPosition(position);
    } catch (IOException ioe) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                ioe);
    }

    XMLOutputFactory outputFactory = createXmlOutputFactory();

    if (outputFactory.isPropertySupported("com.ctc.wstx.automaticEndElements")) {
        // If the current XMLOutputFactory implementation is supplied by
        // Woodstox >= 3.2.9 we want to disable its
        // automatic end element feature (see:
        // http://jira.codehaus.org/browse/WSTX-165) per
        // http://jira.spring.io/browse/BATCH-761).
        outputFactory.setProperty("com.ctc.wstx.automaticEndElements", Boolean.FALSE);
    }
    if (outputFactory.isPropertySupported("com.ctc.wstx.outputValidateStructure")) {
        // On restart we don't write the root element so we have to disable
        // structural validation (see:
        // http://jira.spring.io/browse/BATCH-1681).
        outputFactory.setProperty("com.ctc.wstx.outputValidateStructure", Boolean.FALSE);
    }

    try {
        final FileChannel channel = fileChannel;
        if (transactional) {
            TransactionAwareBufferedWriter writer = new TransactionAwareBufferedWriter(channel, new Runnable() {
                @Override
                public void run() {
                    closeStream();
                }
            });

            writer.setEncoding(encoding);
            writer.setForceSync(forceSync);
            bufferedWriter = writer;
        } else {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, encoding));
        }
        delegateEventWriter = createXmlEventWriter(outputFactory, bufferedWriter);
        eventWriter = new NoStartEndDocumentStreamWriter(delegateEventWriter);
        initNamespaceContext(delegateEventWriter);
        if (!restarted) {
            startDocument(delegateEventWriter);
            if (forceSync) {
                channel.force(false);
            }
        }
    } catch (XMLStreamException xse) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                xse);
    } catch (UnsupportedEncodingException e) {
        throw new DataAccessResourceFailureException(
                "Unable to write to file resource: [" + resource + "] with encoding=[" + encoding + "]", e);
    } catch (IOException e) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]", e);
    }
}

From source file:org.apache.synapse.config.xml.MultiXMLConfigurationSerializer.java

private boolean isWritable(File file) {
    if (file.isDirectory()) {
        // Further generalize this check
        if (".svn".equals(file.getName())) {
            return true;
        }/*w w w. j  av a 2 s  .c om*/

        File[] children = file.listFiles();
        for (File child : children) {
            if (!isWritable(child)) {
                log.warn("File: " + child.getName() + " is not writable");
                return false;
            }
        }

        if (!file.canWrite()) {
            log.warn("Directory: " + file.getName() + " is not writable");
            return false;
        }
        return true;

    } else {
        if (!file.canWrite()) {
            log.warn("File: " + file.getName() + " is not writable");
            return false;
        }

        FileOutputStream fos = null;
        FileLock lock = null;
        boolean writable;

        try {
            fos = new FileOutputStream(file, true);
            FileChannel channel = fos.getChannel();
            lock = channel.tryLock();
        } catch (IOException e) {
            log.warn("Error while attempting to lock the file: " + file.getName(), e);
            writable = false;
        } finally {
            if (lock != null) {
                writable = true;
                try {
                    lock.release();
                } catch (IOException e) {
                    log.warn("Error while releasing the lock on file: " + file.getName(), e);
                    writable = false;
                }
            } else {
                log.warn("Unable to acquire lock on file: " + file.getName());
                writable = false;
            }

            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.warn("Error while closing the stream on file: " + file.getName(), e);
                writable = false;
            }
        }
        return writable;
    }
}

From source file:com.chiorichan.updater.Download.java

@Override
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;
    try {/*  w w w. j a  v  a 2 s.  co m*/
        HttpURLConnection conn = NetworkFunc.openHttpConnection(url);
        int response = conn.getResponseCode();
        int responseFamily = response / 100;

        if (responseFamily == 3)
            throw new DownloadException(
                    "The server issued a redirect response which the Updater failed to follow.");
        else if (responseFamily != 2)
            throw new DownloadException("The server issued a " + response + " response code.");

        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;

        stateDone();
    } catch (DownloadDeniedException 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);
    }

    if (exception != null)
        AutoUpdater.getLogger().severe("Download Resulted in an Exception", exception);
}

From source file:net.technicpack.launchercore.util.Download.java

@Override
@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;
    try {//  w w w . ja  v  a2  s.c o  m
        HttpURLConnection conn = Utils.openHttpConnection(url);
        int response = conn.getResponseCode();
        int responseFamily = response / 100;

        if (responseFamily == 3) {
            throw new DownloadException(
                    "The server issued a redirect response which Technic failed to follow.");
        } else if (responseFamily != 2) {
            throw new DownloadException("The server issued a " + response + " response code.");
        }

        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);
    }
}