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: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  www  .j  ava2s . 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:com.splout.db.dnode.Fetcher.java

/**
 * In case of interrupted, written file is not deleted.
 *///from  ww  w  .  j ava  2s.c o  m
private void copyFile(File sourceFile, File destFile, Reporter reporter)
        throws IOException, InterruptedException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;

    Throttler throttler = new Throttler((double) bytesPerSecThrottle);

    FileInputStream iS = null;
    FileOutputStream oS = null;

    try {
        iS = new FileInputStream(sourceFile);
        oS = new FileOutputStream(destFile);
        source = iS.getChannel();
        destination = oS.getChannel();
        long bytesSoFar = 0;
        long reportingBytesSoFar = 0;
        long size = source.size();

        int transferred = 0;

        while (bytesSoFar < size) {
            // Needed to being able to be interrupted at any moment.
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            // Casting to int here is safe since we will transfer at most "downloadBufferSize" bytes.
            // This is done on purpose for being able to implement Throttling.
            transferred = (int) destination.transferFrom(source, bytesSoFar, downloadBufferSize);
            bytesSoFar += transferred;
            reportingBytesSoFar += transferred;
            throttler.incrementAndThrottle(transferred);
            if (reportingBytesSoFar >= bytesToReportProgress) {
                reporter.progress(reportingBytesSoFar);
                reportingBytesSoFar = 0l;
            }
        }

        if (reporter != null) {
            reporter.progress(reportingBytesSoFar);
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (iS != null) {
            iS.close();
        }
        if (oS != null) {
            oS.close();
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:com.alu.e3.logger.LogCollector.java

/**
 * Copy a file from one location to another on the localhost, first moving
 * (renaming) the source file out of the way of any rotator process, and
 * then optionally deleting the source file after a successful copy.  
 * Will attempt to replicate the modification time from the original file.
 * /*from   www.ja va 2 s  .  c  o  m*/
 * @param sourceFile   File to copy
 * @param destFile      Destination file
 * @param deleteSource   If <code>true</code>, will delete original after copy
 * @return            The number of bytes copied
 * @throws IOException
 */
public static long copyLocalFile(File sourceFile, File destFile, boolean deleteSource) throws IOException {
    long bytesCopied = 0L;

    if ((sourceFile == null) || (destFile == null)) {
        throw new NullPointerException(
                "Source or destination file is null (source: " + sourceFile + ", dest: " + destFile + ")");
    }

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

    String origSourcePath = sourceFile.getPath();
    File tempFile = new File(tempNameForSourceFile(sourceFile.getPath()));
    FileChannel source = null;
    FileChannel destination = null;
    IOException cleanupException = null;
    boolean success = false;

    // Copy and validate result
    try {
        // Rename source file to temporary name before copying
        if (logger.isDebugEnabled()) {
            logger.debug("Renaming local file to: {}", tempFile.getPath());
        }
        if (!sourceFile.renameTo(tempFile)) {
            logger.error("Could not move file to new name: {}", tempFile.getAbsolutePath());
        } else {
            source = new FileInputStream(tempFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            bytesCopied = destination.transferFrom(source, 0, source.size());
            copyModificationTime(tempFile, destFile);

            // Check integrity of copy
            success = validateFileCopy(tempFile, destFile);
            if (!success) {
                logger.warn("Copy of file {} did not pass integrity check!", origSourcePath);
            }
        }
    } catch (IOException ex) {
        // If there's been an error copying the file, we may be left with a zero-length or incomplete file
        if (!success) {
            if (logger.isDebugEnabled()) {
                logger.debug("Deleting failed copy of local file: {}", destFile.getAbsolutePath());
            }
            destFile.delete();
        }
    } finally {
        // Use a try-block during cleanup, but only throw exception if the
        // main file-copy try-block doesn't
        try {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
            if (deleteSource && success) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Deleting local source file: {}", tempFile.getAbsolutePath());
                }
                tempFile.delete();
            } else {
                // Move source file back from temp name
                if (tempFile == null || !tempFile.renameTo(new File(origSourcePath))) {
                    logger.error("Could not restore original filename: {}", origSourcePath);
                }
            }
        } catch (IOException ex) {
            logger.warn("IOException during local file-copy cleanup: {}", ex);
            cleanupException = new IOException(ex);
        }
    }

    if (cleanupException != null) {
        throw cleanupException;
    }
    return bytesCopied;
}

From source file:org.opennms.install.Installer.java

/**
 * <p>copyFile</p>//from ww w  . j a v a 2s. c o m
 *
 * @param source a {@link java.lang.String} object.
 * @param destination a {@link java.lang.String} object.
 * @param description a {@link java.lang.String} object.
 * @param recursive a boolean.
 * @throws java.lang.Exception if any.
 */
public void copyFile(String source, String destination, String description, boolean recursive)
        throws Exception {
    File sourceFile = new File(source);
    File destinationFile = new File(destination);

    if (!sourceFile.exists()) {
        throw new Exception("source file (" + source + ") does not exist!");
    }
    if (!sourceFile.isFile()) {
        throw new Exception("source file (" + source + ") is not a file!");
    }
    if (!sourceFile.canRead()) {
        throw new Exception("source file (" + source + ") is not readable!");
    }
    if (destinationFile.exists()) {
        System.out.print("  - " + destination + " exists, removing... ");
        if (destinationFile.delete()) {
            System.out.println("REMOVED");
        } else {
            System.out.println("FAILED");
            throw new Exception("unable to delete existing file: " + sourceFile);
        }
    }

    System.out.print("  - copying " + source + " to " + destination + "... ");
    if (!destinationFile.getParentFile().exists()) {
        if (!destinationFile.getParentFile().mkdirs()) {
            throw new Exception("unable to create directory: " + destinationFile.getParent());
        }
    }
    if (!destinationFile.createNewFile()) {
        throw new Exception("unable to create file: " + destinationFile);
    }
    FileChannel from = null;
    FileInputStream fisFrom = null;
    FileChannel to = null;
    FileOutputStream fisTo = null;
    try {
        fisFrom = new FileInputStream(sourceFile);
        from = fisFrom.getChannel();
        fisTo = new FileOutputStream(destinationFile);
        to = fisTo.getChannel();
        to.transferFrom(from, 0, from.size());
    } catch (FileNotFoundException e) {
        throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e);
    } finally {
        IOUtils.closeQuietly(fisTo);
        IOUtils.closeQuietly(to);
        IOUtils.closeQuietly(fisFrom);
        IOUtils.closeQuietly(from);
    }
    System.out.println("DONE");
}

From source file:org.apache.carbondata.core.datastore.filesystem.LocalCarbonFile.java

/**
 * This method will delete the data in file data from a given offset
 *///from w  w w. j  a v  a  2 s  . c  om
@Override
public boolean truncate(String fileName, long validDataEndOffset) {
    FileChannel source = null;
    FileChannel destination = null;
    boolean fileTruncatedSuccessfully = false;
    // temporary file name
    String tempWriteFilePath = fileName + CarbonCommonConstants.TEMPWRITEFILEEXTENSION;
    FileFactory.FileType fileType = FileFactory.getFileType(fileName);
    try {
        CarbonFile tempFile = null;
        // delete temporary file if it already exists at a given path
        if (FileFactory.isFileExist(tempWriteFilePath, fileType)) {
            tempFile = FileFactory.getCarbonFile(tempWriteFilePath, fileType);
            tempFile.delete();
        }
        // create new temporary file
        FileFactory.createNewFile(tempWriteFilePath, fileType);
        tempFile = FileFactory.getCarbonFile(tempWriteFilePath, fileType);
        source = new FileInputStream(fileName).getChannel();
        destination = new FileOutputStream(tempWriteFilePath).getChannel();
        long read = destination.transferFrom(source, 0, validDataEndOffset);
        long totalBytesRead = read;
        long remaining = validDataEndOffset - totalBytesRead;
        // read till required data offset is not reached
        while (remaining > 0) {
            read = destination.transferFrom(source, totalBytesRead, remaining);
            totalBytesRead = totalBytesRead + read;
            remaining = remaining - totalBytesRead;
        }
        CarbonUtil.closeStreams(source, destination);
        // rename the temp file to original file
        tempFile.renameForce(fileName);
        fileTruncatedSuccessfully = true;
    } catch (IOException e) {
        LOGGER.error("Exception occured while truncating the file " + e.getMessage(), e);
    } finally {
        CarbonUtil.closeStreams(source, destination);
    }
    return fileTruncatedSuccessfully;
}

From source file:com.healthmarketscience.jackcess.Database.java

/**
 * Copies the given InputStream to the given channel using the most
 * efficient means possible.//w  ww  .  ja  v  a2 s  .  c om
 */
private static void transferFrom(FileChannel channel, InputStream in) throws IOException {
    ReadableByteChannel readChannel = Channels.newChannel(in);
    if (!BROKEN_NIO) {
        // sane implementation
        channel.transferFrom(readChannel, 0, MAX_EMPTYDB_SIZE);
    } else {
        // do things the hard way for broken vms
        ByteBuffer bb = ByteBuffer.allocate(8096);
        while (readChannel.read(bb) >= 0) {
            bb.flip();
            channel.write(bb);
            bb.clear();
        }
    }
}

From source file:com.odoo.core.orm.OModel.java

public void exportDB() {
    FileChannel source;// w ww . ja va2  s  .c om
    FileChannel destination;
    String currentDBPath = getDatabaseLocalPath();
    String backupDBPath = OStorageUtils.getDirectoryPath("file") + "/" + getDatabaseName();
    File currentDB = new File(currentDBPath);
    File backupDB = new File(backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        String subject = "Database Export: " + getDatabaseName();
        Uri uri = Uri.fromFile(backupDB);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.setType("message/rfc822");
        mContext.startActivity(intent);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.bluexml.xforms.controller.alfresco.agents.MappingAgent.java

/**
 * Copies the content of a source file to a target file.
 * /*from   w  ww . ja  va  2  s . c o  m*/
 * @param sourceFile
 *            the source file
 * @param targetFile
 *            the target file
 * 
 * @throws ServletException
 *             the alfresco controller exception
 */
private void copyFile(File sourceFile, File targetFile) throws ServletException {
    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    try {
        try {
            srcChannel = new FileInputStream(sourceFile).getChannel();
            dstChannel = new FileOutputStream(targetFile).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        } catch (IOException e) {
            throw new ServletException(e);
        } finally {
            if (srcChannel != null)
                srcChannel.close();
            if (dstChannel != null)
                dstChannel.close();
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.ehdev.chronos.lib.Chronos.java

@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
    try {/*from w  w  w.ja v a2s. com*/
        Log.w(TAG, "Upgrading database, this will drop tables and recreate.");
        Log.w(TAG, "oldVerion: " + oldVersion + "\tnewVersion: " + newVersion);

        //Back up database
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();
            if (sd.canWrite()) {
                String currentDBPath = "/data/com.kopysoft.chronos/databases/" + DATABASE_NAME;
                String backupDBPath = DATABASE_NAME + ".db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);
                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "ERROR: Can not move file");
        }

        /*
        db.execSQL("CREATE TABLE " + TABLE_NAME_CLOCK +
            " ( _id INTEGER PRIMARY KEY NOT NULL, time LONG NOT NULL, actionReason INTEGER NOT NULL )");
        db.execSQL("CREATE TABLE " + TABLE_NAME_NOTE +
            " ( _id LONG PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )");
        */

        if (oldVersion < 15) {

            DateTime jobMidnight = DateTime.now().withDayOfWeek(7).minusWeeks(1).toDateMidnight().toDateTime()
                    .withZone(DateTimeZone.getDefault());
            Job currentJob = new Job("", 10, jobMidnight, PayPeriodDuration.TWO_WEEKS);

            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(gContext);
            currentJob.setPayRate(Float.valueOf(pref.getString("normal_pay", "7.25")));
            currentJob.setOvertime(Float.valueOf(pref.getString("over_time_threshold", "40")));
            currentJob.setDoubletimeThreshold(Float.valueOf(pref.getString("double_time_threshold", "60")));
            SharedPreferences.Editor edit = pref.edit();
            edit.remove("8_or_40_hours"); //Moved from string to boolean
            edit.commit();
            String date[] = pref.getString("date", "2011.1.17").split("\\p{Punct}");
            jobMidnight = new DateTime(Integer.parseInt(date[0]), Integer.parseInt(date[1]),
                    Integer.parseInt(date[2]), 0, 0);

            currentJob.setStartOfPayPeriod(jobMidnight.withZone(DateTimeZone.getDefault()));

            List<Punch> punches = new LinkedList<Punch>();
            List<Task> tasks = new LinkedList<Task>();
            List<Note> notes = new LinkedList<Note>();

            Task newTask; //Basic element
            newTask = new Task(currentJob, 0, "Regular");
            tasks.add(newTask);
            newTask = new Task(currentJob, 1, "Lunch Break");
            newTask.setEnablePayOverride(true);
            newTask.setPayOverride(-7.25f);
            tasks.add(newTask);
            newTask = new Task(currentJob, 2, "Other Break");
            newTask.setEnablePayOverride(true);
            newTask.setPayOverride(-7.25f);
            tasks.add(newTask);
            newTask = new Task(currentJob, 3, "Travel");
            tasks.add(newTask);
            newTask = new Task(currentJob, 4, "Admin");
            tasks.add(newTask);
            newTask = new Task(currentJob, 5, "Sick Leave");
            tasks.add(newTask);
            newTask = new Task(currentJob, 6, "Personal Time");
            tasks.add(newTask);
            newTask = new Task(currentJob, 7, "Other");
            tasks.add(newTask);
            newTask = new Task(currentJob, 8, "Holiday Pay");
            tasks.add(newTask);

            Cursor cursor = db.query("clockactions", null, null, null, null, null, "_id desc");

            final int colTime = cursor.getColumnIndex("time");
            final int colAR = cursor.getColumnIndex("actionReason");

            if (cursor.moveToFirst()) {
                do {
                    long time = cursor.getLong(colTime);
                    Task type = tasks.get(0);
                    if (colAR != -1) {
                        type = tasks.get(cursor.getInt(colAR));
                    }
                    punches.add(new Punch(currentJob, type, new DateTime(time)));

                } while (cursor.moveToNext());
            }

            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }

            cursor = db.query("notes", null, null, null, null, null, "_id desc");

            final int colInsertTime = cursor.getColumnIndex("time");
            final int colText = cursor.getColumnIndex("note_string");

            if (cursor.moveToFirst()) {
                do {
                    long time = cursor.getLong(colInsertTime);
                    String note = cursor.getString(colText);
                    notes.add(new Note(new DateTime(time), currentJob, note));

                } while (cursor.moveToNext());
            }

            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }

            db.execSQL("DROP TABLE IF EXISTS clockactions");
            db.execSQL("DROP TABLE IF EXISTS notes");
            db.execSQL("DROP TABLE IF EXISTS misc");

            //Recreate DB
            TableUtils.createTable(connectionSource, Punch.class); //Punch - Create Table
            TableUtils.createTable(connectionSource, Task.class); //Task - Create Table
            TableUtils.createTable(connectionSource, Job.class); //Job - Create Table
            TableUtils.createTable(connectionSource, Note.class); //Task - Create Table

            //recreate entries
            Dao<Task, String> taskDAO = getTaskDao();
            Dao<Job, String> jobDAO = getJobDao();
            Dao<Note, String> noteDAO = getNoteDao();
            Dao<Punch, String> punchDOA = getPunchDao();

            jobDAO.create(currentJob);

            for (Task t : tasks) {
                taskDAO.create(t);
            }

            for (Note n : notes) {
                noteDAO.create(n);
            }

            for (Punch p : punches) {
                punchDOA.create(p);
            }

            //"CREATE TABLE " + TABLE_NAME_NOTE " ( _id LONG PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )");
        } else if (oldVersion == 15) {

            //Drop
            //DB - 15
            //TableUtils.dropTable(connectionSource, Punch.class, true); //Punch - Drop all
            //TableUtils.dropTable(connectionSource, Task.class, true); //Task - Drop all
            //TableUtils.dropTable(connectionSource, Job.class, true); //Job - Drop all
            //TableUtils.dropTable(connectionSource, Note.class, true); //Note - Drop all
            Dao<Task, String> taskDAO = getTaskDao();
            List<Task> tasks = taskDAO.queryForAll();

            db.execSQL("DROP TABLE IF EXISTS tasks");

            //create
            TableUtils.createTable(connectionSource, Task.class); //Task - Create Table

            for (Task t : tasks) {
                taskDAO.create(t);
            }
        } else if (oldVersion == 16) {

            //Drop
            //DB - 15
            //TableUtils.dropTable(connectionSource, Punch.class, true); //Punch - Drop all
            //TableUtils.dropTable(connectionSource, Task.class, true); //Task - Drop all
            //TableUtils.dropTable(connectionSource, Job.class, true); //Job - Drop all
            TableUtils.dropTable(connectionSource, Note.class, true); //Note - Drop all

            //create
            TableUtils.createTable(connectionSource, Note.class); //Task - Create Table

        } else if (oldVersion == 17) {

            //update db from old version
            Dao<Job, String> dao = getJobDao();
            dao.executeRaw("ALTER TABLE `jobs` ADD COLUMN fourtyHourWeek BOOLEAN DEFAULT 1;");

        } else if (oldVersion == 18) {

            Dao<Task, String> taskDAO = getTaskDao();
            List<Task> tasks = taskDAO.queryForAll();
            Job currentJob = getAllJobs().get(0);
            if (tasks.size() == 0) {

                Task newTask; //Basic element
                newTask = new Task(currentJob, 0, "Regular");
                tasks.add(newTask);
                newTask = new Task(currentJob, 1, "Lunch Break");
                newTask.setEnablePayOverride(true);
                newTask.setPayOverride(-7.25f);
                tasks.add(newTask);
                newTask = new Task(currentJob, 2, "Other Break");
                newTask.setEnablePayOverride(true);
                newTask.setPayOverride(-7.25f);
                tasks.add(newTask);
                newTask = new Task(currentJob, 3, "Travel");
                tasks.add(newTask);
                newTask = new Task(currentJob, 4, "Admin");
                tasks.add(newTask);
                newTask = new Task(currentJob, 5, "Sick Leave");
                tasks.add(newTask);
                newTask = new Task(currentJob, 6, "Personal Time");
                tasks.add(newTask);
                newTask = new Task(currentJob, 7, "Other");
                tasks.add(newTask);
                newTask = new Task(currentJob, 8, "Holiday Pay");
                tasks.add(newTask);

                for (Task t : tasks) {
                    taskDAO.createOrUpdate(t);
                }
            }
        } else if (oldVersion == 19) {

            try {
                TableUtils.dropTable(connectionSource, Job.class, true); //Job - Create Table

                TableUtils.createTable(connectionSource, Job.class); //Job - Create Table

                DateTime jobMidnight = new DateMidnight().toDateTime().minusWeeks(1)
                        .withZone(DateTimeZone.getDefault());

                Job thisJob = new Job("", 7.25f, jobMidnight, PayPeriodDuration.TWO_WEEKS);

                SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(gContext);
                try {
                    thisJob.setPayRate(Float.valueOf(pref.getString("normal_pay", "7.25")));
                } catch (NumberFormatException e) {
                    thisJob.setPayRate(7.25f);
                    Log.d(TAG, e.getMessage());
                }

                try {
                    thisJob.setOvertime(Float.valueOf(pref.getString("over_time_threshold", "40")));
                } catch (NumberFormatException e) {
                    thisJob.setOvertime(40f);
                    Log.d(TAG, e.getMessage());
                }

                try {
                    thisJob.setDoubletimeThreshold(
                            Float.valueOf(pref.getString("double_time_threshold", "60")));
                } catch (NumberFormatException e) {
                    thisJob.setDoubletimeThreshold(60f);
                    Log.d(TAG, e.getMessage());
                }

                String date[] = pref.getString("date", "2011.1.17").split("\\p{Punct}");
                String time[] = pref.getString("time", "00:00").split("\\p{Punct}");
                thisJob.setStartOfPayPeriod(new DateTime(Integer.parseInt(date[0]), Integer.parseInt(date[1]),
                        Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1])));
                switch (Integer.parseInt(pref.getString("len_of_month", "2"))) {
                case 1:
                    thisJob.setDuration(PayPeriodDuration.ONE_WEEK);
                    break;
                case 2:
                    thisJob.setDuration(PayPeriodDuration.TWO_WEEKS);
                    break;
                case 3:
                    thisJob.setDuration(PayPeriodDuration.THREE_WEEKS);
                    break;
                case 4:
                    thisJob.setDuration(PayPeriodDuration.FOUR_WEEKS);
                    break;
                case 5:
                    thisJob.setDuration(PayPeriodDuration.FULL_MONTH);
                    break;
                case 6:
                    thisJob.setDuration(PayPeriodDuration.FIRST_FIFTEENTH);
                    break;
                default:
                    thisJob.setDuration(PayPeriodDuration.TWO_WEEKS);
                    break;
                }

                getJobDao().create(thisJob);

            } catch (SQLException e1) {
                e1.printStackTrace();
            }

        } else if (oldVersion == 20) {
            getJobDao().executeRaw(
                    "ALTER TABLE 'jobs' ADD COLUMN '" + Job.OVERTIME_OPTIONS + "'  VARCHAR default 'NONE';");
            getJobDao().executeRaw("ALTER TABLE 'jobs' ADD COLUMN '" + Job.SATURDAY_OVERRIDE_FIELD
                    + "'  VARCHAR default 'NONE';");
            getJobDao().executeRaw("ALTER TABLE 'jobs' ADD COLUMN '" + Job.SUNDAY_OVERRIDE_FIELD
                    + "'  VARCHAR default 'NONE';");
            List<Job> jobList = getAllJobs();
            for (Job job : jobList) {
                GenericRawResults<String[]> rawResults = getJobDao().queryRaw(
                        "select fourtyHourWeek,overTimeEnabled  from jobs where job_id = " + job.getID());
                String[] results = rawResults.getResults().get(0);
                if (results[0] == "0") {
                    job.setOvertimeOptions(OvertimeOptions.NONE);
                } else {
                    if (results[1] == "0") {
                        job.setOvertimeOptions(OvertimeOptions.DAY);
                    } else if (results[1] == "1") { //being paranoid
                        job.setOvertimeOptions(OvertimeOptions.WEEK);
                    }
                }
            }

            //delete stuff
            getJobDao().executeRaw("ALTER TABLE 'jobs' DROP COLUMN 'fourtyHourWeek';");
            getJobDao().executeRaw("ALTER TABLE 'jobs' DROP COLUMN 'overTimeEnabled';");
        }

    } catch (SQLException e) {
        e.printStackTrace();
        Log.e(TAG, "Could not upgrade the table for Thing", e);
    }
}

From source file:org.wso2.developerstudio.eclipse.registry.apim.views.RegistryBrowserAPIMView.java

private void copyFileToFile(File source, File dest) throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {//from  w w  w  .  j  a va 2 s . c  o  m
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}