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.bahmanm.karun.PacmanConfHelper.java

/**
 * Constructor//  www. jav  a  2  s . co m
 * 
 * @param confPath Absolute path to 'pacman.conf'.
 */
private PacmanConfHelper(String confPath) throws PacmanConfPathException, FileNotFoundException, IOException {
    // Check for existence
    File f = new File(confPath);
    if (!f.exists() || !f.canRead() || !f.isFile()) {
        throw new PacmanConfPathException(confPath);
    }

    this.confPath = confPath;
    extractInfo();
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static File locateBootstrapperFile() {
    ProtectionDomain protectionDomain = Bootstrapper.class.getProtectionDomain();
    if (protectionDomain == null) {
        JOptionPane.showMessageDialog(null,
                "Error: Could not locate Bootstrapper. (ProtectionDomain was null)");
        throw new RuntimeException();
    }/*from  w ww  . j a v a 2 s.  com*/
    CodeSource codeSource = protectionDomain.getCodeSource();
    if (codeSource == null) {
        JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (CodeSource was null)");
        throw new RuntimeException();
    }
    URL url = codeSource.getLocation();
    if (url == null) {
        JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (Location was null)");
        throw new RuntimeException();
    }
    try {
        URI uri = url.toURI();
        File file = new File(uri.getPath());
        if (file.isDirectory()) {
            if (!Boolean.getBoolean("com.heliosdecompiler.isDebugging")) {
                JOptionPane.showMessageDialog(null,
                        "Error: Could not locate Bootstrapper. (File is directory)");
                throw new RuntimeException(file.getAbsolutePath());
            } else {
                System.out.println(
                        "Warning: Could not locate bootstrapper but com.heliosdecompiler.isDebugging was set to true");
            }
        } else if (!file.exists()) {
            JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (File does not exist)");
            throw new RuntimeException();
        } else if (!file.canRead()) {
            JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (File is not readable)");
            throw new RuntimeException();
        }
        return file;
    } catch (URISyntaxException e) {
        JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (URISyntaxException)");
        throw new RuntimeException();
    }
}

From source file:com.thoughtworks.go.plugin.infra.commons.PluginsZip.java

private void checkFilesAccessibility(File bundledPlugins, File externalPlugins) {
    boolean bundled = bundledPlugins.canRead();
    boolean external = externalPlugins.canRead();
    if (!bundled || !external) {
        String folder = bundled ? externalPlugins.getAbsolutePath() : bundledPlugins.getAbsolutePath();
        LOG.error("Could not read plugins. Please check access rights on files in folder: {}.", folder);
        throw new FileAccessRightsCheckException(String.format(
                "Could not read plugins. Please make sure that the user running GoCD can access %s", folder));
    }/*from   www . ja v  a 2s .  c om*/
}

From source file:org.pegadi.webapp.view.FileView.java

protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // get the file from the map
    File file = (File) map.get("file");

    // check if it exists
    if (file == null || !file.exists() || !file.canRead()) {
        log.warn("Error reading: " + file);
        try {//from  w ww  .  ja  v  a 2  s . co m
            response.sendError(404);
        } catch (IOException e) {
            log.error("Could not write to response", e);
        }
        return;
    }
    // give some info in the response
    response.setContentType(getServletContext().getMimeType(file.getAbsolutePath()));
    // files does not change so often, allow three days caching
    response.setHeader("Cache-Control", "max-age=259200");
    response.setContentLength((int) file.length());

    // start writing to the response
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
        out = new BufferedOutputStream(response.getOutputStream());
        in = new BufferedInputStream(new FileInputStream(file));
        int c = in.read();
        while (c != -1) {
            out.write(c);
            c = in.read();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:com.github.riccardove.easyjasub.EasyJaSubInputFromCommand.java

private static void checkFile(String fileName, File file) throws EasyJaSubException {
    if (!file.exists()) {
        throw new EasyJaSubException("File " + fileName + " does not exist");
    }/*from w  w  w . j ava  2  s. c o m*/
    if (!file.isFile()) {
        throw new EasyJaSubException(fileName + " is not a file");
    }
    if (!file.canRead()) {
        throw new EasyJaSubException("File " + fileName + " can not be read");
    }
}

From source file:de.th.wildau.dsc.sne.webserver.WebServer.java

/**
 * Load the web server configuration. <b>DON'T USE LOG BEFORE THIS METHOD
 * CALL!</b>//  w  w w.j  a v  a2s . co  m
 * 
 * @param startArguments
 *            array
 */
private void loadConfiguration(String[] startArguments) {

    Options options = new Options();
    options.addOption("c", true, "specify server configuration file");
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.printHelp("WebServer", options);
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, startArguments);
    } catch (final ParseException ex) {
        throw new IllegalStateException("Can not parse start arguments. " + ex.getMessage());
    }

    try {
        if (cmd.hasOption("c")) {
            File configFile = new File(cmd.getOptionValue("c"));
            if (configFile.isFile() && configFile.canRead()) {
                Configuration.createInstance(configFile);
            }
        } else {
            // load default configuration
            Configuration.createInstance();
            System.out.println("Load default config: " + Configuration.getConfig().toString());
        }

        Log.createInstance();
        Log.info("loaded server configuration");
    } catch (final Exception ex) {
        System.err.println("Can not load server configuration file.");
    }
}

From source file:com.spotify.helios.authentication.crtauth.CrtAuthProviderFactory.java

@Override
public ServerAuthProvider createServerAuthProvider(final String serverName, final String secret) {
    final ObjectMapper mapper = new ObjectMapper();
    final CrtAuthConfig config;
    try {/*from w w  w .j  a  va 2s .  c  om*/
        File f = new File(DEFAULT_CONFIG_FILE_PATH1);
        if (!f.isFile() || !f.canRead()) {
            f = new File(DEFAULT_CONFIG_FILE_PATH2);
        }
        config = mapper.readValue(f, CrtAuthConfig.class);
        final LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(config.getLdapUrl());
        contextSource.setAnonymousReadOnly(true);
        contextSource.setCacheEnvironmentProperties(false);
        final LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
        final KeyProvider keyProvider = new LdapKeyProvider(ldapTemplate, config.getLdapSearchPath());

        final CrtAuthServer crtAuthServer = new CrtAuthServer.Builder().setServerName(serverName)
                .setKeyProvider(keyProvider).setSecret(secret.getBytes()).build();

        final CrtAuthenticator authenticator = new CrtAuthenticator(crtAuthServer);
        final CrtInjectableProvider<User> userCrtAuthProvider = new CrtInjectableProvider<>(authenticator);

        return new CrtServerAuthProvider(userCrtAuthProvider, new CrtHttpAuthenticator(crtAuthServer));
    } catch (IOException e) {
        throw new RuntimeException(String.format("Could not find or read config file at %s or %s.",
                DEFAULT_CONFIG_FILE_PATH1, DEFAULT_CONFIG_FILE_PATH2));
    }
}

From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java

/**
 * Liefert das File-Objekt fuer diesen Kontoauszug.
 * Wenn er direkt im Filesystem gespeichert ist, wird dieses geliefert.
 * Wurde er jedoch per Messaging gespeichert, dann ruft die Funktion ihn
 * vom Archiv ab und erzeugt eine Temp-Datei mit dem Kontoauszug.
 * @param ka der Kontoauszug./*from   w  w  w.j a v  a  2 s . c o  m*/
 * @return die Datei.
 * @throws ApplicationException
 */
public static File getFile(Kontoauszug ka) throws ApplicationException {
    if (ka == null)
        throw new ApplicationException(i18n.tr("Bitte whlen Sie den zu ffnenden Kontoauszug"));

    try {
        // Wenn ein Pfad und Dateiname angegeben ist, dann sollte die Datei
        // dort auch liegen
        final String path = StringUtils.trimToNull(ka.getPfad());
        final String name = StringUtils.trimToNull(ka.getDateiname());

        if (path != null && name != null) {
            File file = new File(path, name);

            Logger.info("trying to open pdf file from: " + file);
            if (!file.exists()) {
                Logger.error("file does not exist (anymore): " + file);
                throw new ApplicationException(i18n
                        .tr("Datei \"{0}\" existiert nicht mehr. Wurde sie gelscht?", file.getAbsolutePath()));
            }

            if (!file.canRead()) {
                Logger.error("cannot read file: " + file);
                throw new ApplicationException(i18n.tr("Datei \"{0}\" nicht lesbar", file.getAbsolutePath()));
            }

            return file;
        }

        final String uuid = StringUtils.trimToNull(ka.getUUID());

        Logger.info("trying to open pdf file using messaging, uuid: " + uuid);

        // Das kann eigentlich nicht sein. Dann wuerde ja alles fehlen
        if (uuid == null)
            throw new ApplicationException(i18n.tr("Ablageort des Kontoauszuges unbekannt"));

        QueryMessage qm = new QueryMessage(uuid, null);
        Application.getMessagingFactory().getMessagingQueue("jameica.messaging.get").sendSyncMessage(qm);
        byte[] data = (byte[]) qm.getData();
        if (data == null) {
            Logger.error("got no data from messaging for uuid: " + uuid);
            throw new ApplicationException(
                    i18n.tr("Datei existiert nicht mehr im Archiv. Wurde sie gelscht?"));
        }
        Logger.info("got " + data.length + " bytes from messaging for uuid: " + uuid);

        File file = File.createTempFile("kontoauszug-" + RandomStringUtils.randomAlphanumeric(5), ".pdf");
        file.deleteOnExit();

        OutputStream os = null;

        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            IOUtil.copy(new ByteArrayInputStream(data), os);
        } finally {
            IOUtil.close(os);
        }

        Logger.info("copied messaging data into temp file: " + file);
        return file;
    } catch (ApplicationException ae) {
        throw ae;
    } catch (Exception e) {
        Logger.error("unable to open file", e);
        throw new ApplicationException(i18n.tr("Fehler beim ffnen des Kontoauszuges: {0}", e.getMessage()));
    }
}

From source file:net.sasasin.sreader.batch.SingleAccountFeedReader.java

public void run() {
    logger.info(this.getClass().getSimpleName() + " is started.");

    File path = new File(System.getProperty("user.home") + File.separatorChar + "sreader.txt");

    if (!path.exists() || !path.isFile() || !path.canRead()) {
        System.out.println("FAIL;" + path.getPath() + " can not proc.");
        return;// w w w .  j a va2  s.  co  m
    }

    List<String> lines = null;
    try {
        lines = IOUtils.readLines(new FileReader(path));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    // import path to feed_url table.
    importSubscribe(lines);

    logger.info(this.getClass().getSimpleName() + " is ended.");
}

From source file:se.crisp.codekvast.agent.daemon.appversion.ManifestAppVersionStrategy.java

private File getJarFile(File codeBaseFile, String jarUri) throws IOException, URISyntaxException {
    URL url = null;/*from w w  w .j  av  a 2  s.c o m*/
    // try to parse it as a URL...
    try {
        url = new URL(jarUri);
    } catch (MalformedURLException ignore) {
    }

    if (url == null) {
        // Try to treat it as a file...
        File file = new File(jarUri);
        if (file.isFile() && file.canRead() && file.getName().endsWith(".jar")) {
            url = file.toURI().toURL();
        }
    }
    if (url == null) {
        // Search for it in codeBaseFile. Treat it as a regular expression for the basename
        url = search(codeBaseFile, jarUri);
    }

    File result = url == null ? null : new File(url.toURI());
    if (result == null || !result.canRead()) {
        throw new IOException("Cannot read " + jarUri);
    }
    return result;
}