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.solr.core.TestCoreDiscovery.java

@Test
public void testCoreDirCantRead() throws Exception {
    File coreDir = solrHomeDirectory;
    setMeUp(coreDir.getAbsolutePath());/*  w  ww  .j av a  2 s .c  om*/
    addCoreWithProps(makeCorePropFile("core1", false, true),
            new File(coreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));

    // Insure that another core is opened successfully
    addCoreWithProps(makeCorePropFile("core2", false, false, "dataDir=core2"),
            new File(coreDir, "core2" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));

    File toSet = new File(coreDir, "core1");
    assumeTrue("Cannot make " + toSet + " non-readable. Test aborted.", toSet.setReadable(false, false));
    CoreContainer cc = init();
    try (SolrCore core1 = cc.getCore("core1"); SolrCore core2 = cc.getCore("core2")) {
        assertNull(core1);
        assertNotNull(core2);
    } finally {
        cc.shutdown();
    }
    // So things can be cleaned up by the framework!
    toSet.setReadable(true, false);
}

From source file:com.puppycrawl.tools.checkstyle.MainTest.java

@Test
public void testExistingTargetFilePlainOutputToFileWithoutRwPermissions() throws Exception {
    final File file = temporaryFolder.newFile("file.output");
    assertTrue(file.setReadable(true, true));
    assertTrue(file.setWritable(false, false));
    exit.expectSystemExitWithStatus(-1);
    exit.checkAssertionAfterwards(new Assertion() {
        @Override/*w  w w  . j  a v a2  s . c o  m*/
        public void checkAssertion() throws IOException {
            assertEquals("Permission denied : '" + file.getCanonicalPath() + "'." + System.lineSeparator(),
                    systemOut.getLog());
            assertEquals("", systemErr.getLog());
        }
    });
    Main.main("-c", "src/test/resources/com/puppycrawl/tools/checkstyle/config-classname.xml", "-f", "plain",
            "-o", file.getCanonicalPath(), "src/test/resources/com/puppycrawl/tools/checkstyle/InputMain.java");
}

From source file:gov.jgi.meta.MetaUtils.java

public static File createTempDir(String prefix, String tmpDir) throws IOException {
    final File sysTempDir = new File(tmpDir);
    File newTempDir;
    final int maxAttempts = 9;
    int attemptCount = 0;

    do {//from w  ww  .  j ava 2s .  c om
        attemptCount++;
        if (attemptCount > maxAttempts) {
            throw new IOException(
                    "The highly improbable has occurred! Failed to create a unique temporary directory after "
                            + maxAttempts + " attempts.");
        }
        String dirName = prefix + UUID.randomUUID().toString();
        newTempDir = new File(sysTempDir, dirName);
    } while (newTempDir.exists());

    try {
        FileUtils.forceMkdir(newTempDir);
    } catch (Exception e) {
        throw new IOException("Failed to create temp dir named " + newTempDir.getAbsolutePath() + ". Reason: "
                + e.getMessage(), e);
    }

    if (!(newTempDir.setExecutable(true, false) && newTempDir.setReadable(true, false)
            && newTempDir.setWritable(true, false))) {
        throw new IOException("unable to set RWX bits to 777");
    }

    return (newTempDir);
}

From source file:org.eclipse.thym.blackberry.core.bdt.BlackBerryProjectGenerator.java

private void copyFilesToProject(HybridMobileLibraryResolver resolver, IPath project_path) throws IOException {
    IPath nodeModulesDest = project_path.append("cordova").append("node_modules");
    IPath bbtoolsBinDest = project_path.append("cordova").append("dependencies").append("bb-tools")
            .append("bin");
    IPath bbtoolsLibDest = project_path.append("cordova").append("dependencies").append("bb-tools")
            .append("lib");
    String bbNativePackager = "blackberry-nativepackager";
    String bbSigner = "blackberry-signer";
    String bbDeploy = "blackberry-deploy";
    String bbDebugTokenRequest = "blackberry-debugtokenrequest";

    // create project using template directory
    if (!project_path.toFile().exists()) {
        project_path.toFile().mkdir();// ww  w. j  av a 2s  . c  om
    }
    directoryCopy(resolver.getTemplateFile(new Path("templateDir")), toURL(project_path.toFile()));

    // copy repo level target tool to project
    fileCopy(resolver.getTemplateFile(new Path("target")), toURL(project_path.append("cordova").toFile()));
    fileCopy(resolver.getTemplateFile(new Path("target.bat")), toURL(project_path.append("cordova").toFile()));
    fileCopy(resolver.getTemplateFile(new Path("lib/target.js")),
            toURL(project_path.append("cordova").append("lib").toFile()));
    fileCopy(resolver.getTemplateFile(new Path("lib.config.js")),
            toURL(project_path.append("cordova").append("lib").toFile()));

    // copy repo level init script to project
    fileCopy(resolver.getTemplateFile(new Path("whereis.cmd")), toURL(project_path.append("cordova").toFile()));
    fileCopy(resolver.getTemplateFile(new Path("init.bat")), toURL(project_path.append("cordova").toFile()));
    fileCopy(resolver.getTemplateFile(new Path("init")), toURL(project_path.append("cordova").toFile()));

    //copy VERSION file [used to identify corresponding ~/.cordova/lib directory for dependencies]
    URL versionFile = resolver.getTemplateFile(new Path("VERSION"));
    fileCopy(versionFile, toURL(project_path.toFile()));
    String version = "";
    BufferedReader r = null;
    try {
        r = new BufferedReader(new FileReader(versionFile.getFile()));
        String line = r.readLine();
        version = line.replaceAll("([^\\x00-\\xFF]|\\s)*", "");
    } finally {
        if (r != null) {
            r.close();
        }
    }

    // copy repo level check_reqs script to project
    fileCopy(resolver.getTemplateFile(new Path("check_reqs.bat")),
            toURL(project_path.append("cordova").toFile()));
    fileCopy(resolver.getTemplateFile(new Path("check_reqs")), toURL(project_path.append("cordova").toFile()));

    // change file permission for cordova scripts because ant copy doesn't preserve file permissions
    project_path.toFile().setExecutable(true);
    project_path.toFile().setWritable(true);
    project_path.toFile().setReadable(true);

    //copy cordova-*version*.js to www
    fileCopy(resolver.getTemplateFile(new Path("cordova.js")), toURL(project_path.append("www").toFile()));

    //copy node modules to cordova build directory
    File nodeModules = project_path.append("cordova").append("node_modules").toFile();
    if (!nodeModules.exists()) {
        nodeModules.mkdir();
    }
    nodeModules.setExecutable(true, false);
    nodeModules.setWritable(true, false);
    nodeModules.setReadable(true, false);
    directoryCopy(resolver.getTemplateFile(new Path("node_modules")), toURL(nodeModules));

    //copy framework bootstrap
    for (String target : TARGETS) {
        IPath chromeDir = project_path.append("native").append(target).append("chrome");
        IPath frameworkLibDir = chromeDir.append("lib");
        if (!frameworkLibDir.toFile().exists()) {
            frameworkLibDir.toFile().mkdir();
        }
        directoryCopy(resolver.getTemplateFile(new Path("bootstrapDir")), toURL(chromeDir.toFile()));
        directoryCopy(resolver.getTemplateFile(new Path("frameworkLibDir")), toURL(frameworkLibDir.toFile()));
    }

    // save release
    IPath updateDir = project_path.append("lib").append("cordova.").append(version);
    if (!updateDir.toFile().exists()) {
        updateDir.toFile().mkdir();
    }
    directoryCopy(resolver.getTemplateFile(new Path("buildDir")), toURL(updateDir.toFile()));
}

From source file:com.asakusafw.operation.tools.hadoop.fs.CleanTest.java

private void assumeAccessRestrictionAvailable() throws IOException {
    File f = File.createTempFile("access-restriction-check", ".dummy");
    f.setReadable(false, false);
    try {//from w  w  w .  j ava  2 s  .c o m
        if (f.canRead()) {
            System.err.println("Current context does not support access restriction.");
            Assume.assumeTrue(false);
        }
    } finally {
        f.setReadable(true, true);
        if (f.delete() == false) {
            System.err.printf("Failed to delete a dummy file: %s%n", f);
        }
    }
}

From source file:org.apache.solr.core.TestCoreDiscovery.java

@Test
public void testFileCantRead() throws Exception {
    File coreDir = solrHomeDirectory;
    setMeUp(coreDir.getAbsolutePath());//from  w w w.j  a v  a2s.co m
    addCoreWithProps(makeCorePropFile("core1", false, true),
            new File(coreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));

    File toSet = new File(solrHomeDirectory, "cantReadFile");
    assertTrue("Should have been able to make file '" + toSet.getAbsolutePath() + "' ", toSet.createNewFile());
    assumeTrue("Cannot make " + toSet + " non-readable. Test aborted.", toSet.setReadable(false, false));
    CoreContainer cc = init();
    try (SolrCore core1 = cc.getCore("core1")) {
        assertNotNull(core1); // Should still be able to create core despite r/o file.
    } finally {
        cc.shutdown();
    }
    // So things can be cleaned up by the framework!
    toSet.setReadable(true, false);
}

From source file:org.apache.solr.core.TestCoreDiscovery.java

@Test
public void testNonCoreDirCantRead() throws Exception {
    File coreDir = solrHomeDirectory;
    setMeUp(coreDir.getAbsolutePath());//from  w ww.j a  v a 2 s. co  m
    addCoreWithProps(makeCorePropFile("core1", false, true),
            new File(coreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));

    addCoreWithProps(makeCorePropFile("core2", false, false, "dataDir=core2"),
            new File(coreDir, "core2" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));

    File toSet = new File(solrHomeDirectory, "cantReadDir");
    assertTrue("Should have been able to make directory '" + toSet.getAbsolutePath() + "' ", toSet.mkdirs());
    assumeTrue("Cannot make " + toSet + " non-readable. Test aborted.", toSet.setReadable(false, false));
    CoreContainer cc = init();
    try (SolrCore core1 = cc.getCore("core1"); SolrCore core2 = cc.getCore("core2")) {
        assertNotNull(core1); // Should be able to open the perfectly valid core1 despite a non-readable directory
        assertNotNull(core2);
    } finally {
        cc.shutdown();
    }
    // So things can be cleaned up by the framework!
    toSet.setReadable(true, false);

}

From source file:com.cmart.PageControllers.SellItemImagesController.java

public void saveImages(String baseURL) {
    //System.out.println("sellitemimagecont: looking for image to upload!");
    //System.out.println("saving images :" + baseURL);
    baseURL = baseURL + "/" + GV.REMOTE_IMAGE_DIR + "/";

    // Special case for the thumbnail
    /*if(this.images.size()>1){
       FileItem image = this.images.get(0);
               /*from www .  ja v  a 2 s  .  c o m*/
       //TODO: compress an image
       String[] ext = image.getName().split("\\.");
       int extIndex = ext.length>0 ? ext.length-1 : 0;
       String filename = this.itemID + "_" + 0 + "." + ext[extIndex];
       String URL = filename;
               
       // Setup the thumbnail file
       File file = new File(GlobalVars.localImageDir, filename);
       file.setReadable(true, false);
       file.setWritable(true, false);
               
       try {
    image.write(file);
            
    GlobalVars.db.insertThumbnail(this.itemID, URL);
       } catch (Exception e) {
    // TODO Auto-generated catch block
    this.errors.add(new Error("SellItemImagesController (saveImages): Could not save thumbnail", e));
    e.printStackTrace();
       }
    }*/
    boolean thumbnail = true;

    // Loop through all the images
    for (int i = 0; i < this.images.size(); i++) {
        FileItem image = this.images.get(i);

        //TODO: make number start from one and only count real images

        if (image.getSize() > 0) {
            // Make the file name and path
            String[] ext = image.getName().split("\\.");
            int extIndex = ext.length > 0 ? ext.length - 1 : 0;
            String filename = this.itemID + "_" + (i + 1) + "." + ext[extIndex];
            //String URL = filename;

            // Setup the image file
            //System.out.println("setting temp dir as the image");
            File file = new File(GV.LOCAL_TEMP_DIR, filename + "tmp");
            file.setReadable(true, false);
            file.setWritable(true, false);

            //System.out.println("URL :" + URL);
            //System.out.println("name :" + filename);
            //System.out.println("local :" + GV.LOCAL_IMAGE_DIR);
            //System.out.println("remote :" + GV.REMOTE_IMAGE_DIR);

            try {
                //System.out.println("doing db insert");
                GV.DB.insertImage(this.itemID, i + 1, filename, "");

                //System.out.println("saving image");
                image.write(file);

                //System.out.println("mkaing file in img dir");
                File file2 = new File(GV.LOCAL_IMAGE_DIR, filename);

                //System.out.println("doing the image resize");
                BufferedImage originalImage2 = ImageIO.read(file);
                int type2 = originalImage2.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                        : originalImage2.getType();

                //System.out.println("doing the image resize second step");
                BufferedImage resizeImageHintJpg2 = resizeImageWithHint(originalImage2, type2, 500, 450);
                ImageIO.write(resizeImageHintJpg2, "jpg", file2);

                try {
                    file.delete();
                } catch (Exception e) {

                }

                //System.out.println("sellitemimagecont: inserted an image!");

                if (thumbnail) {
                    //TODO: some image compression
                    String thumbName = this.itemID + "_" + 0 + "." + ext[extIndex];
                    GV.DB.insertThumbnail(this.itemID, thumbName);

                    //System.out.println("doing thumbnail");

                    File thumbFile = new File(GV.LOCAL_IMAGE_DIR, thumbName);

                    // Get a JPEG writer
                    // TODO: other formats??
                    /*ImageWriter writer = null;
                      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
                      if (iter.hasNext()) {
                          writer = (ImageWriter)iter.next();
                      }
                            
                      // Set the output file
                      ImageOutputStream ios = ImageIO.createImageOutputStream(thumbFile);
                      writer.setOutput(ios);
                              
                      // Set the compression level
                      JPEGImageWriteParam imgparams = new JPEGImageWriteParam(Locale.getDefault());
                      imgparams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
                      imgparams.setCompressionQuality(128);
                              
                      // Write the compressed file
                      RenderedImage rendFile = ImageIO.read(file);
                      writer.write(null, new IIOImage(rendFile, null, null), imgparams);
                              
                              
                              
                            
                    // copy file
                    InputStream fin = new FileInputStream(file);
                    OutputStream fout = new FileOutputStream(thumbFile);
                    byte[] buff = new byte[1024];
                    int len;
                            
                    while((len = fin.read(buff)) > 0)
                         fout.write(buff, 0, len);
                            
                    fin.close();
                    fout.close();
                    */

                    BufferedImage originalImage = ImageIO.read(file2);
                    int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                            : originalImage.getType();

                    BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type, 100, 100);
                    ImageIO.write(resizeImageHintJpg, "jpg", thumbFile);

                    thumbnail = false;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                this.errors.add(new Error("SellItemImagesController (saveImages): Could not save image", e));
                e.printStackTrace();
            }
        }
    }

    if (this.errors.size() == 0 && !this.useHTML5()) {
        createRedirectURL();
    }

    // Try to save the uploaded files
    /*try {
               
       while(images.hasNext()) {
    FileItem item = (FileItem) images.next();
    System.out.println("doing item 1");
    /*
     * Handle Form Fields.
     *
    if(item.isFormField()) {
       System.out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
    } else {
       //Handle Uploaded files.
       System.out.println("Field Name = "+item.getFieldName()+
          ", File Name = "+item.getName()+
          ", Content type = "+item.getContentType()+
          ", File Size = "+item.getSize());
       /*
        * Write file to the ultimate location.
        *
       File file = new File(GlobalVars.imageDir,item.getName());
       item.write(file);
    }
    //System.out.close();
       }
    }catch(Exception ex) {
       System.out.println("Error encountered while uploading file");
    }*/
}

From source file:brooklyn.util.ResourceUtils.java

private InputStream getResourceViaSftp(String url) throws IOException {
    assert url.startsWith("sftp://");
    String subUrl = url.substring("sftp://".length());
    String user;//from w w w .  java  2  s .  c  om
    String address;
    String path;
    int atIndex = subUrl.indexOf("@");
    int colonIndex = subUrl.indexOf(":", (atIndex > 0 ? atIndex : 0));
    if (colonIndex <= 0 || colonIndex <= atIndex) {
        throw new IllegalArgumentException("Invalid sftp url (" + url
                + "); IP or hostname must be specified, such as sftp://localhost:/path/to/file");
    }
    if (subUrl.length() <= (colonIndex + 1)) {
        throw new IllegalArgumentException("Invalid sftp url (" + url
                + "); must specify path of remote file, such as sftp://localhost:/path/to/file");
    }
    if (atIndex >= 0) {
        user = subUrl.substring(0, atIndex);
    } else {
        user = null;
    }
    address = subUrl.substring(atIndex + 1, colonIndex);
    path = subUrl.substring(colonIndex + 1);

    // TODO messy way to get an SCP session 
    SshMachineLocation machine = new SshMachineLocation(MutableMap.builder().putIfNotNull("user", user)
            .put("address", InetAddress.getByName(address)).build());
    try {
        final File tempFile = Os.newTempFile("brooklyn-sftp", "tmp");
        tempFile.setReadable(true, true);
        machine.copyFrom(path, tempFile.getAbsolutePath());
        return new FileInputStream(tempFile) {
            @Override
            public void close() throws IOException {
                super.close();
                tempFile.delete();
            }
        };
    } finally {
        Streams.closeQuietly(machine);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.PeriodicResourceUpdater.java

protected synchronized void copyDatabase(final File existingDB, final String newDB) throws IOException {
    try (final StringReader in = new StringReader(newDB);
            final FileOutputStream out = new FileOutputStream(existingDB);
            final FileLock lock = out.getChannel().tryLock()) {

        if (lock == null) {
            LOGGER.error("Database " + existingDB.getAbsolutePath() + " locked by another process.");
            return;
        }/*from  ww w  .  j  a va 2 s .  c om*/

        IOUtils.copy(in, out);
        existingDB.setReadable(true, false);
        existingDB.setWritable(true, true);
        lock.release();
    }
}