Example usage for java.io File setExecutable

List of usage examples for java.io File setExecutable

Introduction

In this page you can find the example usage for java.io File setExecutable.

Prototype

public boolean setExecutable(boolean executable) 

Source Link

Document

A convenience method to set the owner's execute permission for this abstract pathname.

Usage

From source file:com.github.sakserv.minicluster.yarn.InJvmContainerExecutor.java

/**
 * This method does three things 1. It creates an updated version of the
 * initial launch script where it simply copies its contents less the 'exec'
 * line 2. It extract the 'exec' line and returns it so the Container's class
 * name and launch arguments could be retrieved. 3. It executes the
 * 'exec'-less launch script to ensure that all symlinks and other prepwork
 * expected by the underlying container is performed.
 *
 * @param containerWorkDir/*from   www  .j av  a  2 s.  co  m*/
 * @return
 */
private String filterAndExecuteLaunchScriptAndReturnExecLine(String containerWorkDir) {
    BufferedReader reader = null;
    BufferedWriter writer = null;
    String execLine = null;
    File inJvmlaunchScript = null;
    try {
        File launchScript = new File(containerWorkDir, "launch_container.sh");
        inJvmlaunchScript = new File(containerWorkDir.toString(), "injvm_launch_container.sh");
        inJvmlaunchScript.setExecutable(true);
        reader = new BufferedReader(new FileReader(launchScript));
        writer = new BufferedWriter(new FileWriter(inJvmlaunchScript));

        String line;
        while ((line = reader.readLine()) != null) {
            if (!line.startsWith("exec")) {
                writer.write(line);
                writer.write("\n");
            } else {
                execLine = line;
            }
        }
    } catch (Exception e) {
        throw new IllegalStateException("Failed to override default launch script", e);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            // ignore
        }
        try {
            writer.close();
        } catch (IOException e) {
            // ignore
        }
    }
    if (inJvmlaunchScript != null) {
        try {
            inJvmlaunchScript.setExecutable(true);
            Process process = Runtime.getRuntime().exec(inJvmlaunchScript.getAbsolutePath());
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new IllegalStateException("Failed to execute launch script.  Exit code: " + exitCode);
            }
        } catch (Exception e) {
            throw new IllegalStateException("Failed to execute " + inJvmlaunchScript.getAbsolutePath(), e);
        }
    }
    return execLine;
}

From source file:com.liferay.blade.cli.CreateCommand.java

public void execute() throws Exception {
    if (_options.listtemplates()) {
        listTemplates();// w  ww  . jav  a2  s .  c o  m
        return;
    }

    List<String> args = _options._arguments();

    String template = _options.template();

    if (template == null) {
        template = "mvcportlet";
    } else if (!isExistingTemplate(template)) {
        addError("Create", "the template " + template + " is not in the list");
        return;
    }

    String name = args.remove(0);
    final File dir = _options.dir() != null ? _options.dir() : getDefaultDir();
    final File workDir = Processor.getFile(dir, name);

    if (!checkDir(workDir)) {
        addError("Create",
                name + " is not empty or it is a file." + " Please clean or delete it then run again");
        return;
    }

    final boolean isWorkspace = Util.isWorkspace(dir);

    name = workDir.getName();

    final Pattern glob = Pattern.compile("^standalone/" + template + "/.*|\\...+/.*");

    final Map<String, String> subs = new HashMap<>();
    subs.put("templates/standalone/" + template + "/", "");
    subs.put("_project_path_", workDir.getAbsolutePath());
    subs.put("_name_", getPackageName(name));
    subs.put("_NAME_", name);

    final String packageName = _options.packagename();

    if (isEmpty(packageName)) {
        subs.put("_package_path_", getPackageName(name).replaceAll("\\.", "/"));
        subs.put("_package_", getPackageName(name));
    } else {
        subs.put("_package_path_", packageName.replaceAll("\\.", "/"));
        subs.put("_package_", packageName);
    }

    String classname = _options.classname();

    if (isEmpty(classname)) {
        classname = getClassName(name);
    }

    String service = _options.service();

    if ("service".equals(template)) {
        if (isEmpty(service)) {
            addError("Create",
                    "The service template requires the fully qualified name "
                            + "of service must be specified after the service "
                            + "argument.\nFor example: blade create -t service -s "
                            + "com.liferay.portal.kernel.events.LifecycleAction " + "customPreAction");
            return;
        }

        subs.put("_SERVICE_FULL_", service);
        subs.put("_SERVICE_SHORT_", service.substring(service.lastIndexOf('.') + 1));
    }

    if ("servicewrapper".equals(template)) {
        if (isEmpty(service)) {
            addError("Create",
                    "The servicewrapper template requires the fully qualified"
                            + " name of service must be specified after the service"
                            + " argument.\nFor example: blade create -t " + "servicewrapper -s "
                            + "com.liferay.portal.service.UserLocalServiceWrapper " + "customServiceWrapper");
            return;
        }

        subs.put("_SERVICE_FULL_", service);
        subs.put("_SERVICE_SHORT_", service.substring(service.lastIndexOf('.') + 1));
    }

    if ("servicebuilder".equals(template)) {
        if (isEmpty(packageName)) {
            addError("Create",
                    "The servicebuilder template requires the name of the "
                            + "root package within which to create service builder "
                            + "classes must be specified.\nFor example: blade " + "create -t servicebuilder -p "
                            + "com.liferay.guestbook guestbook");
            return;
        }

        if (name.indexOf(".") > -1) {
            subs.put("_api_", packageName + ".api");
            subs.put("_service_", packageName + ".svc");
            subs.put("_web_", packageName + ".web");
        } else {
            subs.put("_api_", name + "-api");
            subs.put("_service_", name + "-service");
            subs.put("_web_", name + "-web");
        }

        if (isWorkspace) {
            final Path workspacePath = Util.getWorkspaceDir(dir).getAbsoluteFile().toPath();

            final Path dirPath = dir.getAbsoluteFile().toPath();

            final String relativePath = workspacePath.relativize(dirPath).toString();

            final String apiPath = ":" + relativePath.replaceAll("\\\\", "/").replaceAll("\\/", ":") + ":"
                    + name;

            subs.put("_api_path_", apiPath);
        } else {
            subs.put("_api_path_", "");
        }

        subs.put("_portlet_", packageName + ".portlet");
        subs.put("_portletpackage_", packageName.replaceAll("\\.", "/") + "/portlet");
    } else if ("activator".equals(template)) {
        if (!classname.contains("Activator")) {
            classname += "Activator";
        }
    }

    if ("portlet".equals(template) || "mvcportlet".equals(template)) {
        if (classname.endsWith("Portlet")) {
            classname = classname.replaceAll("Portlet$", "");
        }
    }

    final String hostbundlebsn = _options.hostbundlebsn();

    final String hostbundleversion = _options.hostbundleversion();

    if ("fragment".equals(template)) {
        if (isEmpty(hostbundlebsn) || isEmpty(hostbundleversion)) {
            addError("Create", "The fragment template requires the bundle symbolic name "
                    + "of the hostbundle and version must be specified.\n"
                    + "For example: blade create -t fragment -h " + "com.liferay.login.web -H 1.0.0 name");
            return;
        }

        subs.put("_HOST_BUNDLE_BSN_", hostbundlebsn);
        subs.put("_HOST_BUNDLE_VERSION_", hostbundleversion);
    }

    subs.put("_CLASS_", classname);

    String unNormalizedPortletFqn = name.toLowerCase().replaceAll("-", ".") + "_" + classname;

    subs.put("_portlet_fqn_", unNormalizedPortletFqn.replaceAll("\\.", "_"));

    File moduleTemplatesZip = getGradleTemplatesZip();

    InputStream in = new FileInputStream(moduleTemplatesZip);

    copy("standalone", template, workDir, in, glob, true, subs);

    in.close();

    if (isWorkspace) {
        final Pattern buildGlob = Pattern.compile("^workspace/" + template + "/.*|\\...+/.*");

        in = new FileInputStream(moduleTemplatesZip);

        copy("workspace", template, workDir, in, buildGlob, true, subs);

        in.close();

        File settingsFile = new File(workDir, "settings.gradle");

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

        IO.delete(new File(workDir, "gradlew"));
        IO.delete(new File(workDir, "gradlew.bat"));
        IO.delete(new File(workDir, "gradle"));
    } else {
        File gradlew = new File(workDir, "gradlew");

        if (gradlew.exists()) {
            gradlew.setExecutable(true);
        }
    }

    _blade.out().println("Created the project " + name + " using the " + template + " template in " + workDir);
}

From source file:org.jajuk.services.startup.StartupCollectionService.java

/**
 * Registers supported audio supports and default properties.
 *//*from   w w w .  ja v  a  2s . c  o  m*/
public static void registerTypes() {
    try {
        // test mplayer presence in PATH
        mplayerStatus = UtilSystem.MPlayerStatus.MPLAYER_STATUS_OK;
        if (UtilSystem.isUnderWindows()) {
            final File mplayerPath = UtilSystem.getMPlayerWindowsPath();
            // try to find mplayer executable in know locations first
            if (mplayerPath == null) {
                try {
                    Log.debug("Download Mplayer from: " + Const.URL_MPLAYER_WINDOWS);
                    File fMPlayer = SessionService.getConfFileByPath(Const.FILE_MPLAYER_WINDOWS_EXE);
                    DownloadManager.download(new URL(Const.URL_MPLAYER_WINDOWS), fMPlayer);
                    // make sure to delete corrupted mplayer in case of
                    // download problem
                    if (fMPlayer.length() != Const.MPLAYER_WINDOWS_EXE_SIZE) {
                        if (!fMPlayer.delete()) { //NOSONAR
                            Log.warn("Could not delete file " + fMPlayer);
                        }
                        mplayerStatus = UtilSystem.MPlayerStatus.MPLAYER_STATUS_JNLP_DOWNLOAD_PBM;
                    }
                } catch (IOException e) {
                    mplayerStatus = UtilSystem.MPlayerStatus.MPLAYER_STATUS_JNLP_DOWNLOAD_PBM;
                }
            }
        } else if (UtilSystem.isUnderOSX()) {
            final File mplayerPath = UtilSystem.getMPlayerOSXPath();
            // try to find mplayer executable in known locations first
            if (mplayerPath == null) {
                try {
                    Log.debug("Download Mplayer from: " + Const.URL_MPLAYER_OSX);
                    File fMPlayer = SessionService.getConfFileByPath(Const.FILE_MPLAYER_OSX_EXE);
                    DownloadManager.download(new URL(Const.URL_MPLAYER_OSX), fMPlayer);
                    fMPlayer.setExecutable(true);
                    if (fMPlayer.length() != Const.MPLAYER_OSX_EXE_SIZE) {
                        if (!fMPlayer.delete()) { //NOSONAR
                            Log.warn("Could not delete file " + fMPlayer);
                        }
                        mplayerStatus = UtilSystem.MPlayerStatus.MPLAYER_STATUS_JNLP_DOWNLOAD_PBM;
                    }
                } catch (IOException e) {
                    mplayerStatus = UtilSystem.MPlayerStatus.MPLAYER_STATUS_JNLP_DOWNLOAD_PBM;
                }
            }
        }
        // Under others OS, we assume mplayer has been installed
        // using external standard distributions
        else {
            // If a forced mplayer path is defined, test it
            final String forced = Conf.getString(Const.CONF_MPLAYER_PATH_FORCED);
            if (!StringUtils.isBlank(forced)) {
                // Test forced path
                mplayerStatus = UtilSystem.getMplayerStatus(forced);
            } else {
                mplayerStatus = UtilSystem.MPlayerStatus.MPLAYER_STATUS_NOT_FOUND;
            }
            if (mplayerStatus != UtilSystem.MPlayerStatus.MPLAYER_STATUS_OK) {
                // try to find a correct mplayer from the path
                mplayerStatus = UtilSystem.getMplayerStatus("");
            }
        }
        // Choose player according to mplayer presence or not
        if (mplayerStatus != UtilSystem.MPlayerStatus.MPLAYER_STATUS_OK) {
            // No mplayer, show mplayer warnings
            Log.debug("Mplayer status=" + mplayerStatus);
            if (mplayerStatus != UtilSystem.MPlayerStatus.MPLAYER_STATUS_OK) {
                // Test if user didn't already select "don't show again"
                if (!Conf.getBoolean(Const.CONF_NOT_SHOW_AGAIN_PLAYER)) {
                    if (mplayerStatus == UtilSystem.MPlayerStatus.MPLAYER_STATUS_NOT_FOUND) {
                        // No mplayer
                        Messages.showHideableWarningMessage(Messages.getString("Warning.0"),
                                Const.CONF_NOT_SHOW_AGAIN_PLAYER);
                    } else if (mplayerStatus == UtilSystem.MPlayerStatus.MPLAYER_STATUS_WRONG_VERSION) {
                        // wrong mplayer release
                        Messages.showHideableWarningMessage(Messages.getString("Warning.1"),
                                Const.CONF_NOT_SHOW_AGAIN_PLAYER);
                    }
                } else if (mplayerStatus == UtilSystem.MPlayerStatus.MPLAYER_STATUS_JNLP_DOWNLOAD_PBM) {
                    // wrong mplayer release
                    Messages.showHideableWarningMessage(Messages.getString("Warning.3"),
                            Const.CONF_NOT_SHOW_AGAIN_PLAYER);
                }
            }
            TypeManager.registerTypesNoMplayer();
        } else { // mplayer enabled
            TypeManager.registerTypesMplayerAvailable();
        }
    } catch (final ClassNotFoundException e1) {
        Log.error(26, e1);
    }
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Extract scripts to bin dir/*from   w w  w  .j a  v  a 2  s . c  om*/
 *
 * @param destDir
 */
private void extractBin(final File destDir, final File coreJar) throws IOException {
    if (!destDir.isDirectory()) {
        if (!destDir.mkdirs()) {
            ERR("Couldn't create bin dir: " + destDir.getAbsolutePath());
            return;
        }
    }
    ZipUtil.extractZip(coreJar.getAbsolutePath(), destDir, "com/dtolabs/rundeck/core/cli/templates",
            "com/dtolabs/rundeck/core/cli/templates/");

    //set executable on shell scripts
    for (final String s : destDir.list(new FilenameFilter() {
        public boolean accept(final File file, final String s) {
            return !s.endsWith(".bat");
        }
    })) {
        final File script = new File(destDir, s);
        if (!script.setExecutable(true)) {
            ERR("Unable to set executable permissions for file: " + script.getAbsolutePath());
        }
    }
}

From source file:com.clough.android.adbv.manager.ADBManager.java

/**
 * Copying the file by the given file name from the source directory 
 * to application's directory/*w  w  w  .  j a  v a  2  s  . co  m*/
 * @param sourceFilePath Source file path depending on the OS
 * @param fileName Name of the file in the sourceFilePath to be copied
 * @return Absolute file path to the copied file
 * @throws IOException
 * @throws ADBManagerException 
 */
private String copyAssets(String sourceFilePath, String fileName) throws IOException, ADBManagerException {
    File out = new File(APPLICATION_FILE, fileName);
    if (!out.exists()) {
        InputStream fis = Launcher.class.getResourceAsStream(sourceFilePath + fileName);
        if (fis != null) {
            FileOutputStream fos = new FileOutputStream(out);
            int read;
            while ((read = fis.read()) != -1) {
                fos.write(read);
            }
            fos.flush();
            fis.close();
            fos.close();
        }
    }
    if (!out.setExecutable(true)) {
        throw new ADBManagerException("Copied ADB file couldn't make executable");
    }
    return out.getAbsolutePath();

}

From source file:org.kei.android.phone.netcap.OutputFragment.java

@Override
public void onClick(final View v) {
    if (v.equals(refreshBT)) {
        adapter.clear();/*from  w  w  w  . j a v  a2  s  .c om*/
        try {
            final List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            if (interfaces != null && interfaces.size() != 0)
                adapter.add(getResources().getText(R.string.any).toString());
            for (final NetworkInterface ni : interfaces)
                if (ni.isUp())
                    adapter.add(ni.getName());
        } catch (final Throwable e) {
            logException(e);
        }
    } else if (v.equals(browseOutputCaptureTV)) {
        final Map<String, String> extra = new HashMap<String, String>();
        extra.put(FileChooser.FILECHOOSER_TYPE_KEY, "" + FileChooser.FILECHOOSER_TYPE_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_TITLE_KEY, "Save");
        extra.put(FileChooser.FILECHOOSER_MESSAGE_KEY, "Use this folder:? ");
        extra.put(FileChooser.FILECHOOSER_DEFAULT_DIR, browseOutputCaptureTV.getText().toString());
        extra.put(FileChooser.FILECHOOSER_SHOW_KEY, "" + FileChooser.FILECHOOSER_SHOW_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_USER_MESSAGE, getClass().getSimpleName());
        Tools.switchToForResult(owner, FileChooserActivity.class, extra,
                FileChooserActivity.FILECHOOSER_SELECTION_TYPE_DIRECTORY);

    } else if (v.equals(captureBT)) {
        if (!captureBT.isChecked()) {
            captureBT.setChecked(true);
            delete();
        } else {
            String sdest = browseOutputCaptureTV.getText().toString();
            if (sdest.isEmpty()) {
                Tools.showAlertDialog(owner, "Error", "Empty destination folder!");
                captureBT.setChecked(false);
                return;
            }

            File legacy = new File(sdest.replaceFirst("emulated/([0-9]+)/", "emulated/legacy/"));
            File fdest = new File(sdest);
            Log.i(getClass().getSimpleName(), "Test directory '" + legacy + "'");
            if (legacy.isDirectory())
                fdest = legacy;
            if (!fdest.isDirectory()) {
                Tools.showAlertDialog(owner, "Error", "The destination folder is not a valid directory!");
                captureBT.setChecked(false);
                return;
            } else if (!fdest.canWrite()) {
                Tools.showAlertDialog(owner, "Error", "Unable to write into the destination folder!");
                captureBT.setChecked(false);
                return;
            }

            if (!RootTools.isAccessGiven()) {
                Resources r = getResources();
                Tools.toast(owner, R.drawable.ic_launcher, r.getString(R.string.root_toast_error));
                showResult.setText(" " + r.getString(R.string.root_error));
                captureBT.setChecked(false);
                return;
            }

            final PackageManager m = owner.getPackageManager();
            String s = owner.getPackageName();
            try {
                final PackageInfo p = m.getPackageInfo(s, 0);
                s = p.applicationInfo.dataDir;
            } catch (final PackageManager.NameNotFoundException e) {
            }
            s = s + "/netcap";
            copyFile(Build.SUPPORTED_ABIS[0] + "/netcap", s, owner);
            final File netcap = new File(s);
            if (!netcap.exists()) {
                Tools.showAlertDialog(owner, "Error",
                        "'netcap' for '" + Build.SUPPORTED_ABIS[0] + "' was not found!");
                return;
            }
            pname = netcap.getAbsolutePath();
            netcap.setExecutable(true);

            ifaces = "";
            String ni = (String) devicesSp.getSelectedItem();
            if (ni.equals(getResources().getText(R.string.any).toString())) {
                for (int i = 0; i < adapter.getCount(); i++) {
                    ni = adapter.getItem(i);
                    if (ni.equals(getResources().getText(R.string.any).toString()))
                        continue;
                    ifaces += ni;
                    if (i < adapter.getCount() - 1)
                        ifaces += ",";
                }
            } else
                ifaces = ni;

            final File outputFile = new File(fdest,
                    new SimpleDateFormat("yyyyMMdd_hhmmssa'_netcap.pcap'", Locale.US).format(new Date()));
            buffer.clear();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String cmd = netcap.getAbsolutePath() + " -i " + ifaces + " -f "
                                + outputFile.getAbsolutePath() + " -d";
                        if (promiscuousCB.isChecked())
                            cmd += " -p";
                        cmd += " 2>&1";
                        command = new Command(0, cmd) {
                            @Override
                            public void commandOutput(int id, String line) {
                                super.commandOutput(id, line);
                                if (line.startsWith(NETCAP_READY))
                                    pid = line.substring(NETCAP_READY.length());
                                buffer.add(line);
                                owner.runOnUiThread(new Runnable() {
                                    @SuppressWarnings("unchecked")
                                    @Override
                                    public void run() {
                                        final String[] lines = (String[]) buffer.toArray(new String[] {});
                                        final StringBuilder sb = new StringBuilder();
                                        for (final String s : lines)
                                            sb.append(" ").append(s).append("\n");
                                        showResult.setText(sb.toString());
                                    }
                                });
                            }

                            public void commandCompleted(int id, int exitcode) {
                                super.commandCompleted(id, exitcode);
                                owner.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        captureBT.setChecked(false);
                                    }
                                });
                            }

                            public void commandTerminated(int id, String reason) {
                                super.commandTerminated(id, reason);
                            }
                        };
                        RootTools.getShell(true).add(command);
                    } catch (final Exception e) {
                        logException(e);
                    }
                }
            }).start();
        }
    }
}

From source file:com.buglabs.bug.ws.program.ProgramServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();

    if (path == null) {
        log.log(LogService.LOG_WARNING, "Error: null program path.");
        resp.sendError(665, "Error: invalid program path.");
        return;//from   w w w  . j ava 2s. c  o  m
    }

    String[] toks = path.split("/");

    String jarName = toks[toks.length - 1];

    File bundleDir = new File(incomingBundleDir);

    if (!bundleDir.exists()) {
        log.log(LogService.LOG_ERROR, "Unable to save bundle; can't create file.");
        resp.sendError(0, "Unable to save bundle; can't create file.");
    }

    Bundle existingBundle = findBundleByName(jarName);
    if (existingBundle != null) {
        try {
            uninstallBundle(existingBundle);
        } catch (BundleException e) {
            log.log(LogService.LOG_ERROR, "Unable to uninstall existing bundle.  Aborting install.", e);
        }
    }

    File jarFile = new File(bundleDir.getAbsolutePath() + File.separator + jarName + ".jar");
    FileOutputStream fos = new FileOutputStream(jarFile);
    IOUtils.copy(req.getInputStream(), fos);
    fos.flush();
    fos.close();
    //Tell knapsack to start the bundle.
    jarFile.setExecutable(true);

    initService.updateBundles();

    resp.getWriter().println(HTTP_OK_RESPONSE);
    req.getInputStream().close();
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Set executable bit on any script files in the directory if it exists
 * @param sbindir/*from   www .  j  a  v  a 2 s.  com*/
 */
private void setScriptFilesExecutable(final File sbindir) {
    //set executable on files
    if (sbindir.exists()) {
        for (final String s : sbindir.list()) {
            final File script = new File(sbindir, s);
            if (script.isFile() && !script.setExecutable(true)) {
                ERR("Unable to set executable permissions for file: " + script.getAbsolutePath());
            }
        }
    }
}

From source file:com.cloudera.kitten.lua.AsapLuaContainerLaunchParameters.java

private String writeExecutionScript(List<String> cmds) throws IOException {
    UUID id = UUID.randomUUID();
    String ret = "script_" + id + ".sh";
    File fout = new File("/tmp/" + ret);
    FileOutputStream fos = new FileOutputStream(fout);

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    bw.write("#!/bin/bash");
    bw.newLine();/*from ww w  .j  av  a  2 s .  co m*/
    for (String c : cmds) {
        bw.write(c);
        bw.newLine();
    }
    bw.close();
    fout.setExecutable(true);
    return ret;
}

From source file:dk.statsbiblioteket.util.Files.java

/**
 * Copies a file (not a folder).//ww w  .jav a 2s .  c  o m
 *
 * @param source      the file to copy.
 * @param destination where to copy the file to. If this is an existing
 *                    directory, {@code source} will be copied into it,
 *                    otherwise {@code source} will copied to this file.
 * @param overwrite   whether or not to overwrite if the destination
 *                    already exists.
 * @throws IOException                thrown if there was an error writing to the
 *                                    destination file, or if the input file doidn't exist
 *                                    or if the source was a directory.
 * @throws FileNotFoundException      thrown if the source file did not exist.
 * @throws FileAlreadyExistsException if there's already a file at
 *                                    {@code destination} and {@code overwrite} was
 *                                    {@code false}.
 */
private static void copyFile(File source, File destination, boolean overwrite) throws IOException {
    log.trace("copyFile(" + source + ", " + destination + ", " + overwrite + ") called");
    source = source.getAbsoluteFile();
    destination = destination.getAbsoluteFile();
    if (!source.exists()) {
        throw new FileNotFoundException("The source '" + source + "' does not exist");
    }
    if (destination.isDirectory()) {
        throw new IOException("The destination '" + destination + "' is a directory");
    }

    if (destination.exists() && destination.isDirectory()) {
        destination = new File(destination, source.getName());
    }

    if (!overwrite && destination.exists()) {
        throw new FileAlreadyExistsException(destination.toString());
    }

    // BufferedInputStream is not used, as it chokes > 2GB
    InputStream in = new FileInputStream(source);
    OutputStream out = new FileOutputStream(destination);

    try {
        byte[] buf = new byte[2028];
        int count = 0;
        while ((count = in.read(buf)) != -1) {
            out.write(buf, 0, count);
        }
    } finally {
        in.close();
        out.close();
    }
    destination.setExecutable(source.canExecute());
}