Example usage for java.io File canRead

List of usage examples for java.io File canRead

Introduction

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

Prototype

public boolean canRead() 

Source Link

Document

Tests whether the application can read the file denoted by this abstract pathname.

Usage

From source file:io.github.mzmine.modules.featuretableimport.FeatureTableImportModule.java

@Override
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
        @Nonnull Collection<Task<?>> tasks) {

    final List<File> fileNames = parameters.getParameter(FeatureTableImportParameters.fileNames).getValue();
    final String removePrefix = parameters.getParameter(RawDataImportParameters.removePrefix).getValue();
    final String removeSuffix = parameters.getParameter(RawDataImportParameters.removeSuffix).getValue();

    if (fileNames == null) {
        logger.warn("Feature table import module started with no filenames");
        return;/*  ww w .java  2s . c  om*/
    }

    for (File fileName : fileNames) {

        if ((!fileName.exists()) || (!fileName.canRead())) {
            MZmineGUI.displayMessage("Cannot read file " + fileName);
            logger.warn("Cannot read file " + fileName);
            continue;
        }

        DataPointStore dataStore = DataPointStoreFactory.getTmpFileDataStore();

        // Find file extension and initiate corresponding import method
        String fileExtension = FilenameUtils.getExtension(fileName.getAbsolutePath());
        MSDKMethod<?> method = null;
        switch (fileExtension.toUpperCase()) {
        default:
        case "CSV":
            method = new CsvFileImportMethod(fileName, dataStore);
            break;
        case "MZTAB":
            method = new MzTabFileImportMethod(fileName, dataStore);
            break;
        }
        final MSDKMethod<?> finalMethod = method;

        MSDKTask newTask = new MSDKTask("Importing feature table file", fileName.getName(), finalMethod);
        newTask.setOnSucceeded(e -> {
            FeatureTable featureTable = (FeatureTable) finalMethod.getResult();
            if (featureTable == null)
                return;

            // Remove common prefix
            if (!Strings.isNullOrEmpty(removePrefix)) {
                String name = featureTable.getName();
                if (removePrefix != null && name.startsWith(removePrefix))
                    name = name.substring(removePrefix.length());
                featureTable.setName(name);
            }

            // Remove common suffix
            if (!Strings.isNullOrEmpty(removeSuffix)) {
                String suffix = removeSuffix;
                if (suffix.equals(".*"))
                    suffix = "." + fileExtension;
                String name = featureTable.getName();
                if (name.endsWith(suffix))
                    name = name.substring(0, name.length() - suffix.length());
                featureTable.setName(name);
            }

            project.addFeatureTable(featureTable);
        });

        tasks.add(newTask);

    }

}

From source file:io.kodokojo.config.module.SecurityModule.java

@Provides
@Singleton//from   w w w.  j a  v  a 2s  . c om
@Named("securityKey")
SecretKey provideSecretKey(SecurityConfig securityConfig) {
    if (securityConfig == null) {
        throw new IllegalArgumentException("securityConfig must be defined.");
    }
    File keyFile = createPrivateKeyFile(securityConfig);
    if (keyFile.exists() && keyFile.canRead()) {
        return provideAesKey(keyFile);
    } else {
        SecretKey res = generateAesKey();
        try {
            keyFile.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException("Unable to create " + keyFile.getAbsolutePath() + " file.", e);
        }
        try (FileOutputStream out = new FileOutputStream(securityConfig.privateKeyPath())) {
            out.write(res.getEncoded());
            out.flush();
            return res;
        } catch (IOException e) {
            throw new RuntimeException(
                    "unable to read and/or create key file at path " + keyFile.getAbsolutePath(), e);
        }
    }
}

From source file:au.org.ala.layers.intersect.IntersectConfig.java

private static void isValidPathGDAL(String path, String desc) {
    File f = new File(path);

    if (!f.exists()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\" is not a valid local file path.  It does not exist.");
    } else if (!f.isDirectory()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  It is not a directory.");
    } else if (!f.canRead()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  Not permitted to READ.");
    }/* w w  w. j  a va  2s  .  c  om*/

    //look for GDAL file "gdalwarp"
    File g = new File(path + File.separator + "gdalwarp");
    if (!f.exists()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  gdalwarp does not exist.");
    } else if (!g.canExecute()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  gdalwarp not permitted to EXECUTE.");
    }
}

From source file:net.solarnetwork.node.backup.test.DefaultBackupManagerTest.java

@Test
public void restoreBackup() throws IOException {
    createBackup();/*from   w  w w  .j  a  v a2s. co m*/
    manager.restoreBackup(this.backup);
    final File restoredFile = new File(RESTORE_DIR, TEST_FILE_TXT);
    assertTrue("Restored file should exist", restoredFile.canRead());
    final byte[] restoredData = FileCopyUtils.copyToByteArray(restoredFile);
    assertArrayEquals(
            FileCopyUtils.copyToByteArray(
                    new ClassPathResource(TEST_FILE_TXT, DefaultBackupManagerTest.class).getInputStream()),
            restoredData);
}

From source file:ninja.eivind.hotsreplayuploader.providers.hotslogs.HotsLogsProvider.java

@Override
public Status upload(final ReplayFile replayFile) {
    if (isMaintenance()) {
        return null;
    }/*from   www.  ja  va2 s .com*/

    final File file = replayFile.getFile();
    if (!(file.exists() && file.canRead())) {
        return Status.EXCEPTION;
    }

    final String fileName = UUID.randomUUID() + ".StormReplay";
    LOG.info("Assigning remote file name " + fileName + " to " + replayFile);
    final String uri = BASE_URL + "&FileName=" + fileName;

    return uploadFileToHotSLogs(file, fileName, uri);

}

From source file:com.ontotext.s4.TwitterVisualization.processingTweets.ProcessingTweets.java

/**
 * Process all documents into the raw tweets folder. Save processed tweets
 * into the processed tweets Folder.// ww  w  .  j ava2s  . co m
 */
public void ProcessTweets() {

    // get all documents in a folder
    File f = new File(rawTweetsFolder);
    File[] documents = f.listFiles();

    //
    if (documents == null) {
        logger.info("There are no files to process");
        return;
    }

    // the output
    File results = new File(processedTweetsFolder);
    if (!results.exists()) {
        results.mkdirs();
    }

    Writer w = null;
    for (File document : documents) {
        try {

            if (document.isDirectory() || !document.canRead()) {
                continue;
            }

            logger.info("Just send " + document.getName() + " for processing.");
            // annotate each file
            String result = ProcessThisTweet(new String(Files.readAllBytes(document.toPath())));

            logger.info("Received " + document.getName());
            w = new OutputStreamWriter(new FileOutputStream(processedTweetsFolder + "/" + document.getName()));
            w.append(result);

        } catch (FileNotFoundException e) {
            logger.debug(e);
        } catch (IOException e) {
            logger.debug(e);
        } finally {
            try {
                w.close();
            } catch (IOException e) {
                logger.debug(e);
            } catch (Exception e2) {
                logger.debug(e2);
            }
        }
    }
}

From source file:io.neba.core.logviewer.LogFiles.java

private Collection<File> resolveFactoryConfiguredLogFiles() throws IOException {
    Collection<File> logFiles = new ArrayList<>();
    Configuration[] configurations;
    try {//from   w w  w  .  j av  a 2s  .c o m
        configurations = this.configurationAdmin
                .listConfigurations("(service.factoryPid=" + LOG_FACTORY_PID + ")");
    } catch (InvalidSyntaxException e) {
        throw new IllegalStateException(
                "Unable to obtain the log files with factory pid " + LOG_FACTORY_PID + ".", e);
    }
    if (configurations != null) {
        for (Configuration logConfiguration : configurations) {
            File logFile = getConfiguredLogfile(logConfiguration);
            if (logFile != null && logFile.exists() && logFile.canRead()) {
                logFiles.add(logFile);
            }
        }
    }
    return logFiles;
}

From source file:com.amazonaws.devicefarm.DeviceFarmUploader.java

/**
 * Upload a single file, waits for upload to complete.
 * @param file the file//from  www  .j  a v a2  s .c  om
 * @param project the project
 * @param uploadType the upload type
 * @return upload object
 */
public Upload upload(final File file, final Project project, final UploadType uploadType) {

    if (!(file.exists() && file.canRead())) {
        throw new DeviceFarmException(String.format("File %s does not exist or is not readable", file));
    }

    final CreateUploadRequest appUploadRequest = new CreateUploadRequest().withName(file.getName())
            .withProjectArn(project.getArn()).withContentType("application/octet-stream")
            .withType(uploadType.toString());
    final Upload upload = api.createUpload(appUploadRequest).getUpload();

    final CloseableHttpClient httpClient = HttpClients.createDefault();
    final HttpPut httpPut = new HttpPut(upload.getUrl());
    httpPut.setHeader("Content-Type", upload.getContentType());

    final FileEntity entity = new FileEntity(file);
    httpPut.setEntity(entity);

    writeToLog(String.format("Uploading %s to S3", file.getName()));

    final HttpResponse response;
    try {
        response = httpClient.execute(httpPut);
    } catch (IOException e) {
        throw new DeviceFarmException(String.format("Error uploading artifact %s", file), e);
    }

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new DeviceFarmException(String.format("Upload returned non-200 responses: %s",
                response.getStatusLine().getStatusCode()));
    }

    waitForUpload(file, upload);

    return upload;
}

From source file:com.thinkbiganalytics.nifi.v2.spark.ExecuteSparkJob.java

public static final Validator createMultipleFilesExistValidator() {
    return new Validator() {
        @Override/*from  w  ww  . ja v a  2  s  . c o  m*/
        public ValidationResult validate(String subject, String input, ValidationContext context) {
            final String[] files = input.split(",");
            for (String filename : files) {
                try {
                    final File file = new File(filename.trim());
                    if (!file.exists()) {
                        final String message = "file " + filename + " does not exist";
                        return new ValidationResult.Builder().subject(subject).input(input).valid(false)
                                .explanation(message).build();
                    } else if (!file.isFile()) {
                        final String message = filename + " is not a file";
                        return new ValidationResult.Builder().subject(subject).input(input).valid(false)
                                .explanation(message).build();
                    } else if (!file.canRead()) {
                        final String message = "could not read " + filename;
                        return new ValidationResult.Builder().subject(subject).input(input).valid(false)
                                .explanation(message).build();
                    }
                } catch (SecurityException e) {
                    final String message = "Unable to access " + filename + " due to " + e.getMessage();
                    return new ValidationResult.Builder().subject(subject).input(input).valid(false)
                            .explanation(message).build();
                }
            }
            return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
        }

    };
}