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) 

Source Link

Document

A convenience method to set the owner's read permission for this abstract pathname.

Usage

From source file:io.covert.binary.analysis.BinaryAnalysisMapper.java

protected void setup(Context context) throws java.io.IOException, InterruptedException {
    Configuration conf = context.getConfiguration();
    try {//from w w w.  j  a  v  a 2s  . c  o  m
        parser = (OutputParser<K, V>) Class.forName(conf.get("binary.analysis.output.parser")).newInstance();
    } catch (Exception e) {
        throw new IOException("Could create parser", e);
    }

    fileExtention = conf.get("binary.analysis.file.extention", ".dat");
    timeoutMS = conf.getLong("binary.analysis.execution.timeoutMS", Long.MAX_VALUE);
    program = conf.get("binary.analysis.program");
    args = conf.get("binary.analysis.program.args").split(conf.get("binary.analysis.program.args.delim", ","));
    String[] codes = conf.get("binary.analysis.program.exit.codes").split(",");
    exitCodes = new int[codes.length];
    for (int i = 0; i < codes.length; ++i) {
        exitCodes[i] = Integer.parseInt(codes[i]);
    }

    workingDir = new File(".").getAbsoluteFile();
    dataDir = new File(workingDir, "_data");
    dataDir.mkdir();
    logDirContents(workingDir);

    File programFile = new File(workingDir, program);
    if (programFile.exists()) {
        LOG.info("Program file exists in working directory, ensuring executable and readable");
        programFile.setExecutable(true);
        programFile.setReadable(true);
    }
}

From source file:org.dataone.proto.trove.mn.service.v1.impl.MNStorageImpl.java

@Override
public Identifier create(Identifier pid, InputStream object, SystemMetadata sysmeta)
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType,
        InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
    try {/*from w w w  . j a  v  a  2  s. c o  m*/
        File systemMetadata = new File(dataoneCacheDirectory + File.separator + "meta" + File.separator
                + EncodingUtilities.encodeUrlPathSegment(pid.getValue()));
        TypeMarshaller.marshalTypeToFile(sysmeta, systemMetadata.getAbsolutePath());

        if (systemMetadata.exists()) {
            systemMetadata.setLastModified(sysmeta.getDateSysMetadataModified().getTime());
        } else {
            throw new ServiceFailure("1190", "SystemMetadata not found on FileSystem after create");
        }
        File objectFile = new File(dataoneCacheDirectory + File.separator + "object" + File.separator
                + EncodingUtilities.encodeUrlPathSegment(pid.getValue()));
        if (!objectFile.exists() && objectFile.createNewFile()) {
            objectFile.setReadable(true);
            objectFile.setWritable(true);
            objectFile.setExecutable(false);
        }

        if (object != null) {
            FileOutputStream objectFileOutputStream = new FileOutputStream(objectFile);
            BufferedInputStream inputStream = new BufferedInputStream(object);
            byte[] barray = new byte[SIZE];
            int nRead = 0;

            while ((nRead = inputStream.read(barray, 0, SIZE)) != -1) {
                objectFileOutputStream.write(barray, 0, nRead);
            }
            objectFileOutputStream.flush();
            objectFileOutputStream.close();
            inputStream.close();
        }
    } catch (FileNotFoundException ex) {
        throw new ServiceFailure("1190", ex.getCause().toString() + ":" + ex.getMessage());
    } catch (IOException ex) {
        throw new ServiceFailure("1190", ex.getMessage());
    } catch (JiBXException ex) {
        throw new InvalidSystemMetadata("1180", ex.getMessage());
    }
    return pid;
}

From source file:org.silverpeas.core.security.encryption.ContentEncryptionServiceTest.java

private void createSecurityDirectoryAndSetupJCEProviders() throws IOException {
    ACTUAL_KEY_FILE_PATH = FileRepositoryManager.getSecurityDirPath() + ".aid_key";
    DEPRECATED_KEY_FILE_PATH = FileRepositoryManager.getSecurityDirPath() + ".did_key";
    try {//from w  w w.ja  v a 2s . co  m
        CIPHER_KEY = CipherKey.aKeyFromHexText("06277d1ce530c94bd9a13a72a58342be");
    } catch (ParseException e) {
        throw new RuntimeException("Cannot create the cryptographic key!", e);
    }

    String securityPath = FileRepositoryManager.getSecurityDirPath();
    File securityDir = new File(securityPath);
    if (!securityDir.exists()) {
        FileUtils.forceMkdir(securityDir);
    }
    securityDir.setWritable(true);
    securityDir.setExecutable(true);
    securityDir.setReadable(true);
    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        Runtime.getRuntime().exec("attrib +H " + securityPath);
    }

    Security.addProvider(new BouncyCastleProvider());
}

From source file:org.docx4j.template.io.WordprocessingMLPackageWriter.java

/**
 *  {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage}  html
 * @param wmlPackage {@link WordprocessingMLPackage} 
 * @param outFile /* w  w w.j  a  v  a 2s  .  c o m*/
 * @return {@link File} docx 
 * @throws IOException IO
 * @throws Docx4JException  Docx4j
 */
public File writeToHtml(WordprocessingMLPackage wmlPackage, File outFile) throws IOException, Docx4JException {
    Assert.notNull(wmlPackage, " wmlPackage is not specified!");
    Assert.isTrue(outFile.exists(), " outFile is not founded !");
    OutputStream output = null;
    try {
        String imageTargetUri = Docx4jProperties
                .getProperty(Docx4jConstants.DOCX4J_CONVERT_OUT_HTML_IMAGETARGETURI, "images");
        File[] files = outFile.listFiles(new OutputDirFilterHandler(imageTargetUri));
        if (files.length != 1) {
            File imageDir = new File(outFile, imageTargetUri);
            imageDir.setWritable(true);
            imageDir.setReadable(true);
            imageDir.mkdir();
        }
        //?
        output = new FileOutputStream(outFile);
        //Html
        HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
        htmlSettings.setImageDirPath(outFile.getParent());
        htmlSettings.setImageTargetUri(imageTargetUri);
        htmlSettings.setWmlPackage(wmlPackage);

        //d
        htmlSettings.setHyperlinkHandler(getHyperlinkHandler());
        htmlSettings.setScriptElementHandler(getScriptElementHandler());
        htmlSettings.setStyleElementHandler(getStyleElementHandler());

        Docx4jProperties.setProperty(Docx4jConstants.DOCX4J_PARAM_04, true);

        //Docx4J.toHTML(settings, outputStream, flags);
        //Docx4J.toHTML(wmlPackage, imageDirPath, imageTargetUri, outputStream);
        Docx4J.toHTML(htmlSettings, output, Docx4J.FLAG_EXPORT_PREFER_XSL);

    } finally {
        IOUtils.closeQuietly(output);
    }

    return outFile;
}

From source file:org.dataconservancy.packaging.tool.impl.GeneralPackageDescriptionCreatorTest.java

@Test
public void nonreadableFileTest() throws Exception {
    File tempDir = tmpfolder.newFolder("moo");

    File subdir = new File(tempDir, "cow");
    subdir.mkdir();//from   w ww .  j a v  a2  s.  c  om

    if (subdir.setReadable(false)) {

        try {
            creator.createPackageDescription(packageOntologyIdentifier, tempDir);
            Assert.fail("Expected a non-readable directory to cause an exception");
        } catch (PackageDescriptionCreatorException e) {
            /* Expected */
        }
    }
}

From source file:com.streamsets.datacollector.cluster.TestClusterProviderImpl.java

@Test
public void testCopyDirectory() throws Exception {
    File copyTempDir = new File(tempDir, "copy");
    File srcDir = new File(copyTempDir, "somedir");
    File dstDir = new File(copyTempDir, "dst");
    Assert.assertTrue(srcDir.mkdirs());/*from www  .ja va 2s  .c o  m*/
    Assert.assertTrue(dstDir.mkdirs());
    File link1 = new File(copyTempDir, "link1");
    File link2 = new File(copyTempDir, "link2");
    File dir1 = new File(copyTempDir, "dir1");
    File file1 = new File(dir1, "f1");
    File file2 = new File(dir1, "f2");
    Assert.assertTrue(dir1.mkdirs());
    Assert.assertTrue(file1.createNewFile());
    Assert.assertTrue(file2.createNewFile());
    file2.setReadable(false);
    file2.setWritable(false);
    file2.setExecutable(false);
    Files.createSymbolicLink(link1.toPath(), dir1.toPath());
    Files.createSymbolicLink(link2.toPath(), link1.toPath());
    Files.createSymbolicLink(new File(srcDir, "dir1").toPath(), link2.toPath());
    File clone = ClusterProviderImpl.createDirectoryClone(srcDir, srcDir.getName(), dstDir);
    File cloneF1 = new File(new File(clone, "dir1"), "f1");
    Assert.assertTrue(cloneF1.isFile());
}

From source file:io.specto.hoverfly.junit.HoverflyRule.java

private Path extractBinary(final String binaryName) throws IOException, URISyntaxException {
    final URI sourceHoverflyUrl = findResourceOnClasspath(binaryName);
    final Path temporaryHoverflyPath = Files.createTempFile(binaryName, "");
    LOGGER.info("Storing binary in temporary directory " + temporaryHoverflyPath);
    final File temporaryHoverflyFile = temporaryHoverflyPath.toFile();
    FileUtils.copyURLToFile(sourceHoverflyUrl.toURL(), temporaryHoverflyFile);
    if (SystemUtils.IS_OS_WINDOWS) {
        temporaryHoverflyFile.setExecutable(true);
        temporaryHoverflyFile.setReadable(true);
        temporaryHoverflyFile.setWritable(true);
    } else {/*w ww .ja  v a  2s.com*/
        Files.setPosixFilePermissions(temporaryHoverflyPath, new HashSet<>(asList(OWNER_EXECUTE, OWNER_READ)));
    }

    return temporaryHoverflyPath;
}

From source file:at.jku.ce.adaptivetesting.vaadin.ui.topic.accounting.AccountingQuestionManager.java

public int loadQuestions(File containingFolder) throws JAXBException, IOException {
    assert containingFolder.exists() && containingFolder.isDirectory();
    JAXBContext accountingJAXB = JAXBContext.newInstance(XmlAccountingQuestion.class,
            AccountingDataStorage.class);
    JAXBContext profitJAXB = JAXBContext.newInstance(XmlProfitQuestion.class, ProfitDataStorage.class);

    Unmarshaller accountingUnmarshaller = accountingJAXB.createUnmarshaller();
    Unmarshaller profitUnmarshaller = profitJAXB.createUnmarshaller();

    final List<AccountingQuestion> accountingList = new ArrayList<>();
    final List<ProfitQuestion> profitList = new ArrayList<>();

    String accountingRootElement = XmlAccountingQuestion.class.getAnnotation(XmlRootElement.class).name();
    String profitRootElement = XmlProfitQuestion.class.getAnnotation(XmlRootElement.class).name();

    File[] questions = containingFolder
            .listFiles(f -> f.isFile() && (f.canRead() || f.setReadable(true)) && f.getName().endsWith(".xml"));

    // read all questions
    LogHelper.logInfo("Found " + questions.length + " potential questions");
    int successfullyLoaded = 0;
    for (File f : questions) {
        LogHelper.logInfo("Loading question with filename: " + f.getName());
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {// ww  w  . ja  v a2s  .c  o  m
            reader = new BufferedReader(new InputStreamReader(
                    new BOMInputStream(new FileInputStream(f), ByteOrderMark.UTF_8), "UTF8"));

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        String fileAsString = sb.toString().replaceAll("& ", "&amp; ");
        if (fileAsString.contains(profitRootElement)) {
            LogHelper.logInfo("Question detected as " + ProfitQuestion.class.getName());
            // Profit Question
            XmlProfitQuestion question = (XmlProfitQuestion) profitUnmarshaller
                    .unmarshal(new StringReader(fileAsString));
            profitList.add(AccountingXmlHelper.fromXml(question, f.getName()));
            successfullyLoaded++;
        } else if (fileAsString.contains(accountingRootElement)) {
            LogHelper.logInfo("Question detected as " + AccountingQuestion.class.getName());
            // Accounting Question
            XmlAccountingQuestion question = (XmlAccountingQuestion) accountingUnmarshaller
                    .unmarshal(new StringReader(fileAsString));
            accountingList.add(AccountingXmlHelper.fromXml(question, f.getName()));
            successfullyLoaded++;
        } else {
            LogHelper.logInfo(
                    "QuestionManager: item type not supported for " + f.getName() + ", ignoring file.");
            //            throw new IllegalArgumentException(
            //                  "Question type not supported. File: " + f);
            continue;
        }
        LogHelper.logInfo("Loaded question with filename:" + f.getName());
    }
    // Add question to the question manager
    accountingList.forEach(q -> addQuestion(q));
    profitList.forEach(q -> addQuestion(q));
    LogHelper.logInfo("Successfully loaded " + successfullyLoaded + " questions.");
    return questions.length;
}

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

/**
 * Platform independent implementation for {@link File#setReadable(boolean)} File#setReadable does not work as
 * expected on Windows.//from w w w .  j  a  va 2s  .  co m
 *
 * @param f        input file
 * @param readable
 *
 * @return true on success, false otherwise
 */
public static boolean setReadable(File f, boolean readable) {
    if (Shell.WINDOWS) {
        try {
            String permission = readable ? "u+r" : "u-r";
            FileUtil.chmod(f.getCanonicalPath(), permission, false);
            return true;
        } catch (IOException ex) {
            return false;
        }
    } else {
        return f.setReadable(readable);
    }
}

From source file:org.ngrinder.common.util.CompressionUtil.java

/**
 * Untar an input file into an output file.
 * /* w w  w  . ja va  2s .  co m*/
 * The output file is created in the output folder, having the same name as the input file,
 * minus the '.tar' extension.
 * 
 * @param inFile
 *            the input .tar file
 * @param outputDir
 *            the output directory file.
 * @throws IOException
 * @throws FileNotFoundException
 * 
 * @return The {@link List} of {@link File}s with the untared content.
 * @throws ArchiveException
 */
public static List<File> untar(final File inFile, final File outputDir) {
    final List<File> untaredFiles = new LinkedList<File>();
    try {
        final InputStream is = new FileInputStream(inFile);
        final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
                .createArchiveInputStream("tar", is);
        TarArchiveEntry entry = null;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
            final File outputFile = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                if (!outputFile.exists()) {
                    if (!outputFile.mkdirs()) {
                        throw new IllegalStateException(
                                String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                    }
                }
            } else {
                File parentFile = outputFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                final OutputStream outputFileStream = new FileOutputStream(outputFile);

                IOUtils.copy(debInputStream, outputFileStream);
                outputFileStream.close();
                if (FilenameUtils.isExtension(outputFile.getName(), EXECUTABLE_EXTENSION)) {
                    outputFile.setExecutable(true, true);
                }
                outputFile.setReadable(true);
                outputFile.setWritable(true, true);
            }
            untaredFiles.add(outputFile);
        }
        debInputStream.close();
    } catch (Exception e) {
        LOGGER.error("Error while untar {} file by {}", inFile, e.getMessage());
        LOGGER.debug("Trace is : ", e);
        throw new NGrinderRuntimeException("Error while untar file", e);
    }
    return untaredFiles;
}