Example usage for java.nio.channels FileChannel transferFrom

List of usage examples for java.nio.channels FileChannel transferFrom

Introduction

In this page you can find the example usage for java.nio.channels FileChannel transferFrom.

Prototype

public abstract long transferFrom(ReadableByteChannel src, long position, long count) throws IOException;

Source Link

Document

Transfers bytes into this channel's file from the given readable byte channel.

Usage

From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHandler.java

@Override
public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath,
        String destDir, String destFileName) {

    File srcPath = new File(
            getAbsolutePath(srcRootPath) + separator() + Database.getDomainName() + separator() + srcDir);

    if (!srcPath.exists()) {
        try {/* ww w. j  ava  2  s  .  c  om*/
            srcPath.mkdirs();
        } catch (Exception e) {
            logger.error("Can't create directory...:" + srcPath);
            return false;
        }
    }

    File destPath = new File(
            getAbsolutePath(destRootPath) + separator() + Database.getDomainName() + separator() + destDir);

    if (!destPath.exists()) {
        try {
            destPath.mkdirs();
        } catch (Exception e) {
            logger.error("Can't create directory...:" + destPath);
            return false;
        }
    }

    File from = new File(srcPath + separator() + srcFileName);
    File to = new File(destPath + separator() + destFileName);

    boolean res = true;
    FileChannel srcChannel = null;
    FileChannel destChannel = null;

    try {
        srcChannel = new FileInputStream(from).getChannel();
        destChannel = new FileOutputStream(to).getChannel();
        destChannel.transferFrom(srcChannel, 0, srcChannel.size());
    } catch (Exception ex) {
        logger.error("ALDefaultStorageHandler.copyFile", ex);
        res = false;
    } finally {
        if (destChannel != null) {
            try {
                destChannel.close();
            } catch (IOException ex) {
                logger.error("ALDefaultStorageHandler.copyFile", ex);
                res = false;
            }
        }
        if (srcChannel != null) {
            try {
                srcChannel.close();
            } catch (IOException ex) {
                logger.error("ALDefaultStorageHandler.copyFile", ex);
                res = false;
            }
        }
    }

    return res;
}

From source file:maspack.fileutil.SafeFileUtils.java

/**
 * Internal copy file method.//from  w w  w.j  a  v  a 2 s.c o m
 * 
 * @param srcFile
 * the validated source file, must not be {@code null}
 * @param destFile
 * the validated destination file, must not be {@code null}
 * @param options
 * determine whether to use a file lock, and preserve date information
 * @throws IOException
 * if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, int options) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    File lockFile = new File(destFile.getAbsolutePath() + LOCK_EXTENSION);

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;

        // Create lock before starting transfer
        // NOTE: we are purposely not using the Java NIO FileLock, because that
        // is automatically removed when the JVM exits. We want this file to
        // persist to inform the system the transfer was never completed.
        if ((options & LOCK_FILE) != 0) {
            if (lockFile.exists()) {

                // if we are not cleaning old locks, throw error
                if ((options & CLEAN_LOCK) == 0) {
                    throw new IOException(
                            "Lock file exists, preventing a write to " + destFile.getAbsolutePath()
                                    + ".  Delete " + lockFile.getName() + " or set the CLEAN_LOCK option flag");
                }
            } else {
                lockFile.createNewFile(); // will always return true or throw
                                          // error
            }

        }

        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        closeQuietly(output);
        closeQuietly(fos);
        closeQuietly(input);
        closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }

    if ((options & PRESERVE_DATE) != 0) {
        destFile.setLastModified(srcFile.lastModified());
    }

    // successful copy, delete lock file
    deleteQuietly(lockFile);

}

From source file:com.aipo.social.opensocial.spi.AipoStorageService.java

@Override
public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath,
        String destDir, String destFileName, SecurityToken paramSecurityToken) throws ProtocolException {

    File srcPath = new File(
            getAbsolutePath(srcRootPath) + separator() + Database.getDomainName() + separator() + srcDir);

    if (!srcPath.exists()) {
        try {//from   www.j a v  a 2s . c  om
            srcPath.mkdirs();
        } catch (Exception e) {
            return false;
        }
    }

    File destPath = new File(
            getAbsolutePath(destRootPath) + separator() + Database.getDomainName() + separator() + destDir);

    if (!destPath.exists()) {
        try {
            destPath.mkdirs();
        } catch (Exception e) {
            return false;
        }
    }

    File from = new File(srcPath + separator() + srcFileName);
    File to = new File(destPath + separator() + destFileName);

    boolean res = true;
    FileChannel srcChannel = null;
    FileChannel destChannel = null;

    try {
        srcChannel = new FileInputStream(from).getChannel();
        destChannel = new FileOutputStream(to).getChannel();
        destChannel.transferFrom(srcChannel, 0, srcChannel.size());
    } catch (Exception ex) {
        res = false;
    } finally {
        if (destChannel != null) {
            try {
                destChannel.close();
            } catch (IOException ex) {
                res = false;
            }
        }
        if (srcChannel != null) {
            try {
                srcChannel.close();
            } catch (IOException ex) {
                res = false;
            }
        }
    }

    return res;
}

From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java

public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException {
    //get a temporary file
    log.debug("copyLocalFileAsTempFileInExternallyAccessableDir");
    File f = this.createTempFileInExternallyAccessableDir();

    //copying one file to another with FileChannel 
    //@see http://www.exampledepot.com/egs/java.nio/File2File.html
    FileChannel srcChannel = new FileInputStream(localFileRef).getChannel();
    FileChannel dstChannel = new FileOutputStream(f).getChannel();
    log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef
            + " to dest-outputStream: " + f.getAbsolutePath());
    // Copy file contents from source to destination
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    //Close the channels
    srcChannel.close();/*from w  w  w  .ja  v a  2s .com*/
    dstChannel.close();
    log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath());
    return f;
}

From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java

private void copyFile(File source_file, File destination_file) throws IOException {
    if (destination_file.exists()) {
        Log2Dump dump = new Log2Dump();
        dump.add("source_file", source_file);
        dump.add("destination_file", destination_file);
        dump.add("delete_after_copy", delete_after_copy);

        if (fileexistspolicy == FileExistsPolicy.IGNORE) {
            Log2.log.debug("Destination file exists, ignore copy/move", dump);
            return;
        } else if (fileexistspolicy == FileExistsPolicy.OVERWRITE) {
            Log2.log.debug("Destination file exists, overwrite it", dump);
            FileUtils.forceDelete(destination_file);
        } else if (fileexistspolicy == FileExistsPolicy.RENAME) {
            // destination_file
            int cursor = 1;
            int dot_pos;
            StringBuilder sb;/*from  ww w.j av a2  s .  com*/
            while (destination_file.exists()) {
                sb = new StringBuilder();
                sb.append(destination_file.getParent());
                sb.append(File.separator);
                dot_pos = destination_file.getName().lastIndexOf(".");
                if (dot_pos > 0) {
                    sb.append(destination_file.getName().substring(0, dot_pos));
                    sb.append(" (");
                    sb.append(cursor);
                    sb.append(")");
                    sb.append(
                            destination_file.getName().substring(dot_pos, destination_file.getName().length()));
                } else {
                    sb.append(destination_file.getName());
                    sb.append(" (");
                    sb.append(cursor);
                    sb.append(")");
                }
                destination_file = new File(sb.toString());
                cursor++;
            }
            dump.add("new destination file name", destination_file);
            Log2.log.debug("Destination file exists, change destionation name", dump);
        }
    }
    /**
     * Imported from org.apache.commons.io.FileUtils
     * Licensed to the Apache Software Foundation,
     * http://www.apache.org/licenses/LICENSE-2.0
     */
    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(source_file);
        fos = new FileOutputStream(destination_file);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
            pos += output.transferFrom(input, pos, count);

            if (progression != null) {
                actual_progress_value = (int) ((pos + progress_copy) / (1024 * 1024));
                if (actual_progress_value > last_progress_value) {
                    last_progress_value = actual_progress_value;
                    progression.updateProgress(actual_progress_value, progress_size);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (source_file.length() != destination_file.length()) {
        throw new IOException(
                "Failed to copy full contents from '" + source_file + "' to '" + destination_file + "'");
    }
    if (destination_file.setExecutable(source_file.canExecute()) == false) {
        Log2.log.error("Can't set Executable status to dest file", new IOException(destination_file.getPath()));
    }
    if (destination_file.setLastModified(source_file.lastModified()) == false) {
        Log2.log.error("Can't set LastModified status to dest file",
                new IOException(destination_file.getPath()));
    }
}

From source file:org.rhq.plugins.jslee.JainSleeServerComponent.java

private void copyFile(File sourceFile, File destFile) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath()
                + "]");
    }/*from w  w  w .  j  a  v a2  s .  c o  m*/

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:de.baumann.quitsmoking.fragments.FragmentNotes.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_backup) {

        final CharSequence[] options = { getString(R.string.action_backup), getString(R.string.action_restore),
                getString(R.string.action_delete) };

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override/*from  w  w  w.  j  a  va 2 s .  c om*/
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals(getString(R.string.action_backup))) {

                    sharedPref.edit().putString("sortDB", "title").apply();
                    setNotesList();

                    File directory = new File(
                            Environment.getExternalStorageDirectory() + "/QuitSmoking/backup/");
                    if (!directory.exists()) {
                        //noinspection ResultOfMethodCallIgnored
                        directory.mkdirs();
                    }

                    try {
                        File sd = Environment.getExternalStorageDirectory();
                        File data = Environment.getDataDirectory();

                        if (sd.canWrite()) {

                            String currentDBPath2 = "//data//" + "de.baumann.quitsmoking" + "//databases//"
                                    + "notes.db";
                            String backupDBPath2 = "//QuitSmoking//" + "//backup//" + "notes.db";
                            File currentDB2 = new File(data, currentDBPath2);
                            File backupDB2 = new File(sd, backupDBPath2);

                            FileChannel src2 = new FileInputStream(currentDB2).getChannel();
                            FileChannel dst2 = new FileOutputStream(backupDB2).getChannel();
                            dst2.transferFrom(src2, 0, src2.size());
                            src2.close();
                            dst2.close();

                            Snackbar snackbar = Snackbar.make(listView, R.string.toast_backup,
                                    Snackbar.LENGTH_LONG);
                            snackbar.show();
                        }
                    } catch (Exception e) {
                        Snackbar snackbar = Snackbar.make(listView, R.string.toast_backup_not,
                                Snackbar.LENGTH_LONG);
                        snackbar.show();
                    }
                }

                if (options[item].equals(getString(R.string.action_restore))) {

                    sharedPref.edit().putString("sortDB", "seqno").apply();
                    setNotesList();

                    try {
                        File sd = Environment.getExternalStorageDirectory();
                        File data = Environment.getDataDirectory();

                        if (sd.canWrite()) {

                            String currentDBPath2 = "//data//" + "de.baumann.quitsmoking" + "//databases//"
                                    + "notes.db";
                            String backupDBPath2 = "//QuitSmoking//" + "//backup//" + "notes.db";
                            File currentDB2 = new File(data, currentDBPath2);
                            File backupDB2 = new File(sd, backupDBPath2);

                            FileChannel src2 = new FileInputStream(backupDB2).getChannel();
                            FileChannel dst2 = new FileOutputStream(currentDB2).getChannel();
                            dst2.transferFrom(src2, 0, src2.size());
                            src2.close();
                            dst2.close();
                            Snackbar snackbar = Snackbar.make(listView, R.string.toast_restore,
                                    Snackbar.LENGTH_LONG);
                            snackbar.show();
                            setNotesList();
                        }
                    } catch (Exception e) {
                        Snackbar snackbar = Snackbar.make(listView, R.string.toast_restore_not,
                                Snackbar.LENGTH_LONG);
                        snackbar.show();
                    }
                }

                if (options[item].equals(getString(R.string.action_delete))) {

                    sharedPref.edit().putString("sortDB", "icon").apply();
                    setNotesList();

                    Snackbar snackbar = Snackbar
                            .make(listView, R.string.note_delete_confirmation, Snackbar.LENGTH_LONG)
                            .setAction(R.string.yes, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    getActivity().deleteDatabase("notes.db");
                                    setNotesList();
                                }
                            });
                    snackbar.show();
                }
            }
        });
        builder.setPositiveButton(R.string.goal_cancel, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    if (id == R.id.action_sort) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View dialogView = View.inflate(getActivity(), R.layout.dialog_sort, null);

        final CheckBox ch_title = (CheckBox) dialogView.findViewById(R.id.checkBoxTitle);
        final CheckBox ch_create = (CheckBox) dialogView.findViewById(R.id.checkBoxCreate);
        final CheckBox ch_edit = (CheckBox) dialogView.findViewById(R.id.checkBoxEdit);
        final CheckBox ch_icon = (CheckBox) dialogView.findViewById(R.id.checkBoxIcon);
        final CheckBox ch_att = (CheckBox) dialogView.findViewById(R.id.checkBoxAtt);

        if (sharedPref.getString("sortDB", "title").equals("title")) {
            ch_title.setChecked(true);
        } else {
            ch_title.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("create")) {
            ch_create.setChecked(true);
        } else {
            ch_create.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("seqno")) {
            ch_edit.setChecked(true);
        } else {
            ch_edit.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("icon")) {
            ch_icon.setChecked(true);
        } else {
            ch_icon.setChecked(false);
        }
        if (sharedPref.getString("sortDB", "title").equals("attachment")) {
            ch_att.setChecked(true);
        } else {
            ch_att.setChecked(false);
        }

        ch_title.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_edit.setChecked(false);
                    ch_icon.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "title").apply();
                    setNotesList();
                }
            }
        });
        ch_create.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_edit.setChecked(false);
                    ch_icon.setChecked(false);
                    ch_title.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "create").apply();
                    setNotesList();
                }
            }
        });
        ch_edit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_icon.setChecked(false);
                    ch_title.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "seqno").apply();
                    setNotesList();
                }
            }
        });
        ch_icon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_edit.setChecked(false);
                    ch_title.setChecked(false);
                    ch_att.setChecked(false);
                    sharedPref.edit().putString("sortDB", "icon").apply();
                    setNotesList();
                }
            }
        });
        ch_att.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ch_create.setChecked(false);
                    ch_edit.setChecked(false);
                    ch_title.setChecked(false);
                    ch_icon.setChecked(false);
                    sharedPref.edit().putString("sortDB", "attachment").apply();
                    setNotesList();
                }
            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.action_sort);
        builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });

        final AlertDialog dialog2 = builder.create();
        // Display the custom alert dialog on interface
        dialog2.show();
        return true;
    }

    if (id == R.id.action_note) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

        String dateCreate = format.format(date);
        sharedPref.edit().putString("handleTextCreate", dateCreate).apply();

        helper_notes.editNote(getActivity());

    }

    return super.onOptionsItemSelected(item);
}

From source file:org.alfresco.repo.content.AbstractContentWriter.java

/**
 * {@inheritDoc}//www . j a  v  a 2s  .  c om
 */
public FileChannel getFileChannel(boolean truncate) throws ContentIOException {
    /*
     * By calling this method, clients indicate that they wish to make random
     * changes to the file.  It is possible that the client might only want
     * to update a tiny proportion of the file (truncate == false) or
     * start afresh (truncate == true).
     * 
     * Where the underlying support is not present for this method, a temporary
     * file will be used as a substitute.  When the write is complete, the
     * results are copied directly to the underlying channel.
     */

    // get the underlying implementation's best writable channel
    channel = getWritableChannel();
    // now use this channel if it can provide the random access, otherwise spoof it
    FileChannel clientFileChannel = null;
    if (channel instanceof FileChannel) {
        // all the support is provided by the underlying implementation
        clientFileChannel = (FileChannel) channel;
        // copy over the existing content, if required
        if (!truncate && existingContentReader != null) {
            ReadableByteChannel existingContentChannel = existingContentReader.getReadableChannel();
            long existingContentLength = existingContentReader.getSize();
            // copy the existing content
            try {
                clientFileChannel.transferFrom(existingContentChannel, 0, existingContentLength);
                // copy complete
                if (logger.isDebugEnabled()) {
                    logger.debug("Copied content for random access: \n" + "   writer: " + this + "\n"
                            + "   existing: " + existingContentReader);
                }
            } catch (IOException e) {
                throw new ContentIOException("Failed to copy from existing content to enable random access: \n"
                        + "   writer: " + this + "\n" + "   existing: " + existingContentReader, e);
            } finally {
                try {
                    existingContentChannel.close();
                } catch (IOException e) {
                }
            }
        }
        // debug
        if (logger.isDebugEnabled()) {
            logger.debug("Content writer provided direct support for FileChannel: \n" + "   writer: " + this);
        }
    } else {
        // No random access support is provided by the implementation.
        // Spoof it by providing a 2-stage write via a temp file
        File tempFile = TempFileProvider.createTempFile("random_write_spoof_", ".bin");
        final FileContentWriter spoofWriter = new FileContentWriter(tempFile, // the file to write to
                getExistingContentReader()); // this ensures that the existing content is pulled in
        // Attach a listener
        // - to ensure that the content gets loaded from the temp file once writing has finished
        // - to ensure that the close call gets passed on to the underlying channel
        ContentStreamListener spoofListener = new ContentStreamListener() {
            public void contentStreamClosed() throws ContentIOException {
                // the spoofed temp channel has been closed, so get a new reader for it
                ContentReader spoofReader = spoofWriter.getReader();
                FileChannel spoofChannel = spoofReader.getFileChannel();
                // upload all the temp content to the real underlying channel
                try {
                    long spoofFileSize = spoofChannel.size();
                    spoofChannel.transferTo(0, spoofFileSize, channel);
                } catch (IOException e) {
                    throw new ContentIOException(
                            "Failed to copy from spoofed temporary channel to permanent channel: \n"
                                    + "   writer: " + this + "\n" + "   temp: " + spoofReader,
                            e);
                } finally {
                    try {
                        spoofChannel.close();
                    } catch (Throwable e) {
                    }
                    try {
                        channel.close();
                    } catch (IOException e) {
                        throw new ContentIOException("Failed to close underlying channel", e);
                    }
                }
            }
        };
        spoofWriter.addListener(spoofListener);
        // we now have the spoofed up channel that the client can work with
        clientFileChannel = spoofWriter.getFileChannel(truncate);
        // debug
        if (logger.isDebugEnabled()) {
            logger.debug("Content writer provided indirect support for FileChannel: \n" + "   writer: " + this
                    + "\n" + "   temp writer: " + spoofWriter);
        }
    }
    // the file is now available for random access
    return clientFileChannel;
}

From source file:org.wso2.esb.integration.common.utils.ESBTestCaseUtils.java

/**
 * Copy the given source file to the given destination
 *
 * @param sourceUri source file location
 * @param destUri   destination file location
 * @throws IOException//w w w  . j ava  2s  .  c  om
 */
public static void copyFile(String sourceUri, String destUri) throws IOException {
    File sourceFile = new File(sourceUri);
    File destFile = new File(destUri);

    if (destFile.exists()) {
        destFile.delete();
    }
    destFile.createNewFile();
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;

    try {
        fileInputStream = new FileInputStream(sourceFile);
        fileOutputStream = new FileOutputStream(destFile);

        FileChannel source = fileInputStream.getChannel();
        FileChannel destination = fileOutputStream.getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:eu.optimis.vc.api.IsoCreator.IsoImageCreation.java

private void storeAgents(File scriptsDirectory) {
    if (virtualMachine.isHasIPS() || virtualMachine.isHasBTKey() || virtualMachine.isHasVPNKey()) {
        LOGGER.debug("Adding agents to ISO");

        // Add the agent tar ball
        String agentsTarBallName = "vpn.tar.gz";
        // Agents tar ball source
        File agentsTarBallFileSource = new File(
                configuration.getAgentsDirectory() + File.separator + agentsTarBallName);
        LOGGER.debug("agentsTarBallFileSource is: " + agentsTarBallFileSource.getPath());
        // Destination folder
        File agentsIsoDirectory = new File(isoDataDirectory + File.separator + "agents");
        agentsIsoDirectory.mkdirs();/*from   www .  j  ava2 s .  c  o m*/
        LOGGER.debug("agentsIsoDirectory is: " + agentsIsoDirectory.getPath());
        // Agents tar ball destination
        File agentsTarBallFileDestination = new File(agentsIsoDirectory + File.separator + agentsTarBallName);
        LOGGER.debug("agentsTarBallFileDestination is: " + agentsTarBallFileDestination.getPath());

        // Copy the file to the iso directory
        LOGGER.debug("Copying agent file to ISO directory...");
        FileChannel source = null;
        FileChannel destination = null;
        try {
            if (!agentsTarBallFileDestination.exists()) {
                agentsTarBallFileDestination.createNewFile();
            }
            source = new FileInputStream(agentsTarBallFileSource).getChannel();
            destination = new FileOutputStream(agentsTarBallFileDestination).getChannel();
            destination.transferFrom(source, 0, source.size());
            LOGGER.debug(
                    "Copied agent file to ISO directory, size is : " + agentsTarBallFileDestination.length());
            agentsTarBallFileDestination.getTotalSpace();
        } catch (IOException e) {
            LOGGER.error(
                    "Failed to create agents tar ball with path: " + agentsTarBallFileDestination.getPath(), e);
        } finally {
            if (source != null) {
                try {
                    source.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close source agents tar ball file with path: "
                            + agentsTarBallFileSource.getPath(), e);
                }
            }
            if (destination != null) {
                try {
                    destination.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close destination agents tar ball file with path: "
                            + agentsTarBallFileDestination.getPath(), e);
                }
            }
        }

        // Add the agent script
        File agentsFile = new File(scriptsDirectory + File.separator + "agents.sh");
        try {
            LOGGER.debug(ATTEMPTING_TO_CREATE_FILE + agentsFile.getPath());
            agentsFile.createNewFile();
            LOGGER.debug(CREATED_FILE + agentsFile.getPath());

            // TODO: This should be stored somewhere else and not hardcoded
            // Mount location is currently hard coded in the init.d scripts
            // of the base VM /mnt/context/
            String agentsScript = "#!/bin/bash\n" + "#Setup environment\n" + "touch /var/lock/subsys/local\n"
                    + "source /etc/profile\n" + "\n"
                    + "#Extract the agent from the ISO agent directory to /opt/optimis/vpn/\n"
                    + "mkdir -p /opt/optimis\n" + "tar zxvf /mnt/context/agents/" + agentsTarBallName
                    + " -C /opt/optimis/\n" + "chmod -R 777 /opt/optimis/vpn\n" + "\n"
                    + "#Install and start the agents\n" + "\n";

            // Add VPN install and init script to
            // /mnt/context/scripts/agents.sh
            if (virtualMachine.isHasIPS()) {
                agentsScript += "#IPS\n" + "/opt/optimis/vpn/IPS_Meta.sh\n"
                        + "/bin/date > /opt/optimis/vpn/dsa.log\n" + "\n";
            }

            // Add VPN install and init script to
            // /mnt/context/scripts/agents.sh ?

            // KMS
            if (virtualMachine.isHasBTKey()) {
                agentsScript += "#KMS\n" + "/opt/optimis/vpn/KMS_Meta.sh\n"
                        + "/bin/date >> /opt/optimis/vpn/scagent.log\n" + "\n";
            }

            // Add VPN install and init script to
            // /mnt/context/scripts/agents.sh
            if (virtualMachine.isHasVPNKey()) {
                agentsScript += "#VPN\n" + "/opt/optimis/vpn/VPN_Meta.sh\n";
            }

            // Write out the agents file
            FileOutputStream fos = new FileOutputStream(agentsFile.getPath());
            fos.write(agentsScript.getBytes());
            fos.close();
            LOGGER.debug("Writing agents script complete!");

        } catch (IOException e) {
            LOGGER.error("Failed to create agents script file with path: " + agentsFile.getPath(), e);
        }
    } else {
        LOGGER.debug("Agents not not needed by service!");
    }

}