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:org.jboss.tools.openshift.common.core.utils.FileUtils.java

/**
 * Replicates the owner permissions from the source to the destination. Due
 * to limitation in java6 this is the best we can do (there's no way in
 * java6 to know if rights are due to owner or group)
 * //from   w  w w .  ja  v a2  s  .  c  o m
 * @param source
 * @param destination
 * 
 * @see File#canRead()
 * @see File#setReadable(boolean)
 * @see File#canWrite()
 * @see File#setWritable(boolean)
 * @see File#canExecute()
 * @see File#setExecutable(boolean)
 */
private static void copyPermissions(File source, File destination) {
    Assert.isLegal(source != null);
    Assert.isLegal(destination != null);

    destination.setReadable(source.canRead());
    destination.setWritable(source.canWrite());
    destination.setExecutable(source.canExecute());
}

From source file:org.cloudifysource.utilitydomain.context.blockstorage.VolumeUtils.java

/**
 * @see {@link StorageFacade#partition(String, long)}
 * @param device .//  ww  w  .  j av  a2  s . c  om
 * @param timeoutInMillis .
 * @throws LocalStorageOperationException .
 * @throws TimeoutException .
 */
public static void partition(final String device, final long timeoutInMillis)
        throws LocalStorageOperationException, TimeoutException {
    try {
        File tempParitioningScript = File.createTempFile("partitionvolume", ".sh");
        FileUtils.writeStringToFile(tempParitioningScript,
                "(echo o; echo n; echo p; echo 1; echo; echo; echo w) | sudo fdisk " + device);
        tempParitioningScript.setExecutable(true);
        tempParitioningScript.deleteOnExit();
        executeCommandLine(tempParitioningScript.getAbsolutePath(), timeoutInMillis);
    } catch (IOException ioe) {
        // fdisk returns exit code 1 even when successful so we have to verify
        logger.info("inspecting fdisk command exception: " + ioe.getMessage());
        if (!verifyDevicePartitioning(device, timeoutInMillis)) {
            throw new LocalStorageOperationException(
                    "Failed to partition device " + device + ", reported error: " + ioe.getMessage(), ioe);
        }
    }

}

From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java

public static void copyFileAttributes(@Nonnull final File from, @Nonnull final File to) {
    to.setExecutable(from.canExecute());
    to.setReadable(from.canRead());/*w ww. j av a2  s .c o m*/
    to.setWritable(from.canWrite());
}

From source file:net.sourceforge.pmd.it.ZipFileExtractor.java

/**
 * Extracts the given zip file into the tempDir.
 * @param zipPath the zip file to extract
 * @param tempDir the target directory//from  ww w  .j  a v a  2  s .co m
 * @throws Exception if any error happens during extraction
 */
public static void extractZipFile(Path zipPath, Path tempDir) throws Exception {
    ZipFile zip = new ZipFile(zipPath.toFile());
    try {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File file = tempDir.resolve(entry.getName()).toFile();
            if (entry.isDirectory()) {
                assertTrue(file.mkdirs());
            } else {
                try (InputStream data = zip.getInputStream(entry);
                        OutputStream fileOut = new FileOutputStream(file);) {
                    IOUtils.copy(data, fileOut);
                }
                if ((entry.getUnixMode() & OWNER_EXECUTABLE) == OWNER_EXECUTABLE) {
                    file.setExecutable(true);
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:com.dc.util.file.FileSupport.java

public static void writeTextFile(String folderPath, String fileName, String data, boolean isExecutable)
        throws IOException {
    File dir = new File(folderPath);
    if (!dir.exists()) {
        dir.mkdirs();/*from  w  w  w . ja v a  2s .c  o  m*/
    }
    File file = new File(dir, fileName);
    FileWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    try {
        fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(data);
        bufferedWriter.flush();
        if (isExecutable) {
            file.setExecutable(true);
        }
    } finally {
        if (fileWriter != null) {
            fileWriter.close();
        }
        if (bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
}

From source file:org.rapidcontext.util.FileUtil.java

/**
 * Copies a file or a directory. Directories are copied
 * recursively and file modification dates are kept. If the
 * executable bit is set on the source file, that bit will also
 * be set on the destination file.//from  w w w  . ja v a 2  s .c  o  m
 *
 * @param src            the source file or directory
 * @param dst            the destination file or directory
 *
 * @throws IOException if some file couldn't be copied
 */
@SuppressWarnings("resource")
public static void copy(File src, File dst) throws IOException {
    if (src.isDirectory()) {
        dst.mkdirs();
        File[] files = src.listFiles();
        for (int i = 0; i < files.length; i++) {
            copy(files[i], new File(dst, files[i].getName()));
        }
    } else {
        copy(new FileInputStream(src), dst);
        dst.setExecutable(src.canExecute());
    }
    dst.setLastModified(src.lastModified());
}

From source file:org.eclipse.cft.server.core.internal.CloudUtil.java

/**
 * Creates a temporary folder and file with the given names. It is the
 * responsibility of the caller to properly dispose the folder and file
 * after it is created/*from   ww  w  . j  a  va2  s  .co  m*/
 * @param folderName
 * @param fileName
 * @return
 * @throws IOException
 */
public static File createTemporaryFile(String folderName, String fileName) throws IOException {
    File tempFolder = File.createTempFile(folderName, null);
    // Delete an existing one
    tempFolder.delete();

    tempFolder.mkdirs();
    tempFolder.setExecutable(true);

    File targetFile = new File(tempFolder, fileName);

    // delete existing file
    targetFile.delete();

    targetFile.createNewFile();
    targetFile.setExecutable(true);
    targetFile.setWritable(true);

    return targetFile;
}

From source file:org.datavyu.models.db.MongoDatastore.java

/**
 * Spin up the mongo instance so that we can query and do stuff with it.
 *///from   w  w  w .j a  v a  2s  .  co m
public static void startMongo() {
    // Unpack the mongo executable.
    try {
        String mongoDir;
        switch (Datavyu.getPlatform()) {
        case MAC:
            mongoDir = NativeLoader.unpackNativeApp(mongoOSXLocation);
            break;
        case WINDOWS:
            mongoDir = NativeLoader.unpackNativeApp(mongoWindowsLocation);
            break;
        default:
            mongoDir = NativeLoader.unpackNativeApp(mongoOSXLocation);
        }

        // When files are unjared - they loose their executable status.
        // So find the mongod executable and set it to exe
        Collection<File> files = FileUtils.listFiles(new File(mongoDir), new RegexFileFilter(".*mongod.*"),
                TrueFileFilter.INSTANCE);

        File f;
        if (files.iterator().hasNext()) {
            f = files.iterator().next();
            f.setExecutable(true);
        } else {
            f = new File("");
            System.out.println("ERROR: Could not find mongod");
        }

        //            File f = new File(mongoDir + "/mongodb-osx-x86_64-2.0.2/bin/mongod");
        //            f.setExecutable(true);

        // Spin up a new mongo instance.
        File mongoD = new File(mongoDir);
        //            int port = findFreePort(27019);
        int port = 27019;

        // Try to shut down the server if it is already running
        try {
            mongoDriver = new Mongo("127.0.0.1", port);
            DB db = mongoDriver.getDB("admin");
            db.command(new BasicDBObject("shutdownServer", 1));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mongoProcess = new ProcessBuilder(f.getAbsolutePath(), "--dbpath", mongoD.getAbsolutePath(),
                "--bind_ip", "127.0.0.1", "--port", String.valueOf(port), "--directoryperdb").start();
        //            InputStream in = mongoProcess.getInputStream();
        //            InputStreamReader isr = new InputStreamReader(in);

        System.out.println("Starting mongo driver.");
        mongoDriver = new Mongo("127.0.0.1", port);

        System.out.println("Getting DB");

        // Start with a clean DB
        mongoDB = mongoDriver.getDB("datavyu");

        DBCollection varCollection = mongoDB.getCollection("variables");
        varCollection.setObjectClass(MongoVariable.class);

        DBCollection cellCollection = mongoDB.getCollection("cells");
        cellCollection.setObjectClass(MongoCell.class);

        DBCollection matrixCollection = mongoDB.getCollection("matrix_values");
        matrixCollection.setObjectClass(MongoMatrixValue.class);

        DBCollection nominalCollection = mongoDB.getCollection("nominal_values");
        nominalCollection.setObjectClass(MongoNominalValue.class);

        DBCollection textCollection = mongoDB.getCollection("text_values");
        textCollection.setObjectClass(MongoTextValue.class);

        System.out.println("Got DB");
        running = true;

    } catch (Exception e) {
        System.err.println("Unable to fire up the mongo datastore.");
        e.printStackTrace();
    }
}

From source file:org.servalproject.maps.osmbboxsplit.BBoxSplit.java

/**
 * read an OSM PBF file and optionally write an osmosis script using the supplied template
 * /*from w ww  .  j a  v a2 s . c o  m*/
 * @param inputFile path to the input file
 * @param outputDir path to the output directory
 * @param template the contents of the template file
 * @param minFileSize the minimum file size, in MB, of files to process
 * @throws IOException if the specified file cannot be read
 */
public static void readFile(File inputFile, File outputDir, String template, int minFileSize)
        throws IOException {

    // check the parameters
    try {
        if (FileUtils.isFileAccessible(inputFile.getCanonicalPath()) == false) {
            throw new IOException("unable to access the required file");
        }

        System.out.println("Processing file: " + inputFile.getCanonicalPath());

    } catch (IOException e) {
        throw new IOException("unable to access the required file", e);
    }

    // check to see if this file should be ignored
    if (OsmBBoxSplit.ignoreList.size() > 0) {
        if (OsmBBoxSplit.ignoreList.contains(inputFile.getCanonicalPath())) {
            System.out.println("WARNING: File specified in the ignore list, skipping...");
            return;
        }
    }

    // read the data in the file
    BlockInputStream blockinput;
    BinaryDataParser dataParser = new BinaryDataParser();
    try {
        blockinput = (new BlockInputStream(new FileInputStream(inputFile), dataParser));
    } catch (FileNotFoundException e) {
        throw new IOException("unable to access the required file", e);
    }

    // output some information
    try {
        blockinput.process();

        System.out.println("File Size: " + FileUtils.humanReadableByteCount(inputFile.length(), true));
    } catch (IOException e) {
        throw new IOException("unable to process the required file", e);
    } finally {
        blockinput.close();
    }

    // determine if we need to split the file
    if (inputFile.length() >= (minFileSize * 1000 * 1000)) {
        // file is over the minimum file size so try to split

        double minLat = dataParser.getGeoCoordinates()[0];
        double minLng = dataParser.getGeoCoordinates()[1];
        double maxLat = dataParser.getGeoCoordinates()[2];
        double maxLng = dataParser.getGeoCoordinates()[3];

        //         boolean latOk = false;
        //         boolean lngOk = false;
        //         
        //         // check to make sure that the all of the lats and longs are of the same size
        //         if((minLat < 0 && maxLat < 0) || (minLat > 0 && maxLat > 0)) {
        //            latOk = true;
        //         }
        //         
        //         if((minLng < 0 && maxLng < 0) || (minLng > 0 && maxLng > 0)) {
        //            lngOk = true;
        //         }
        //         
        //         if(!latOk || !lngOk) {
        //            System.out.println("Error: bounding box spans equator or prime meridian, can't split");
        //            return;
        //         }
        //         
        //         // calculate the differences
        //         double diffLat = (maxLat - minLat) / 2;
        //         double diffLng = (maxLng - minLng) / 2;
        //         
        //         // calculate the new bounding boxes
        //         double newLat = minLat + diffLat;
        //         double newLng = minLng + diffLng;

        // calculate the new latitude and longitude
        double newLat = (minLat + maxLat) / 2;
        double newLng = (minLng + maxLng) / 2;

        // output the new definitions
        System.out.println("BBox A lat/lng: " + newLat + ", " + minLng + " - " + maxLat + ", " + newLng);
        System.out
                .println("URL: " + String.format(BinaryDataParser.URL_FORMAT, minLng, newLat, newLng, maxLat));

        System.out.println("BBox B lat/lng: " + newLat + ", " + newLng + " - " + maxLat + ", " + maxLng);
        System.out
                .println("URL: " + String.format(BinaryDataParser.URL_FORMAT, newLng, newLat, maxLng, maxLat));

        System.out.println("BBox C lat/lng: " + minLat + ", " + minLng + " - " + newLat + ", " + newLng);
        System.out
                .println("URL: " + String.format(BinaryDataParser.URL_FORMAT, minLng, minLat, newLng, newLat));

        System.out.println("BBox D lat/lng: " + minLat + ", " + newLng + " - " + newLat + ", " + maxLng);
        System.out
                .println("URL: " + String.format(BinaryDataParser.URL_FORMAT, newLng, minLat, maxLng, newLat));

        // create a new script
        if (template != null) {

            String scriptContents = new String(template);

            // add missing information
            scriptContents = scriptContents.replace("{{INPUT_PATH}}", inputFile.getCanonicalPath());
            scriptContents = scriptContents.replace("{{OUTPUT_PATH}}",
                    inputFile.getCanonicalFile().getParent());

            //replace all of the a quadrant variables
            scriptContents = scriptContents.replace("{{BBOX_A_BOTTOM}}", Double.toString(newLat));
            scriptContents = scriptContents.replace("{{BBOX_A_LEFT}}", Double.toString(minLng));
            scriptContents = scriptContents.replace("{{BBOX_A_TOP}}", Double.toString(maxLat));
            scriptContents = scriptContents.replace("{{BBOX_A_RIGHT}}", Double.toString(newLng));
            scriptContents = scriptContents.replace("{{BBOX_A_FILE}}",
                    inputFile.getName().replace(".osm.pbf", "_a.osm.pbf"));

            scriptContents = scriptContents.replace("{{BBOX_B_BOTTOM}}", Double.toString(newLat));
            scriptContents = scriptContents.replace("{{BBOX_B_LEFT}}", Double.toString(newLng));
            scriptContents = scriptContents.replace("{{BBOX_B_TOP}}", Double.toString(maxLat));
            scriptContents = scriptContents.replace("{{BBOX_B_RIGHT}}", Double.toString(maxLng));
            scriptContents = scriptContents.replace("{{BBOX_B_FILE}}",
                    inputFile.getName().replace(".osm.pbf", "_b.osm.pbf"));

            scriptContents = scriptContents.replace("{{BBOX_C_BOTTOM}}", Double.toString(minLat));
            scriptContents = scriptContents.replace("{{BBOX_C_LEFT}}", Double.toString(minLng));
            scriptContents = scriptContents.replace("{{BBOX_C_TOP}}", Double.toString(newLat));
            scriptContents = scriptContents.replace("{{BBOX_C_RIGHT}}", Double.toString(newLng));
            scriptContents = scriptContents.replace("{{BBOX_C_FILE}}",
                    inputFile.getName().replace(".osm.pbf", "_c.osm.pbf"));

            scriptContents = scriptContents.replace("{{BBOX_D_BOTTOM}}", Double.toString(minLat));
            scriptContents = scriptContents.replace("{{BBOX_D_LEFT}}", Double.toString(newLng));
            scriptContents = scriptContents.replace("{{BBOX_D_TOP}}", Double.toString(newLat));
            scriptContents = scriptContents.replace("{{BBOX_D_RIGHT}}", Double.toString(maxLng));
            scriptContents = scriptContents.replace("{{BBOX_D_FILE}}",
                    inputFile.getName().replace(".osm.pbf", "_d.osm.pbf"));

            // write the file
            try {

                File newFile = new File(
                        outputDir.getCanonicalPath() + File.separator + inputFile.getName() + ".sh");

                System.out.println("writing script file:\n" + newFile.getCanonicalPath());

                org.apache.commons.io.FileUtils.writeStringToFile(newFile, scriptContents);

                newFile.setExecutable(true);

            } catch (IOException e) {
                throw new IOException("unable to write the script file.", e);
            }
        }

    }

}

From source file:com.frostwire.gui.updates.PortableUpdater.java

private static void createScript(String scriptName) {
    File fileJS = new File(CommonUtils.getUserSettingsDir(), scriptName);
    //        if (fileJS.exists()) {
    //            return;
    //        }//from   www.j  a  va  2  s .c  o  m

    URL url = ResourceManager.getURLResource(scriptName);

    InputStream is = null;
    OutputStream out = null;

    try {
        if (url != null) {
            is = new BufferedInputStream(url.openStream());
            out = new FileOutputStream(fileJS);
            IOUtils.copy(is, out);

            fileJS.setExecutable(true);
        }
    } catch (IOException e) {
        LOG.error("Error creating script", e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(out);
    }
}