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, boolean ownerOnly) 

Source Link

Document

Sets the owner's or everybody's execute permission for this abstract pathname.

Usage

From source file:skoa.helpers.ConfiguracionGraficas.java

private void inicial() {
    Date fechaActual = new Date();
    NombreCarpetaActual = formatoDelTextoCarpeta.format(fechaActual);
    //Para cada consulta, se crea una carpeta con la fecha y hora de realizacion de la consulta,
    //para almacenar en ella todos los resultados y graficas de esa consulta.
    String os = System.getProperty("os.name");
    //En Windows las barras son \ y en Linux /.
    if (os.indexOf("Win") >= 0)
        ruta_destino = ruta_jar + "\\Consultas\\";
    else//  w  ww.  jav  a  2 s.c  om
        ruta_destino = ruta_jar + "/Consultas/";
    ruta_destino = ruta_destino + NombreCarpetaActual;
    File destino_consulta = new File(ruta_destino);
    destino_consulta.setExecutable(true, false);
    destino_consulta.setReadable(true, false);
    destino_consulta.setWritable(true, false);
    //HACEMOS LA CREACION DE LA CARPETA DESTINO PARA LA NUEVA CONSULTA POSTERIOR.
    if (destino_consulta.mkdir()) {
    } //System.out.println("**SE CREA DIR.   "+ruta_destino);
    else { //En caso de existir ya el directorio, porque hemos hecho las consultas muy rapido
           //y estas coinciden en su nombre, ya que el nombre es la hora en que se consulta
           //le vamos a aadir un numero indicando que es una consulta a la misma hora.
        String aux = NombreCarpetaActual.substring(NombreCarpetaActual.indexOf(" ") + 1); //Contamos desde el primer espacio
        if (aux.indexOf(" ") != -1) {
            aux = aux.substring(aux.length() - 1); //Cogemos el ultimo caracter.
            int naux = Integer.parseInt(aux); //Lo pasamos a entero
            naux++; //Lo incrementamos en 1
            NombreCarpetaActual = NombreCarpetaActual + " " + naux;
        } else
            NombreCarpetaActual = NombreCarpetaActual + " 1";
        if (os.indexOf("Win") >= 0)
            ruta_destino = ruta_jar + "\\Consultas\\";
        else
            ruta_destino = ruta_jar + "/Consultas/";
        //ruta_destino=ruta_jar+"\\Consultas\\";
        ruta_destino = ruta_destino + NombreCarpetaActual;
        destino_consulta = new File(ruta_destino);
        destino_consulta.setExecutable(true, false);
        destino_consulta.setReadable(true, false);
        destino_consulta.setWritable(true, false);
        destino_consulta.mkdir();
    }
    interfaz.getContentPane().setLayout(new BorderLayout());
    panel.add(opciones); //No se aade esta opcion en cargarVista() para generalizarla y usarla siempre.
    panel.add(opciones2); //No se aade esta opcion en cargarVista() para generalizarla y usarla siempre.
    cargarVista();
    interfaz.getContentPane().add(oeste, "West");
    interfaz.getContentPane().add(centro, "Center");
    interfaz.setVisible(true);
}

From source file:com.buaa.cfs.utils.FileUtil.java

/**
 * Set permissions to the required value. Uses the java primitives instead of forking if group == other.
 *
 * @param f          the file to change//w  w w  .  j  a v  a  2 s . co  m
 * @param permission the new permissions
 *
 * @throws IOException
 */
public static void setPermission(File f, FsPermission permission) throws IOException {
    FsAction user = permission.getUserAction();
    FsAction group = permission.getGroupAction();
    FsAction other = permission.getOtherAction();

    // use the native/fork if the group/other permissions are different
    // or if the native is available or on Windows
    if (group != other || NativeIO.isAvailable() || Shell.WINDOWS) {
        execSetPermission(f, permission);
        return;
    }

    boolean rv = true;

    // read perms
    rv = f.setReadable(group.implies(FsAction.READ), false);
    checkReturnValue(rv, f, permission);
    if (group.implies(FsAction.READ) != user.implies(FsAction.READ)) {
        rv = f.setReadable(user.implies(FsAction.READ), true);
        checkReturnValue(rv, f, permission);
    }

    // write perms
    rv = f.setWritable(group.implies(FsAction.WRITE), false);
    checkReturnValue(rv, f, permission);
    if (group.implies(FsAction.WRITE) != user.implies(FsAction.WRITE)) {
        rv = f.setWritable(user.implies(FsAction.WRITE), true);
        checkReturnValue(rv, f, permission);
    }

    // exec perms
    rv = f.setExecutable(group.implies(FsAction.EXECUTE), false);
    checkReturnValue(rv, f, permission);
    if (group.implies(FsAction.EXECUTE) != user.implies(FsAction.EXECUTE)) {
        rv = f.setExecutable(user.implies(FsAction.EXECUTE), true);
        checkReturnValue(rv, f, permission);
    }
}

From source file:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java

public synchronized File prepareConfigDir(String strRelativePath) {
    String filePath = getBaseBuildWorkingDirectory() + File.separator + strRelativePath;

    File f = new File(filePath);

    f.setReadable(true, true);/*from   ww  w  . j  a  v  a 2s  .c  o m*/
    f.setWritable(true, true);
    f.setExecutable(true, true);

    f.mkdir();

    return f;
}

From source file:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java

public synchronized File prepareSSHKeyFile(String strRelativePath, String sshKey) {
    String filePath = getBaseBuildWorkingDirectory() + File.separator + strRelativePath;

    File f = new File(filePath);

    f.setReadable(true, true);//w  w  w .  j  a  v  a2  s.  c om
    f.setWritable(true, true);
    f.setExecutable(false, false);

    try {
        FileUtils.writeStringToFile(f, sshKey);
    } catch (IOException e) {
        log.error(e.getMessage());
        return null;
    }

    try {
        if (SystemUtils.IS_OS_UNIX || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC_OSX)
            Runtime.getRuntime().exec("chmod 700 " + filePath);
    } catch (IOException e) {
        log.warn(e.getMessage());
    }

    return f;
}

From source file:org.apache.flink.runtime.blob.BlobCacheGetTest.java

/**
 * Retrieves a BLOB via a {@link BlobCacheService} which cannot create incoming files. File
 * transfers should fail./*from w w w  . j  a v a 2  s . c o  m*/
 *
 * @param jobId
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testGetFailsIncoming(@Nullable final JobID jobId, BlobKey.BlobType blobType) throws IOException {
    assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

    final Configuration config = new Configuration();
    config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

    File tempFileDir = null;
    try (BlobServer server = new BlobServer(config, new VoidBlobStore());
            BlobCacheService cache = new BlobCacheService(config, new VoidBlobStore(),
                    new InetSocketAddress("localhost", server.getPort()))) {

        server.start();

        // store the data on the server
        byte[] data = new byte[2000000];
        rnd.nextBytes(data);
        BlobKey blobKey = put(server, jobId, data, blobType);
        verifyType(blobType, blobKey);

        // make sure the blob cache cannot create any files in its storage dir
        if (blobType == PERMANENT_BLOB) {
            tempFileDir = cache.getPermanentBlobService().createTemporaryFilename().getParentFile();
        } else {
            tempFileDir = cache.getTransientBlobService().createTemporaryFilename().getParentFile();
        }
        assertTrue(tempFileDir.setExecutable(true, false));
        assertTrue(tempFileDir.setReadable(true, false));
        assertTrue(tempFileDir.setWritable(false, false));

        // request the file from the server via the cache
        exception.expect(IOException.class);
        exception.expectMessage("Failed to fetch BLOB ");

        try {
            get(cache, jobId, blobKey);
        } finally {
            HashSet<String> expectedDirs = new HashSet<>();
            expectedDirs.add("incoming");
            if (jobId != null) {
                // only the incoming and job directory should exist (no job directory!)
                expectedDirs.add(JOB_DIR_PREFIX + jobId);
                File storageDir = tempFileDir.getParentFile();
                String[] actualDirs = storageDir.list();
                assertNotNull(actualDirs);
                assertEquals(expectedDirs, new HashSet<>(Arrays.asList(actualDirs)));

                // job directory should be empty
                File jobDir = new File(tempFileDir.getParentFile(), JOB_DIR_PREFIX + jobId);
                assertArrayEquals(new String[] {}, jobDir.list());
            } else {
                // only the incoming and no_job directory should exist (no job directory!)
                expectedDirs.add(NO_JOB_DIR_PREFIX);
                File storageDir = tempFileDir.getParentFile();
                String[] actualDirs = storageDir.list();
                assertNotNull(actualDirs);
                assertEquals(expectedDirs, new HashSet<>(Arrays.asList(actualDirs)));

                // no_job directory should be empty
                File noJobDir = new File(tempFileDir.getParentFile(), NO_JOB_DIR_PREFIX);
                assertArrayEquals(new String[] {}, noJobDir.list());
            }

            // file should still be there on the server (even if transient)
            assertTrue(server.getStorageLocation(jobId, blobKey).exists());
        }
    } finally {
        // set writable again to make sure we can remove the directory
        if (tempFileDir != null) {
            //noinspection ResultOfMethodCallIgnored
            tempFileDir.setWritable(true, false);
        }
    }
}

From source file:org.apache.flink.runtime.blob.BlobCacheGetTest.java

/**
 * Retrieves a BLOB via a {@link BlobCacheService} which cannot create the final storage file.
 * File transfers should fail./*from   w  w  w  .  ja va  2  s  . c  o m*/
 *
 * @param jobId
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testGetFailsStore(@Nullable final JobID jobId, BlobKey.BlobType blobType)
        throws IOException, InterruptedException {
    assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

    final Configuration config = new Configuration();
    config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

    File jobStoreDir = null;
    try (BlobServer server = new BlobServer(config, new VoidBlobStore());
            BlobCacheService cache = new BlobCacheService(config, new VoidBlobStore(),
                    new InetSocketAddress("localhost", server.getPort()))) {

        server.start();

        // store the data on the server
        byte[] data = new byte[2000000];
        rnd.nextBytes(data);
        BlobKey blobKey = put(server, jobId, data, blobType);
        verifyType(blobType, blobKey);

        // make sure the blob cache cannot create any files in its storage dir
        if (blobType == PERMANENT_BLOB) {
            jobStoreDir = cache.getPermanentBlobService().getStorageLocation(jobId, new PermanentBlobKey())
                    .getParentFile();
        } else {
            jobStoreDir = cache.getTransientBlobService().getStorageLocation(jobId, new TransientBlobKey())
                    .getParentFile();
        }
        assertTrue(jobStoreDir.setExecutable(true, false));
        assertTrue(jobStoreDir.setReadable(true, false));
        assertTrue(jobStoreDir.setWritable(false, false));

        // request the file from the server via the cache
        exception.expect(AccessDeniedException.class);

        try {
            get(cache, jobId, blobKey);
        } finally {
            // there should be no remaining incoming files
            File incomingFileDir = new File(jobStoreDir.getParent(), "incoming");
            assertArrayEquals(new String[] {}, incomingFileDir.list());

            // there should be no files in the job directory
            assertArrayEquals(new String[] {}, jobStoreDir.list());

            // if transient, the get will fail but since the download was successful, the file
            // will not be on the server anymore
            if (blobType == TRANSIENT_BLOB) {
                verifyDeletedEventually(server, jobId, blobKey);
            } else {
                assertTrue(server.getStorageLocation(jobId, blobKey).exists());
            }
        }
    } finally {
        // set writable again to make sure we can remove the directory
        if (jobStoreDir != null) {
            //noinspection ResultOfMethodCallIgnored
            jobStoreDir.setWritable(true, false);
        }
    }
}

From source file:org.pepstock.jem.node.tasks.platform.WindowsPlatform.java

/**
 * Writes a script file, using WINDOWS CMD syntax, to execute the job
 * /* w  ww .  j a v  a2 s .c  o  m*/
 * @param file file to write with all statements
 * @param job job which must be executed
 * @param jCommand java command to use
 * @throws IOException if any errors occurs
 */
private void write(File file, JavaCommand jCommand) throws IOException {
    PrintWriter fos = null;
    try {
        // writes the job shell script
        fos = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), CharSet.DEFAULT));
        // echo off
        fos.println("@echo off");
        // if it has got the classpath
        if (jCommand.getClassPath() != null) {
            // gets separator
            String pathSeparator = File.pathSeparator;
            String classPathProperty = jCommand.getClassPath();
            // splits classpath
            String[] filesNames = classPathProperty.split(pathSeparator);
            // creates a record of shell script file
            // setting all classpath            
            for (int i = 0; i < filesNames.length; i++) {
                if (i == 0) {
                    fos.println("set CLASSPATH=" + filesNames[i]);
                } else {
                    fos.println("set CLASSPATH=%CLASSPATH%;" + filesNames[i]);
                }
            }
        }
        // writes the command
        fos.println(jCommand.toCommandLine());
    } finally {
        // ALWAYS it closes the widnows CMD file
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (Exception e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
    // sets the file as EXECUTABLE!!
    file.setExecutable(true, false);
}

From source file:org.pepstock.jem.node.tasks.platform.UnixPlatform.java

/**
 * Writes a script file, using BASH syntax, to execute the job
 * /*from   ww w  . java  2s . c o m*/
 * @param file file to write with all statements
 * @param job job which must be executed
 * @param jCommand java command to use
 * @throws IOException if any errors occurs
 */
private void write(File file, Job job, JavaCommand jCommand) throws IOException {
    // gets user
    String user = job.isUserSurrogated() ? job.getJcl().getUser() : job.getUser();
    PrintWriter fos = null;
    try {
        // writes the job shell script
        fos = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), CharSet.DEFAULT));
        // if it has got the classpath
        if (jCommand.getClassPath() != null) {
            // gets separator
            String pathSeparator = File.pathSeparator;
            String classPathProperty = jCommand.getClassPath();
            // splits classpath
            String[] filesNames = classPathProperty.split(pathSeparator);
            // creates a record of shell script file
            // setting all classpath
            for (int i = 0; i < filesNames.length; i++) {
                if (i == 0) {
                    fos.println("CLASSPATH=" + filesNames[i]);
                } else {
                    fos.println("CLASSPATH=$CLASSPATH:" + filesNames[i]);
                }
            }
        }
        // writes the sudo command
        fos.println("sudo -n -u " + user + " -i " + jCommand.toCommandLine());
    } finally {
        // ALWAYS it closes the shell script file
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (Exception e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
    // sets the file as EXECUTABLE!!
    file.setExecutable(true, false);
}

From source file:com.igormaznitsa.mvngolang.utils.UnpackUtils.java

public static int unpackFileToFolder(@Nonnull final Log logger, @Nullable final String folder,
        @Nonnull final File archiveFile, @Nonnull final File destinationFolder, final boolean makeAllExecutable)
        throws IOException {
    final String normalizedName = archiveFile.getName().toLowerCase(Locale.ENGLISH);

    final ArchEntryGetter entryGetter;

    boolean modeZipFile = false;

    final ZipFile theZipFile;
    final ArchiveInputStream archInputStream;
    if (normalizedName.endsWith(".zip")) {
        logger.debug("Detected ZIP archive");

        modeZipFile = true;/*www  .  j  a  v  a 2  s  .co  m*/

        theZipFile = new ZipFile(archiveFile);
        archInputStream = null;
        entryGetter = new ArchEntryGetter() {
            private final Enumeration<ZipArchiveEntry> iterator = theZipFile.getEntries();

            @Override
            @Nullable
            public ArchiveEntry getNextEntry() throws IOException {
                ArchiveEntry result = null;
                if (this.iterator.hasMoreElements()) {
                    result = this.iterator.nextElement();
                }
                return result;
            }
        };
    } else {
        theZipFile = null;
        final InputStream in = new BufferedInputStream(new FileInputStream(archiveFile));
        try {
            if (normalizedName.endsWith(".tar.gz")) {
                logger.debug("Detected TAR.GZ archive");
                archInputStream = new TarArchiveInputStream(new GZIPInputStream(in));

                entryGetter = new ArchEntryGetter() {
                    @Override
                    @Nullable
                    public ArchiveEntry getNextEntry() throws IOException {
                        return ((TarArchiveInputStream) archInputStream).getNextTarEntry();
                    }
                };

            } else {
                logger.debug("Detected OTHER archive");
                archInputStream = ARCHIVE_STREAM_FACTORY.createArchiveInputStream(in);
                logger.debug("Created archive stream : " + archInputStream.getClass().getName());

                entryGetter = new ArchEntryGetter() {
                    @Override
                    @Nullable
                    public ArchiveEntry getNextEntry() throws IOException {
                        return archInputStream.getNextEntry();
                    }
                };
            }

        } catch (ArchiveException ex) {
            IOUtils.closeQuietly(in);
            throw new IOException("Can't recognize or read archive file : " + archiveFile, ex);
        } catch (CantReadArchiveEntryException ex) {
            IOUtils.closeQuietly(in);
            throw new IOException("Can't read entry from archive file : " + archiveFile, ex);
        }
    }

    try {

        final String normalizedFolder = folder == null ? null : FilenameUtils.normalize(folder, true) + '/';

        int unpackedFilesCounter = 0;
        while (true) {
            final ArchiveEntry entry = entryGetter.getNextEntry();
            if (entry == null) {
                break;
            }
            final String normalizedPath = FilenameUtils.normalize(entry.getName(), true);

            logger.debug("Detected archive entry : " + normalizedPath);

            if (normalizedFolder == null || normalizedPath.startsWith(normalizedFolder)) {
                final File targetFile = new File(destinationFolder, normalizedFolder == null ? normalizedPath
                        : normalizedPath.substring(normalizedFolder.length()));
                if (entry.isDirectory()) {
                    logger.debug("Folder : " + normalizedPath);
                    if (!targetFile.exists() && !targetFile.mkdirs()) {
                        throw new IOException("Can't create folder " + targetFile);
                    }
                } else {
                    final File parent = targetFile.getParentFile();

                    if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
                        throw new IOException("Can't create folder : " + parent);
                    }

                    final FileOutputStream fos = new FileOutputStream(targetFile);

                    try {
                        if (modeZipFile) {
                            logger.debug("Unpacking ZIP entry : " + normalizedPath);

                            final InputStream zipEntryInStream = theZipFile
                                    .getInputStream((ZipArchiveEntry) entry);
                            try {
                                if (IOUtils.copy(zipEntryInStream, fos) != entry.getSize()) {
                                    throw new IOException(
                                            "Can't unpack file, illegal unpacked length : " + entry.getName());
                                }
                            } finally {
                                IOUtils.closeQuietly(zipEntryInStream);
                            }
                        } else {
                            logger.debug("Unpacking archive entry : " + normalizedPath);

                            if (!archInputStream.canReadEntryData(entry)) {
                                throw new IOException("Can't read archive entry data : " + normalizedPath);
                            }
                            if (IOUtils.copy(archInputStream, fos) != entry.getSize()) {
                                throw new IOException(
                                        "Can't unpack file, illegal unpacked length : " + entry.getName());
                            }
                        }
                    } finally {
                        fos.close();
                    }

                    if (makeAllExecutable) {
                        try {
                            targetFile.setExecutable(true, true);
                        } catch (SecurityException ex) {
                            throw new IOException("Can't make file executable : " + targetFile, ex);
                        }
                    }
                    unpackedFilesCounter++;
                }
            } else {
                logger.debug("Archive entry " + normalizedPath + " ignored");
            }
        }
        return unpackedFilesCounter;
    } finally {
        IOUtils.closeQuietly(theZipFile);
        IOUtils.closeQuietly(archInputStream);
    }
}

From source file:com.kalix.tools.kibana.KibanaController.java

/**
 * download kibana from remote server/*from w ww.  j  a  v a  2  s.c  o  m*/
 *
 * @throws Exception
 */
public void download() throws Exception {
    File target = new File(workingDirectory, KIBANA_FOLDER);
    if (target.exists()) {
        LOGGER.warn("Kibana folder already exists, download is skipped");
        return;
    }
    LOGGER.debug("Downloading Kibana from {}", KIBANA_LOCATION);
    if (isWindows()) {
        try (ZipArchiveInputStream inputStream = new ZipArchiveInputStream(
                new URL(KIBANA_LOCATION).openStream())) {
            ZipArchiveEntry entry;
            while ((entry = (ZipArchiveEntry) inputStream.getNextEntry()) != null) {
                File file = new File(workingDirectory, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    int read;
                    byte[] buffer = new byte[4096];
                    try (FileOutputStream outputStream = new FileOutputStream(file)) {
                        while ((read = inputStream.read(buffer, 0, 4096)) != -1) {
                            outputStream.write(buffer, 0, read);
                        }
                    }
                }
            }
        }
    } else {
        try (GzipCompressorInputStream gzInputStream = new GzipCompressorInputStream(
                new URL(KIBANA_LOCATION).openStream())) {
            try (TarArchiveInputStream inputStream = new TarArchiveInputStream(gzInputStream)) {
                TarArchiveEntry entry;
                while ((entry = (TarArchiveEntry) inputStream.getNextEntry()) != null) {
                    File file = new File(workingDirectory, entry.getName());
                    if (entry.isDirectory()) {
                        file.mkdirs();
                    } else {
                        int read;
                        byte[] buffer = new byte[4096];
                        try (FileOutputStream outputStream = new FileOutputStream(file)) {
                            while ((read = inputStream.read(buffer, 0, 4096)) != -1) {
                                outputStream.write(buffer, 0, read);
                            }
                        }
                        file.setLastModified(entry.getLastModifiedDate().getTime());
                        if (entry instanceof TarArchiveEntry) {
                            int mode = ((TarArchiveEntry) entry).getMode();
                            if ((mode & 00100) > 0) {
                                file.setExecutable(true, (mode & 00001) == 0);
                            }
                        }
                    }
                }
            }
        }
    }
    overrideConfig();
}