Example usage for java.io File setReadable

List of usage examples for java.io File setReadable

Introduction

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

Prototype

public boolean setReadable(boolean readable, boolean ownerOnly) 

Source Link

Document

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

Usage

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

/**
 * Uploads a byte array to a server which cannot move incoming files to the final blob store via
 * the {@link BlobServer}. File transfers should fail.
 *
 * @param jobId//from ww w  . j av a 2  s  .  c  om
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsStore(@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 jobStoreDir = null;
    try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

        server.start();

        // make sure the blob server cannot create any files in its storage dir
        jobStoreDir = server.getStorageLocation(jobId, BlobKey.createKey(blobType)).getParentFile();
        assertTrue(jobStoreDir.setExecutable(true, false));
        assertTrue(jobStoreDir.setReadable(true, false));
        assertTrue(jobStoreDir.setWritable(false, false));

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // upload the file to the server directly
        exception.expect(AccessDeniedException.class);

        try {
            put(server, jobId, data, blobType);
        } 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());
        }
    } finally {
        // set writable again to make sure we can remove the directory
        if (jobStoreDir != null) {
            //noinspection ResultOfMethodCallIgnored
            jobStoreDir.setWritable(true, false);
        }
    }
}

From source file:hudson.plugins.project_inheritance.projects.view.InheritanceViewAction.java

private void dumpMasterScript(boolean isLinux, List<File> generatedScripts, File srcDir) throws IOException {
    Map<String, String> parameters = getResolvedBuildParameters(this.getBuild());

    String scrFile = (isLinux) ? "build.sh" : "build.bat";
    String scrPreamble = (isLinux) ? "#!/bin/bash" : "@echo off";
    String scrSetCmd = (isLinux) ? "export" : "set";
    String scrInvoke = (isLinux) ? "./" : "CALL ";
    String lineEnd = (isLinux) ? "\n" : "\r\n";

    File mainScript = new File(srcDir, scrFile);
    BufferedWriter out = new BufferedWriter(new FileWriter(mainScript, true));
    out.write(scrPreamble);//from   w w w  .j ava2s  .co m
    out.write(lineEnd);

    if (parameters.size() > 0) {
        for (String parameter : parameters.keySet()) {
            out.write(
                    String.format("%s %s=\"%s\"%s", scrSetCmd, parameter, parameters.get(parameter), lineEnd));
        }
    }

    for (File script : generatedScripts) {
        if (isLinux) {
            out.write(String.format("echo 'Will run %s now ...'%s", script.getName(), lineEnd));
        } else {
            out.write(String.format("echo Will run %s now ...%s", script.getName(), lineEnd));
        }
        out.write(String.format("%s%s%s", scrInvoke, script.getName(), lineEnd));
    }
    if (isLinux) {
        mainScript.setExecutable(true, false);
        mainScript.setWritable(true, false);
        mainScript.setReadable(true, false);
    }
    out.close();
    generatedScripts.add(mainScript);
}

From source file:com.thoughtworks.go.server.service.GoConfigServiceTest.java

@Test
public void shouldThrowIfCruiseHasNoReadPermissionOnArtifactsDir() throws Exception {
    if (SystemUtils.IS_OS_WINDOWS) {
        return;/* www.  ja va2  s.c  o m*/
    }

    File artifactsDir = FileUtil.createTempFolder();
    artifactsDir.setReadable(false, false);
    cruiseConfig.setServerConfig(new ServerConfig(artifactsDir.getAbsolutePath(), new SecurityConfig()));
    expectLoad(cruiseConfig);

    try {
        goConfigService.initialize();
        fail("should throw when cruise has no read permission on artifacts dir "
                + artifactsDir.getAbsolutePath());
    } catch (Exception e) {
        assertThat(e.getMessage(),
                is("Cruise does not have read permission on " + artifactsDir.getAbsolutePath()));
    } finally {
        FileUtils.deleteQuietly(artifactsDir);
    }

}

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);
    f.setWritable(true, true);//from   w w w  .  jav  a 2s . com
    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);
    f.setWritable(true, true);/*  w w w  .  jav  a  2 s . c o  m*/
    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.BlobCachePutTest.java

/**
 * Uploads a byte array to a server which cannot create incoming files via the {@link
 * BlobCacheService}. File transfers should fail.
 *
 * @param jobId//w w w . jav a  2s . co  m
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsIncoming(@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();

        // make sure the blob server cannot create any files in its storage dir
        tempFileDir = server.createTemporaryFilename().getParentFile();
        assertTrue(tempFileDir.setExecutable(true, false));
        assertTrue(tempFileDir.setReadable(true, false));
        assertTrue(tempFileDir.setWritable(false, false));

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // upload the file to the server via the cache
        exception.expect(IOException.class);
        exception.expectMessage("PUT operation failed: ");

        try {
            put(cache, jobId, data, blobType);
        } finally {
            File storageDir = tempFileDir.getParentFile();
            // only the incoming directory should exist (no job directory!)
            assertArrayEquals(new String[] { "incoming" }, storageDir.list());
        }
    } 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.BlobCachePutTest.java

/**
 * Uploads a byte array to a server which cannot create any files via the {@link
 * BlobCacheService}. File transfers should fail.
 *
 * @param jobId/*from  w  ww . jav a  2 s . co m*/
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testPutBufferFails(@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();

        // make sure the blob server cannot create any files in its storage dir
        tempFileDir = server.createTemporaryFilename().getParentFile().getParentFile();
        assertTrue(tempFileDir.setExecutable(true, false));
        assertTrue(tempFileDir.setReadable(true, false));
        assertTrue(tempFileDir.setWritable(false, false));

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // upload the file to the server via the cache
        exception.expect(IOException.class);
        exception.expectMessage("PUT operation failed: ");

        put(cache, jobId, data, blobType);

    } 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.BlobCachePutTest.java

/**
 * Uploads a byte array to a server which cannot create files via the {@link BlobCacheService}.
 * File transfers should fail./*from www  . j av a  2s  .  c o m*/
 *
 * @param jobId
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsStore(@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 jobStoreDir = null;
    try (BlobServer server = new BlobServer(config, new VoidBlobStore());
            BlobCacheService cache = new BlobCacheService(config, new VoidBlobStore(),
                    new InetSocketAddress("localhost", server.getPort()))) {

        server.start();

        // make sure the blob server cannot create any files in its storage dir
        jobStoreDir = server.getStorageLocation(jobId, BlobKey.createKey(blobType)).getParentFile();
        assertTrue(jobStoreDir.setExecutable(true, false));
        assertTrue(jobStoreDir.setReadable(true, false));
        assertTrue(jobStoreDir.setWritable(false, false));

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // upload the file to the server via the cache
        exception.expect(IOException.class);
        exception.expectMessage("PUT operation failed: ");

        try {
            put(cache, jobId, data, blobType);
        } 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());
        }
    } finally {
        // set writable again to make sure we can remove the directory
        if (jobStoreDir != null) {
            //noinspection ResultOfMethodCallIgnored
            jobStoreDir.setWritable(true, false);
        }
    }
}

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  .j  a v a  2s.  c o m
        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:org.apache.flink.runtime.blob.BlobCacheGetTest.java

/**
 * Retrieves a BLOB via a {@link BlobCacheService} which cannot create incoming files. File
 * transfers should fail.//from  ww  w.  j av a 2  s  .c  om
 *
 * @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);
        }
    }
}