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:com.pieframework.model.repository.ModelStore.java

/**
 * @param file// w  w w .j a  va 2s  .  c  o m
 * @return
 * @throws SimpleSerializerException
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
public static System getSystem(File file) throws SimpleSerializerException, IOException,
        ParserConfigurationException, SAXException, TransformerException {

    if (file == null || !file.canRead()) {
        throw new IllegalArgumentException("Cannot build Model from given file.");
    }

    StringWriter writer = new StringWriter();
    processXIncludes(file, writer);

    // Deserialize a System File
    System system;
    system = DefaultSerializer.read(System.class, IOUtils.toInputStream(writer.toString()));

    linkComponents(system);

    return system;
}

From source file:exm.stc.ui.Main.java

/**
 * Setup input file.  If necessary, run through CPP
 * @param logger//from w  w w. ja  v  a  2  s .c o  m
 * @param preprocess
 * @param args
 * @return
 */
private static File setupInputFile(Logger logger, boolean preprocess, Args args) {
    File result;
    try {
        if (preprocess) {
            File input = new File(args.inputFilename);
            if (!input.isFile() || !input.canRead()) {
                System.out.println("Input file \"" + input + "\" is not readable");
                System.exit(1);
            }

            result = File.createTempFile("stc-preproc", ".swift");
            temporaries.add(result);
            runPreprocessor(logger, args.inputFilename, result.getPath(), args.preprocessorMacros);
        } else {
            result = new File(args.inputFilename);
        }
        if (!result.isFile() || !result.canRead()) {
            System.out.println("Input file \"" + result + "\" is not readable");
            System.exit(1);
        }
        return result;
    } catch (IOException ex) {
        System.out.println("Error while setting up input file: " + ex.toString());
        System.exit(1);
    } catch (Throwable t) {
        STCompiler.reportInternalError(logger, t);
        System.exit(1);
    }
    return null;
}

From source file:com.heliosapm.streams.collector.ds.pool.PoolConfig.java

/**
 * Undeploys the pool defined in the passed file
 * @param file The pool configuration file
 *///  w  w  w. java2s.co  m
public static void undeployPool(final File file) {
    if (file == null)
        throw new IllegalArgumentException("The passed file was null");
    if (!file.canRead())
        throw new IllegalArgumentException("Cannot read file [" + file + "]");
    if (pools.remove(file) != null) {
        final Properties p = URLHelper.readProperties(URLHelper.toURL(file));
        final String poolName = p.getProperty(NAME.name().toLowerCase());
        if (poolName == null) {
            p.setProperty("name", StringHelper.splitString(file.getName(), '.', true)[0]);
        }
        undeployPool(p);
    }
}

From source file:com.grillecube.engine.renderer.model.json.JSONHelper.java

/**
 * return a String which contains the full file bytes
 * // w  w  w. j  a v a 2s . c  o m
 * @throws IOException
 */
public static String readFile(File file) throws IOException {
    if (!file.exists()) {
        throw new IOException("Couldnt read model file. (It doesnt exists: " + file.getPath() + ")");
    }
    if (file.isDirectory()) {
        throw new IOException("Couldnt read model file. (It is a directory!!! " + file.getPath() + ")");
    }
    if (!file.canRead() && !file.setReadable(true)) {
        throw new IOException("Couldnt read model file. (Missing read permissions: " + file.getPath() + ")");
    }

    byte[] encoded = Files.readAllBytes(Paths.get(file.getPath()));
    return (new String(encoded, StandardCharsets.UTF_8));
}

From source file:org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil.java

public static String getUserData(String payloadFileName) {
    String userData = null;/*  www.j a  v a  2  s.co m*/
    try {
        File file = new File(payloadFileName);
        if (!file.exists()) {
            handleException("Payload file " + payloadFileName + " does not exist");
        }
        if (!file.canRead()) {
            handleException("Payload file " + payloadFileName + " does cannot be read");
        }
        byte[] bytes = AutoscaleUtil.getBytesFromFile(file);
        if (bytes != null) {
            //                /BASE64.e encoder = new BASE64Encoder();
            userData = Base64.encode(bytes);
        }
    } catch (IOException e) {
        AutoscaleUtil.handleException("Cannot read data from payload file " + payloadFileName, e);
    }
    return userData;
}

From source file:com.aurel.track.util.PropertiesConfigurationHelper.java

/**
 * Obtain the Torque.properties from TRACKPLUS_HOME or if not available from the WAR.
 * @return//www. jav a 2s.c  o m
 */
public static PropertiesConfiguration getPathnamePropFile(String absolutePath, String propFile) {
    PropertiesConfiguration propertiesConfiguration = null;
    File props = null;
    InputStream in = null;
    try {
        // First check if we have a configuration file pointed to by the environment
        if (absolutePath != null && !"".equals(absolutePath)) {
            props = new File(absolutePath + File.separator + propFile);
            LOGGER.debug("Trying file " + absolutePath + File.separator + propFile);
            if (props.exists() && props.canRead()) {
                LOGGER.info("Retrieving configuration from " + absolutePath + File.separator + propFile);
                in = new FileInputStream(props);
                propertiesConfiguration = new PropertiesConfiguration();
                propertiesConfiguration.load(in);
                in.close();
            }
        }

    } catch (Exception e) {
        LOGGER.warn("Could not read " + propFile + " from " + absolutePath + ". Exiting. " + e.getMessage());
    }
    return propertiesConfiguration;
}

From source file:it.geosolutions.mariss.wps.gs.DownloadProcess.java

private static Pattern loadTimeRegex(File mosaicDir) throws ProcessException {

    FileInputStream in = null;// w ww .  j  av a  2 s.c o m
    try {
        File f = new File(mosaicDir, "timeregex.properties");
        if (!f.exists() || !f.isFile() || !f.canRead()) {
            throw new ProcessException("The timeregex.properties file don't exist or is not accessible...");
        }
        in = new FileInputStream(f);
        Properties prop = new Properties();
        prop.load(in);
        String regex = prop.getProperty("regex");
        if (StringUtils.isBlank(regex)) {
            throw new ProcessException("The timeregex.properties not contains a valid regex...");
        }
        Pattern p = Pattern.compile(regex);
        LOGGER.info("Timeregex '" + regex + "' loaded");
        return p;
    } catch (IOException e) {
        LOGGER.severe(e.getMessage());
        throw new ProcessException("Error while trying to access to timeregex.properties file");
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOGGER.severe(e.getMessage());
            }
        }
    }
}

From source file:com.xse.optstack.persconftool.base.persistence.PersConfExport.java

private static void copyDefaultDataFiles(final File targetBaseFolder, final EApplication application,
        final Function<EConfiguration, EDefaultData> defaultDataProvider) {
    for (final EResource eResource : application.getResources()) {
        // copy default data files in case we have a file-based default data configuration with new file refs
        if (eResource.getConfiguration().getType() == EDefaultDataType.FILE) {
            final EDefaultData factoryDefaultData = defaultDataProvider.apply(eResource.getConfiguration());
            if (!StringUtils.isEmpty(factoryDefaultData.getLocalResourcePath())) {
                final File dataFile = new File(factoryDefaultData.getLocalResourcePath());
                if (dataFile.exists() && dataFile.canRead()) {
                    try {
                        final Path source = Paths.get(dataFile.toURI());
                        final Path target = Paths.get(new File(
                                targetBaseFolder.getAbsolutePath() + File.separator + eResource.getName())
                                        .toURI());
                        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
                    } catch (final IOException | IllegalArgumentException | SecurityException e) {
                        Logger.error(Activator.PLUGIN_ID,
                                "Error copying factory default file to target location: " + eResource.getName(),
                                e);/*from w w w .  ja v a 2s  .  co  m*/
                    }
                } else {
                    Logger.warn(Activator.PLUGIN_ID, "Invalid factory default data path!");
                }
            }
        }
    }
}

From source file:aiai.apps.commons.utils.ZipUtils.java

/**
 * Unzips a zip file into the given destination directory.
 *
 * The archive file MUST have a unique "root" folder. This root folder is
 * skipped when unarchiving./* ww w. jav  a 2 s. co  m*/
 *
 */
public static void unzipFolder(File archiveFile, File zipDestinationFolder) {

    log.debug("Start unzipping archive file");
    log.debug("'\tzip archive file: {}", archiveFile.getAbsolutePath());
    log.debug("'\t\tis exist: {}", archiveFile.exists());
    log.debug("'\t\tis writable: {}", archiveFile.canWrite());
    log.debug("'\t\tis readable: {}", archiveFile.canRead());
    log.debug("'\ttarget dir: {}", zipDestinationFolder.getAbsolutePath());
    log.debug("'\t\tis exist: {}", zipDestinationFolder.exists());
    log.debug("'\t\tis writable: {}", zipDestinationFolder.canWrite());
    try (MyZipFile zipFile = new MyZipFile(archiveFile)) {

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zipEntry = entries.nextElement();
            log.debug("'\t\tzip entry: {}, is directory: {}", zipEntry.getName(), zipEntry.isDirectory());

            String name = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                if (name.endsWith("/") || name.endsWith("\\")) {
                    name = name.substring(0, name.length() - 1);
                }

                File newDir = new File(zipDestinationFolder, name);
                log.debug("'\t\t\tcreate dirs in {}", newDir.getAbsolutePath());
                if (!newDir.mkdirs()) {
                    throw new RuntimeException("Creation of target dir was failed, target dir: "
                            + zipDestinationFolder + ", entity: " + name);
                }
            } else {
                File destinationFile = DirUtils.createTargetFile(zipDestinationFolder, name);
                if (destinationFile == null) {
                    throw new RuntimeException("Creation of target file was failed, target dir: "
                            + zipDestinationFolder + ", entity: " + name);
                }
                if (!destinationFile.getParentFile().exists()) {
                    destinationFile.getParentFile().mkdirs();
                }
                log.debug("'\t\t\tcopy content of zip entry to file {}", destinationFile.getAbsolutePath());
                FileUtils.copyInputStreamToFile(zipFile.getInputStream(zipEntry), destinationFile);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Unzip failed:", e);
    }
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java

private static void loadApplicationPropertiesFile() {
    // Set the projects properties.
    // First look for a system property pointing to a project properties file.
    // This value can be either a file path, file protocol (e.g. - file:/path/to/file),
    // or a URL (http://some/server/file).
    // If this value either does not exist or is not valid, the default
    // file that comes with this application will be used for initialization.
    String environmentProjectPropsFile = System.getProperty(ApplicationConstants.ENV_PROJECT_PROPS);
    logger.info("Have {} from environment: {}", ApplicationConstants.PROJECT_PROPS,
            environmentProjectPropsFile);
    URI projectPropsUri = null;/*ww w  .j  av  a 2 s . c o  m*/
    if (environmentProjectPropsFile != null) {
        try {
            projectPropsUri = new URI(environmentProjectPropsFile);
            // properties file needs a scheme in the URI so convert to file if necessary.
            if (null == projectPropsUri.getScheme()) {
                File projectProperties = new File(environmentProjectPropsFile);
                if (projectProperties.exists() && projectProperties.isFile()) {
                    projectPropsUri = projectProperties.toURI();
                } else {
                    // No scheme and not a file - yikes!!! Let's bail and
                    // use fall-back file.
                    projectPropsUri = null;
                    throw new URISyntaxException(environmentProjectPropsFile, "Not a valid file");
                }
            }
        } catch (URISyntaxException e) {
            // fall back to default file
            logger.error("Unable to load properties file: {} -- reason: {}", environmentProjectPropsFile,
                    e.getReason());
            logger.error("Falling back to default {} file: {}", ApplicationConstants.PROJECT_PROPS,
                    ApplicationConstants.PROJECT_PROPS);
        }
    }

    applicationProps = new Properties();
    // load properties if environment value set
    if (projectPropsUri != null) {
        File envPropFile = new File(projectPropsUri);
        if (envPropFile.exists() && envPropFile.isFile() && envPropFile.canRead()) {
            Reader reader;
            try {
                reader = new FileReader(envPropFile);
                logger.info("About to load {} from environment: {}", ApplicationConstants.PROJECT_PROPS,
                        envPropFile.getAbsolutePath());
                applicationProps.load(reader);
                logger.info("Success -- loaded properties file.");
            } catch (IOException e) {
                logger.error("Could not load environment properties file: {}", projectPropsUri, e);
                // set URI back to null so default prop file loaded
                projectPropsUri = null;
            }
        }
    }

    if (projectPropsUri == null) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            InputStream resourceStream = loader.getResourceAsStream(ApplicationConstants.PROJECT_PROPS);
            applicationProps.load(resourceStream);
            logger.info("loaded default applicationProps: ");
        } catch (IOException e) {
            logger.error("Could not load properties file: {}", ApplicationConstants.PROJECT_PROPS, e);
            // couldn't load default properties so bail...
            throw new RuntimeException("Couldn't load an applications properties file.", e);
        }
    }
}