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:Main.java

public static void main(String[] args) {
    File f = new File("test.txt");

    boolean bool = f.setExecutable(true);

    System.out.println("setExecutable() succeeded?: " + bool);

    bool = f.canExecute();/*from  w w w . j  ava 2  s .c o  m*/

    System.out.print("Can execute?: " + bool);

}

From source file:org.apache.s4.tools.CreateApp.java

public static void main(String[] args) {

    final CreateAppArgs appArgs = new CreateAppArgs();
    Tools.parseArgs(appArgs, args);//from w ww.j a  v  a 2s.c  om

    if (new File(appArgs.getAppDir() + "/" + appArgs.appName.get(0)).exists()) {
        System.err.println("There is already a directory called " + appArgs.appName.get(0) + " in the "
                + appArgs.getAppDir()
                + " directory. Please specify another name for your project or specify another parent directory");
        System.exit(1);
    }
    // create project structure
    try {
        createDir(appArgs, "/src/main/java");
        createDir(appArgs, "/src/main/resources");
        createDir(appArgs, "/src/main/java/hello");

        // copy gradlew script (redirecting to s4 gradlew)
        File gradlewTempFile = File.createTempFile("gradlew", "tmp");
        gradlewTempFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/gradlew")),
                gradlewTempFile);
        String gradlewScriptContent = Files.readLines(gradlewTempFile, Charsets.UTF_8,
                new PathsReplacer(appArgs));
        Files.write(gradlewScriptContent, gradlewTempFile, Charsets.UTF_8);
        Files.copy(gradlewTempFile, new File(appArgs.getAppDir() + "/gradlew"));
        new File(appArgs.getAppDir() + "/gradlew").setExecutable(true);

        // copy build file contents
        String buildFileContents = Resources.toString(Resources.getResource("templates/build.gradle"),
                Charsets.UTF_8);
        buildFileContents = buildFileContents.replace("<s4_install_dir>",
                "'" + new File(appArgs.s4ScriptPath).getParent() + "'");
        Files.write(buildFileContents, new File(appArgs.getAppDir() + "/build.gradle"), Charsets.UTF_8);

        // copy lib
        FileUtils.copyDirectory(new File(new File(appArgs.s4ScriptPath).getParentFile(), "lib"),
                new File(appArgs.getAppDir() + "/lib"));

        // update app settings
        String settingsFileContents = Resources.toString(Resources.getResource("templates/settings.gradle"),
                Charsets.UTF_8);
        settingsFileContents = settingsFileContents.replaceFirst("rootProject.name=<project-name>",
                "rootProject.name=\"" + appArgs.appName.get(0) + "\"");
        Files.write(settingsFileContents, new File(appArgs.getAppDir() + "/settings.gradle"), Charsets.UTF_8);
        // copy hello app files
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloPE.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloPE.java"));
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloApp.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloApp.java"));
        // copy hello app adapter
        Files.copy(
                Resources.newInputStreamSupplier(Resources.getResource("templates/HelloInputAdapter.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloInputAdapter.java"));

        File s4TmpFile = File.createTempFile("s4Script", "template");
        s4TmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/s4")), s4TmpFile);

        // create s4
        String preparedS4Script = Files.readLines(s4TmpFile, Charsets.UTF_8, new PathsReplacer(appArgs));

        File s4Script = new File(appArgs.getAppDir() + "/s4");
        Files.write(preparedS4Script, s4Script, Charsets.UTF_8);
        s4Script.setExecutable(true);

        File readmeTmpFile = File.createTempFile("newApp", "README");
        readmeTmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/newApp.README")),
                readmeTmpFile);
        // display contents from readme
        Files.readLines(readmeTmpFile, Charsets.UTF_8, new LineProcessor<Boolean>() {

            @Override
            public boolean processLine(String line) throws IOException {
                if (!line.startsWith("#")) {
                    System.out.println(line.replace("<appDir>", appArgs.getAppDir()));
                }
                return true;
            }

            @Override
            public Boolean getResult() {
                return true;
            }

        });
    } catch (Exception e) {
        logger.error("Could not create project due to [{}]. Please check your configuration.", e.getMessage());
    }
}

From source file:com.sanaldiyar.projects.nanohttpd.nanoinstaller.App.java

public static void main(String[] args) {
    try {/*from www.  ja  va 2 s  .  c om*/
        String executableName = new File(
                App.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
        Options options = new Options();

        Option destination = OptionBuilder.withArgName("folder").withLongOpt("destination").hasArgs(1)
                .withDescription("destionation folder").withType(String.class).create("d");

        Option lrfolder = OptionBuilder.withArgName("folder").withLongOpt("localrepo").hasArgs(1)
                .withDescription("local repository folder").withType(String.class).create("lr");

        Option rmlrfolder = OptionBuilder.withLongOpt("deletelocalrepo").hasArg(false)
                .withDescription("delete local repository after installation").create("dlr");

        Option help = OptionBuilder.withLongOpt("help").withDescription("print this help").create("h");

        options.addOption(destination);
        options.addOption(lrfolder);
        options.addOption(rmlrfolder);
        options.addOption(help);

        HelpFormatter helpFormatter = new HelpFormatter();

        CommandLineParser commandLineParser = new PosixParser();
        CommandLine commands;
        try {
            commands = commandLineParser.parse(options, args);
        } catch (ParseException ex) {
            System.out.println("Error at parsing arguments");
            helpFormatter.printHelp("java -jar " + executableName, options);
            return;
        }

        if (commands.hasOption("h")) {
            helpFormatter.printHelp("java -jar " + executableName, options);
            return;
        }

        String sdest = commands.getOptionValue("d", "./nanosystem");
        System.out.println("The nano system will be installed into " + sdest);
        File dest = new File(sdest);
        if (dest.exists()) {
            FileUtils.deleteDirectory(dest);
        }
        dest.mkdirs();
        File bin = new File(dest, "bin");
        bin.mkdir();
        File bundle = new File(dest, "bundle");
        bundle.mkdir();
        File conf = new File(dest, "conf");
        conf.mkdir();
        File core = new File(dest, "core");
        core.mkdir();
        File logs = new File(dest, "logs");
        logs.mkdir();
        File nanohttpdcore = new File(dest, "nanohttpd-core");
        nanohttpdcore.mkdir();
        File nanohttpdservices = new File(dest, "nanohttpd-services");
        nanohttpdservices.mkdir();
        File temp = new File(dest, "temp");
        temp.mkdir();
        File apps = new File(dest, "apps");
        apps.mkdir();

        File local = new File(commands.getOptionValue("lr", "./local-repository"));
        Collection<RemoteRepository> repositories = Arrays.asList(
                new RemoteRepository("sanaldiyar-snap", "default", "http://maven2.sanaldiyar.com/snap-repo"),
                new RemoteRepository("central", "default", "http://repo1.maven.org/maven2/"));
        Aether aether = new Aether(repositories, local);

        //Copy core felix main
        System.out.println("Downloading Felix main executable");
        List<Artifact> felixmain = aether.resolve(
                new DefaultArtifact("org.apache.felix", "org.apache.felix.main", "jar", "LATEST"), "runtime");
        for (Artifact artifact : felixmain) {
            if (artifact.getArtifactId().equals("org.apache.felix.main")) {
                FileUtils.copyFile(artifact.getFile(), new File(bin, "felix-main.jar"));
                System.out.println(artifact.getArtifactId());
                break;
            }
        }
        System.out.println("OK");

        //Copy core felix bundles
        System.out.println("Downloading Felix core bundles");
        Collection<String> felixcorebundles = Arrays.asList("fileinstall", "bundlerepository", "gogo.runtime",
                "gogo.shell", "gogo.command");
        for (String felixcorebunlde : felixcorebundles) {
            List<Artifact> felixcore = aether.resolve(new DefaultArtifact("org.apache.felix",
                    "org.apache.felix." + felixcorebunlde, "jar", "LATEST"), "runtime");
            for (Artifact artifact : felixcore) {
                if (artifact.getArtifactId().equals("org.apache.felix." + felixcorebunlde)) {
                    FileUtils.copyFileToDirectory(artifact.getFile(), core);
                    System.out.println(artifact.getArtifactId());
                }
            }
        }
        System.out.println("OK");

        //Copy nanohttpd core bundles
        System.out.println("Downloading nanohttpd core bundles and configurations");
        List<Artifact> nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "nanohttpd", "jar", "LATEST"),
                "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            if (!artifact.getArtifactId().equals("org.osgi.core")) {
                FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
                System.out.println(artifact.getArtifactId());
            }
        }

        nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("com.sanaldiyar.projects", "engender", "jar", "LATEST"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("org.codehaus.jackson", "jackson-mapper-asl", "jar", "1.9.5"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        nanohttpdcorebundle = aether
                .resolve(new DefaultArtifact("org.mongodb", "mongo-java-driver", "jar", "LATEST"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        //Copy nanohttpd conf
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/nanohttpd.conf"),
                new File(dest, "nanohttpd.conf"));
        System.out.println("Configuration: nanohttpd.conf");

        //Copy nanohttpd start script
        File startsh = new File(dest, "start.sh");
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/start.sh"), startsh);
        startsh.setExecutable(true);
        System.out.println("Script: start.sh");

        System.out.println("OK");

        //Copy nanohttpd service bundles
        System.out.println("Downloading nanohttpd service bundles");
        List<Artifact> nanohttpdservicebundle = aether
                .resolve(new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "mongodbbasedsessionhandler",
                        "jar", "1.0-SNAPSHOT"), "runtime");
        for (Artifact artifact : nanohttpdservicebundle) {
            if (artifact.getArtifactId().equals("mongodbbasedsessionhandler")) {
                FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdservices);
                System.out.println(artifact.getArtifactId());
                break;
            }
        }

        //Copy nanohttpd mongodbbasedsessionhandler conf
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/mdbbasedsh.conf"),
                new File(dest, "mdbbasedsh.conf"));
        System.out.println("Configuration: mdbbasedsh.conf");

        System.out.println("OK");

        if (commands.hasOption("dlr")) {
            System.out.println("Local repository is deleting");
            FileUtils.deleteDirectory(local);
            System.out.println("OK");
        }

        System.out.println("You can reconfigure nanohttpd and services. To start system run start.sh script");

    } catch (Exception ex) {
        System.out.println("Error at installing.");
    }
}

From source file:usr.erichschroeter.conversionsvg.ConversionSvg.java

public static void main(String[] args) {
    // license to use JIDE software (JDAF, Grids, Components, etc)
    // com.jidesoft.utils.Lm.verifyLicense("Erich Schroeter",
    // "ConversionSVG", "3.99ekleZZE3EXVgbI0hck9kXuHYXJh2");
    Options o = new Options();
    o.addOption(new Option("v", "version", false, "display the version"));
    o.addOption(new Option("V", "verbose", false, "display verbose information"));
    o.addOption(new Option("h", "help", false, "display this menu"));
    o.addOption(new Option("I", "inkscape", true, "the location of Inkscape executable"));

    try {/*from ww w.  j ava2 s.c  om*/
        CommandLineParser parser = new GnuParser();
        CommandLine commandline = parser.parse(o, args);

        if (commandline.hasOption("h")) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("conversionsvg [Options]", o);
            System.exit(0);
        }
        if (commandline.hasOption("v")) {
            System.out.printf("%s%n", new ConversionSvgApplication().getVersion());
            System.exit(0);
        }
        isVerbose = commandline.hasOption("V");

        if (commandline.hasOption("I")) {
            Inkscape.setExecutable(new File(commandline.getOptionValue("I")));
        } else {
            Inkscape.setExecutable(Inkscape.findExecutable());
        }

        args = commandline.getArgs();
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    if (isVerbose) {
        File inkscape = Inkscape.getExecutable();
        if (inkscape == null) {
            System.out.println("could not find Inkscape installed");
        } else {
            System.out.printf("found Inkscape installed at <%s>%n", Inkscape.getExecutable().getAbsolutePath());
        }
    }

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception exception) {
                exception.printStackTrace();
            }

            // // install the preference values
            // int width = getApplicationPreferences()
            // .getInt("window.size.width", 600);
            // int height =
            // getApplicationPreferences().getInt("window.size.height",
            // 350);
            // int x =
            // getApplicationPreferences().getInt("window.location.x", 100);
            // int y =
            // getApplicationPreferences().getInt("window.location.y", 100);
            //
            // getApplicationWindow().setPreferredSize(new Dimension(width,
            // height));
            // getApplicationWindow().setLocation(new Point(x, y));
            //
            // // initialize the thread pool
            // int corePoolSize = getApplicationPreferences().getInt(
            // "thread_pool.core_size", 10);
            // int maximumPoolSize = getApplicationPreferences().getInt(
            // "thread_pool.max_size", 20);
            // int keepAliveTime = getApplicationPreferences().getInt(
            // "thread_pool.keep_alive_time", 10);
            // // The thread pool used to start Inkscape processes
            // PriorityBlockingQueue<Runnable> queue = new
            // PriorityBlockingQueue<Runnable>(
            // corePoolSize);
            // setThreadPool(new ThreadPoolExecutor(corePoolSize,
            // maximumPoolSize,
            // keepAliveTime, TimeUnit.SECONDS, queue));
            //
            // getApplicationWindow().setVisible(true);

            ConversionSvgApplication app = new ConversionSvgApplication();
            JRibbon ribbon = app.createApplicationRibbon();
            ribbon.setApplicationMenu(app.createApplicationRibbonMenu());
            for (RibbonTask t : app.createApplicationRibbonTasks()) {
                ribbon.addTask(t);
            }
            app.installApplicationRibbon(ribbon);
            app.getApplicationWindow().pack();
            app.run();

        }
    });
}

From source file:Main.java

public static void copyAssetFileToFiles(Context context, String root, String filename) throws IOException {
    InputStream is = context.getAssets().open(filename);
    byte[] buffer = new byte[is.available()];
    is.read(buffer);//from w  w  w  .  j ava  2  s. c  o  m
    is.close();

    File tgtfile = new File(root + "/" + filename);
    tgtfile.createNewFile();
    tgtfile.setExecutable(true);
    FileOutputStream os = new FileOutputStream(tgtfile);
    os.write(buffer);
    os.close();
}

From source file:org.phenotips.textanalysis.internal.BiolarkFileUtils.java

/**
 * Gives the target or it's contents executable permissions. Operates recursively.
 *
 * @param target File or directory to modify
 *//*from ww w  .jav  a2s . co  m*/
public static void makeExecutable(File target) {
    if (target.isFile()) {
        target.setExecutable(true);
    } else {
        for (File file : target.listFiles()) {
            makeExecutable(file);
        }
    }
}

From source file:org.libimobiledevice.ios.driver.binding.raw.JNAInit.java

public static synchronized boolean init() {
    if (initialize) {
        return true;
    }// w  w  w  . j ava2  s .  c  o  m

    // create the tmp dir where all the lib will be loaded from.
    // by default JNA created 1 different folder for each lib, which breaks libraries having a
    // @loader_path/libcrypto.1.0.0.dylib syntax. Creating this helper class to have everything in
    // one place, jna.tmpdir
    String home = System.getProperty("user.home");
    File jna = new File(home, "/.ios-driver/jna/darwin");
    jna.mkdirs();
    output = jna;

    //    System.setProperty("jna.library.path", jna.getAbsolutePath());
    //    System.out.println("jna.library.path=" + System.getProperty("jna.library.path"));

    // extract everything in it
    List<String> libs = new ArrayList<String>();
    if (Platform.isMac()) {
        libs.add("crypto.1.0.0");
        libs.add("iconv.2");
        libs.add("ssl.1.0.0");
        libs.add("z.1");
        libs.add("lzma.5");
    }

    if (Platform.isLinux() || Platform.isWindows()) {
        libs.add("crypto");
        libs.add("ssl");
    }

    libs.add("imobiledevice.4");
    libs.add("imobiledevice-sdk");
    libs.add("plist.2");
    libs.add("usbmuxd.2");
    libs.add("xml2.2");
    //libs.add("zip");

    for (String lib : libs) {
        unpack(lib, jna);
    }
    NativeLibrary.addSearchPath("imobiledevice-sdk", jna.getAbsolutePath());

    File dst = new File(jna, "idevicedebug");
    copy("darwin/idevicedebug", dst);
    dst.setExecutable(true);

    ImobiledeviceSdkLibrary.sdk_idevice_event_unsubscribe();
    initialize = true;
    return true;
}

From source file:org.apache.whirr.util.KeyPair.java

/**
 * Set file permissions to 600 (unix)// w  ww .j a va2s .c  om
 */
public static void setPermissionsTo600(File f) {
    f.setReadable(false, false);
    f.setReadable(true, true);

    f.setWritable(false, false);
    f.setWritable(true, true);

    f.setExecutable(false);
}

From source file:com.stratio.crossdata.connector.plugin.installer.InstallerGoalLauncher.java

public static void launchInstallerGoal(InstallerGoalConfig config, Log log) throws IOException {

    log.info("Create TARGET directory.");
    File targetDirectory = new File(
            FilenameUtils.concat(config.getOutputDirectory(), config.getConnectorName()));
    if (targetDirectory.exists()) {
        log.info("Remove previous TARGET directory");
        FileUtils.forceDelete(targetDirectory);
    }/*from  www. ja v  a 2  s.  c om*/
    File includeConfigDirectory = new File(config.getIncludeDirectory());
    FileUtils.copyDirectory(includeConfigDirectory, targetDirectory);

    log.info("Create LIB directory.");
    File libDirectory = new File(FilenameUtils.concat(targetDirectory.toString(), "lib"));
    FileUtils.copyFileToDirectory(config.getMainJarRepo(), libDirectory);
    for (File jarFile : config.getDependenciesJarRepo()) {
        FileUtils.copyFileToDirectory(jarFile, libDirectory);
    }

    log.info("Create CONF directory.");
    File confDirectory = new File(FilenameUtils.concat(targetDirectory.toString(), "conf"));
    File confConfigDirectory = new File(config.getConfigDirectory());
    FileUtils.copyDirectory(confConfigDirectory, confDirectory);

    log.info("Create BIN Directory");
    File binDirectory = new File(FilenameUtils.concat(targetDirectory.toString(), "bin"));
    FileUtils.forceMkdir(binDirectory);

    log.info("Launch template");
    String outputString = (config.getUnixScriptTemplate());
    outputString = outputString.replaceAll("<name>", config.getConnectorName());
    outputString = outputString.replaceAll("<desc>", config.getDescription());
    String user = config.getUserService();
    if (config.isUseCallingUserAsService()) {
        user = System.getProperty("user.name");
    }
    outputString = outputString.replaceAll("<user>", user);
    outputString = outputString.replaceAll("<mainClass>", config.getMainClass());
    int index = config.getMainClass().lastIndexOf('.');
    String className = config.getMainClass();
    if (index != -1) {
        className = config.getMainClass().substring(index + 1);
    }
    outputString = outputString.replaceAll("<mainClassName>", className);

    outputString = outputString.replaceAll("<jmxPort>", config.getJmxPort());
    String pidFileName = "";
    if (config.getPidFileName() != null) {
        pidFileName = config.getPidFileName();
    }
    outputString = outputString.replaceAll("<pidFileName>", pidFileName);

    File binFile = new File(FilenameUtils.concat(binDirectory.toString(), config.getConnectorName()));
    FileUtils.writeStringToFile(binFile, outputString);
    if (!binFile.setExecutable(true)) {
        throw new IOException("Can't change executable option.");
    }

    log.info("Process complete: " + targetDirectory);
}

From source file:ch.vorburger.mariadb4j.Util.java

public static void forceExecutable(File executableFile) throws IOException {
    if (executableFile.exists() && !executableFile.canExecute()) {
        boolean succeeded = executableFile.setExecutable(true);
        if (succeeded) {
            logger.info("chmod +x " + executableFile.toString() + " (using java.io.File.setExecutable)");
        } else {//from   w  ww .j a  v a2 s.c  o  m
            throw new IOException("Failed to do chmod +x " + executableFile.toString()
                    + " using java.io.File.setExecutable, which will be a problem on *NIX...");
        }
    }
}