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:com.seedboxer.seedboxer.sources.processors.QueueProcessor.java

private String downloadFile(URL url, String path) throws IOException {
    URLConnection conn = url.openConnection();
    InputStream in = conn.getInputStream();
    String disposition = conn.getHeaderField("Content-Disposition");
    String fileNameProperty = "filename=\"";
    String fileName = disposition.substring(disposition.indexOf(fileNameProperty),
            disposition.lastIndexOf("\""));
    fileName = fileName.substring(fileNameProperty.length(), fileName.length());
    path += File.separator + fileName;
    File file = new File(path);
    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    byte[] bytes = new byte[1024];
    int read;/*from   w  w  w  .j a  v a  2s  . co m*/
    while ((read = in.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    in.close();
    out.close();
    file.setReadable(true, false);
    file.setWritable(true, false);
    return fileName;
}

From source file:org.rhq.enterprise.server.plugins.jdr.JdrServerPluginComponent.java

private void writeAccessToken() {
    File dataDir = new File(System.getProperty("jboss.server.data.dir"));
    if (!dataDir.exists() || !dataDir.canWrite()) {
        log.error("Failed to write access token, jboss.server.data.dir=" + dataDir
                + " does not exist or not writable");
        return;/* w  w  w . j  a v  a2s .  co  m*/
    }
    File file = new File(dataDir, TOKEN_FILE_NAME);

    try {
        PrintWriter pw = new PrintWriter(file);
        pw.println(accessToken);
        pw.close();
        file.setWritable(true, true);
        file.setReadable(true, true);
        file.setExecutable(false, false);
        boolean isWindows = (File.separatorChar == '\\');
        if (!isWindows) {
            try {
                Runtime.getRuntime().exec("chmod 600 " + file.getAbsolutePath());
            } catch (IOException e) {
                log.error("Unable to set file permissions", e);
            }
        }
    } catch (FileNotFoundException fnfe) {
        log.error("Failed to write acces token, jboss.server.data.dir=" + file.getParent()
                + " does not exist or not writable");
    }
}

From source file:free.rm.skytube.gui.businessobjects.updates.UpgradeAppTask.java

/**
 * Download the remote APK file and return an instance of {@link File}.
 *
 * @return   A {@link File} instance of the downloaded APK.
 * @throws IOException/*  ww w  .j a v  a2s  .c om*/
 */
private File downloadApk() throws IOException {
    WebStream webStream = new WebStream(this.apkUrl);
    File apkFile = File.createTempFile("skytube-upgrade", ".apk", apkDir);
    OutputStream out;

    // set the APK file to readable to every user so that this file can be read by Android's
    // package manager program
    apkFile.setReadable(true /*set file to readable*/, false /*set readable to every user on the system*/);
    out = new FileOutputStream(apkFile);

    // download the file by transferring bytes from in to out
    byte[] buf = new byte[1024];
    int totalBytesRead = 0;
    for (int bytesRead; (bytesRead = webStream.getStream().read(buf)) > 0;) {
        out.write(buf, 0, bytesRead);

        // update the progressbar of the downloadDialog
        totalBytesRead += bytesRead;
        publishProgress(totalBytesRead, webStream.getStreamSize());
    }

    // close the streams
    webStream.getStream().close();
    out.close();

    return apkFile;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.loc.AbstractServiceUpdater.java

private void deleteDatabase(final File db) {
    db.setReadable(true, true);
    db.setWritable(true, false);//ww w .  j  a v  a2 s. com

    if (db.isDirectory()) {
        for (final File file : db.listFiles()) {
            file.delete();
        }
        LOGGER.debug("[" + getClass().getSimpleName() + "] Successfully deleted database under: " + db);
    } else {
        db.delete();
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.loc.AbstractServiceUpdater.java

private void moveDirectory(final File existingDB, final File newDB) throws IOException {
    LOGGER.info("[" + getClass().getSimpleName() + "] Moving Location database from: " + newDB + ", to: "
            + existingDB);//from w  w  w  .  java 2  s.c o m

    for (final File file : existingDB.listFiles()) {
        file.setReadable(true, true);
        file.setWritable(true, false);
        file.delete();
    }

    existingDB.delete();
    Files.move(newDB.toPath(), existingDB.toPath(), StandardCopyOption.ATOMIC_MOVE);
}

From source file:org.apache.ambari.server.serveraction.kerberos.CreateKeytabFilesServerAction.java

/**
 * Ensures that the owner of the Ambari server process is the only local user account able to
 * read and write to the specified file or read, write to, and execute the specified directory.
 *
 * @param file the file or directory for which to modify access
 *//*from ww  w .  jav a 2  s  . com*/
private void ensureAmbariOnlyAccess(File file) {
    if (file.exists()) {
        if (!file.setReadable(false, false) || !file.setReadable(true, true)) {
            LOG.warn(String.format("Failed to set %s readable only by Ambari", file.getAbsolutePath()));
        }

        if (!file.setWritable(false, false) || !file.setWritable(true, true)) {
            LOG.warn(String.format("Failed to set %s writable only by Ambari", file.getAbsolutePath()));
        }

        if (file.isDirectory()) {
            if (!file.setExecutable(false, false) && !file.setExecutable(true, true)) {
                LOG.warn(String.format("Failed to set %s executable by Ambari", file.getAbsolutePath()));
            }
        } else {
            if (!file.setExecutable(false, false)) {
                LOG.warn(String.format("Failed to set %s not executable", file.getAbsolutePath()));
            }
        }
    }
}

From source file:com.seedboxer.seedboxer.ws.controller.DownloadsController.java

/**
 * Save torrent file to watch-dog directory of downloader application (rTorrent or uTorrent) and
 * add the same torrent to the user queue.
 *
 * @param fileName/*  ww w.jav  a2 s .  co m*/
 * @param torrentFileInStream
 * @throws Exception
 */
public void addTorrent(String username, String fileName, final InputStream torrentFileInStream)
        throws Exception {
    User user = getUser(username);

    File torrent = new File(watchDownloaderPath + File.separator + fileName);
    Files.copy(new InputSupplier<InputStream>() {
        @Override
        public InputStream getInput() throws IOException {
            return torrentFileInStream;
        }
    }, torrent);
    torrent.setReadable(true, false);
    torrent.setWritable(true, false);
    String name = TorrentUtils.getName(torrent);
    putToDownload(user, Collections.singletonList(name), false);
}

From source file:com.anthemengineering.mojo.infer.InferMojo.java

/**
 * Extracts a given infer.tar.xz file to the given directory.
 *
 * @param tarXzToExtract the file to extract
 * @param inferDownloadDir the directory to extract the file to
 *//*from   w  w  w.  jav a 2 s  .c  om*/
private static void extract(File tarXzToExtract, File inferDownloadDir) throws IOException {

    FileInputStream fin = null;
    BufferedInputStream in = null;
    XZCompressorInputStream xzIn = null;
    TarArchiveInputStream tarIn = null;

    try {
        fin = new FileInputStream(tarXzToExtract);
        in = new BufferedInputStream(fin);
        xzIn = new XZCompressorInputStream(in);
        tarIn = new TarArchiveInputStream(xzIn);

        TarArchiveEntry entry;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            final File fileToWrite = new File(inferDownloadDir, entry.getName());

            if (entry.isDirectory()) {
                FileUtils.forceMkdir(fileToWrite);
            } else {
                BufferedOutputStream out = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream(fileToWrite));
                    final byte[] buffer = new byte[4096];
                    int n = 0;
                    while (-1 != (n = tarIn.read(buffer))) {
                        out.write(buffer, 0, n);
                    }
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }

            // assign file permissions
            final int mode = entry.getMode();

            fileToWrite.setReadable((mode & 0004) != 0, false);
            fileToWrite.setReadable((mode & 0400) != 0, true);
            fileToWrite.setWritable((mode & 0002) != 0, false);
            fileToWrite.setWritable((mode & 0200) != 0, true);
            fileToWrite.setExecutable((mode & 0001) != 0, false);
            fileToWrite.setExecutable((mode & 0100) != 0, true);
        }
    } finally {
        if (tarIn != null) {
            tarIn.close();
        }
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePrivateKeyDataProvider.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testGetEncryptedPrivateKeyData02() throws IOException {
    final String fileName = "testGetEncryptedPrivateKeyData02.key";
    File file = new File(fileName);
    file = file.getCanonicalFile();/* w w w  . j a va2 s .com*/

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x01, 0x71, 0x33 };

    FileUtils.writeByteArrayToFile(file, data);

    try {
        assertTrue("Setting the file to not-readable should have succeeded.", file.setReadable(false, false));
        assertFalse("The file should not be readable.", file.canRead());
        assertTrue("The file should still be writable.", file.canWrite());

        FilePrivateKeyDataProvider provider = new FilePrivateKeyDataProvider(file);

        try {
            provider.getEncryptedPrivateKeyData();
            fail("Expected exception KeyNotFoundException.");
        } catch (KeyNotFoundException e) {
            assertNotNull("The cause should not be null.", e.getCause());
        }
    } finally {
        FileUtils.forceDelete(file);
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePublicKeyDataProvider.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testGetEncryptedPublicKeyData02() throws IOException {
    final String fileName = "testGetEncryptedPublicKeyData02.key";
    File file = new File(fileName);
    file = file.getCanonicalFile();/*from   ww w.j  a  v  a2  s  .c  o  m*/

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x01, 0x71, 0x33 };

    FileUtils.writeByteArrayToFile(file, data);

    try {
        assertTrue("Setting the file to not-readable should have succeeded.", file.setReadable(false, false));
        assertFalse("The file should not be readable.", file.canRead());
        assertTrue("The file should still be writable.", file.canWrite());

        FilePublicKeyDataProvider provider = new FilePublicKeyDataProvider(file);

        try {
            provider.getEncryptedPublicKeyData();
            fail("Expected exception KeyNotFoundException.");
        } catch (KeyNotFoundException e) {
            assertNotNull("The cause should not be null.", e.getCause());
        }
    } finally {
        FileUtils.forceDelete(file);
    }
}