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:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java

/**
 * Speichert den Kontoauszug in einer Datei.
 * @param ka der Kontoauszug./* w w w. ja  v a  2s .c om*/
 * @param target die Datei, in der der Kontoauszug gespeichert werden soll.
 * @throws ApplicationException
 */
public static void store(Kontoauszug ka, File target) throws ApplicationException {
    if (ka == null)
        throw new ApplicationException(i18n.tr("Bitte whlen Sie den zu speichernden Kontoauszug"));

    if (target == null)
        throw new ApplicationException(i18n.tr("Bitte whlen Sie die Zieldatei aus"));

    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()));
            }

            FileCopy.copy(file, target, true);
            Logger.info("copied " + file + " to " + target);
            return;
        }

        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);

        OutputStream os = null;

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

        Logger.info("copied messaging data into file: " + target);
    } 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:com.redhat.tools.nexus.audit.serial.store.JsonAuditStore.java

private AuditInfo getAuditInformation(final File auditFile) throws AuditStoreException {
    if (auditFile.exists() && auditFile.isFile() && auditFile.canRead()) {
        FileReader reader = null;
        try {// ww w  .  j a v  a2 s  .  com
            reader = new FileReader(auditFile);
            return getGson().fromJson(reader, AuditInfo.class);
        } catch (final FileNotFoundException e) {
            throw new AuditStoreException("Cannot open audit file: %s\nReason: %s", e, auditFile,
                    e.getMessage());
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }

    return null;
}

From source file:com.sap.prd.mobile.ios.mios.FatLibAnalyzer.java

FatLibAnalyzer(final File fatLib) {
    if (fatLib == null)
        throw new NullPointerException();

    if (!fatLib.canRead())
        throw new IllegalArgumentException("Cannot access " + fatLib + ".");

    this.fatLib = fatLib;
}

From source file:uk.urchinly.wabi.expose.DownloadController.java

@RequestMapping(value = "/download/{assetId}", method = RequestMethod.GET)
public void download(HttpServletResponse response, @PathVariable("assetId") String assetId) throws IOException {

    Asset asset = this.assetMongoRepository.findOne(assetId);

    if (asset == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from  w  w  w. jav a 2 s  . com
    }

    File file = new File(appSharePath, asset.getFileName());

    if (file.canRead()) {
        this.rabbitTemplate.convertAndSend(MessagingConstants.USAGE_ROUTE,
                new UsageEvent("download asset", asset.toString()));

        response.setContentType(asset.getContentType());
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } else {
        logger.warn("File '{}' not found.", file.getAbsolutePath());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:net.nicholaswilliams.java.teamcity.plugin.linux.AbstractLinuxPropertiesLocator.java

private void determinePluginVersion(File pluginRoot, Map<String, String> properties) {
    File versionFile = new File(pluginRoot, "version.properties");
    if (versionFile.exists()) {
        if (versionFile.canRead()) {
            Properties versionProperties = new Properties();
            FileInputStream stream = null;
            try {
                stream = FileUtils.openInputStream(versionFile);
                versionProperties.load(stream);
                if (versionProperties.getProperty(LinuxPropertiesLocator.PLUGIN_VERSION_KEY) != null) {
                    properties.put(LinuxPropertiesLocator.PLUGIN_VERSION_KEY,
                            versionProperties.getProperty(LinuxPropertiesLocator.PLUGIN_VERSION_KEY));
                }//from www. j a v  a  2s  .c om
            } catch (IOException e) {
                AbstractLinuxPropertiesLocator.logger
                        .error("linux-system-properties plugin version file could not be read.", e);
            } finally {
                try {
                    if (stream != null)
                        stream.close();
                } catch (IOException e) {
                    AbstractLinuxPropertiesLocator.logger.warn("Unable to close version file after reading.",
                            e);
                }
            }
        } else {
            AbstractLinuxPropertiesLocator.logger
                    .warn("linux-system-properties plugin version file not readable.");
        }
    } else {
        AbstractLinuxPropertiesLocator.logger.warn("linux-system-properties plugin version file not found.");
    }
}

From source file:org.apache.solr.kelvin.App.java

private JsonNode readFileToJsonNode(File file) throws Exception {
    if (file.canRead()) {
        String text = FileUtils.readFileToString(file, defautEncoding);
        return parseJson(text);
    } else {//from w ww.j a  v  a2  s. com
        throw new Exception("Cannot read " + file.getName());
    }
}

From source file:com.swater.meimeng.activity.oomimg.ImageCache.java

/**
 * Blocking call to scale a local file. Scales using preserving aspect ratio
 *
 * @param localFile// w w w  .j  a  va 2  s  .co  m
 *            local image file to be scaled
 * @param width
 *            maximum width
 * @param height
 *            maximum height
 * @return the scaled image
 * @throws org.apache.http.client.ClientProtocolException
 * @throws java.io.IOException
 */
private static Bitmap scaleLocalImage(File localFile, int width, int height)
        throws ClientProtocolException, IOException {

    if (DEBUG) {
        Log.d(TAG, "scaleLocalImage(" + localFile + ", " + width + ", " + height + ")");
    }

    if (!localFile.exists()) {
        throw new IOException("local file does not exist: " + localFile);
    }
    if (!localFile.canRead()) {
        throw new IOException("cannot read from local file: " + localFile);
    }

    // the below borrowed from:
    // https://github.com/thest1/LazyList/blob/master/src/com/fedorvlasov/lazylist/ImageLoader.java

    // decode image size
    final BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;

    BitmapFactory.decodeStream(new FileInputStream(localFile), null, o);

    // Find the correct scale value. It should be the power of 2.
    //final int REQUIRED_WIDTH = width, REQUIRED_HEIGHT = height;
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp / 2 <= width || height_tmp / 2 <= height) {
            break;
        }
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // decode with inSampleSize
    final BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    final Bitmap prescale = BitmapFactory.decodeStream(new FileInputStream(localFile), null, o2);

    if (prescale == null) {
        Log.e(TAG, localFile + " could not be decoded");
    } else if (DEBUG) {
        Log.d(TAG, "Successfully completed scaling of " + localFile + " to " + width + "x" + height);
    }

    return prescale;
}

From source file:fr.inria.ucn.collectors.AppDataUsageCollector.java

@Override
public void run(Context c, long ts) {
    try {//ww  w  .  j  a v  a 2s  .c  o  m
        // data used per app
        JSONArray parray = new JSONArray();

        File f = new File(PROC_UID_STAT);
        if (f.exists() && f.isDirectory() && f.canRead()) {
            for (String dir : f.list()) {
                parray.put(getProcInfo(c, Integer.parseInt(dir)));
            }
        } else {
            ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningAppProcessInfo pinfo : am.getRunningAppProcesses()) {
                parray.put(getProcInfo(c, pinfo.uid));
            }
        }

        // done
        Helpers.sendResultObj(c, "app_data_usage", ts, new JSONObject().put("process_list", parray));

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:org.opengeo.gsr.core.controller.ImageResourceController.java

public boolean dispatchImageResource(final String fileName, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    final boolean debug = logger.isDebugEnabled();
    if (debug) {/*from  w  ww  .  j  a va 2s  .c  o  m*/
        logger.debug("Attemping to dispatch image resource: " + fileName);
    }

    boolean resolved = false;
    File imageFile = new File(imageBaseDirectory, fileName);
    if (imageFile.canRead()) {
        try {
            commitResponse(imageFile, response);
            resolved = true;
        } catch (IOException e) {
            logger.info(e.getMessage());
            if (debug) {
                logger.debug("Error dispatching image resource response", e);
            }
        }
    }
    return resolved;
}

From source file:org.red5.server.LoaderBase.java

/**
 * Set the folder containing webapps.//from  w  ww. j  a  v a2 s  .  c  o m
 * 
 * @param webappFolder web app folder
 */
public void setWebappFolder(String webappFolder) {
    File fp = new File(webappFolder);
    if (!fp.canRead()) {
        throw new RuntimeException(String.format("Webapp folder %s cannot be accessed.", webappFolder));
    }
    if (!fp.isDirectory()) {
        throw new RuntimeException(String.format("Webapp folder %s doesn't exist.", webappFolder));
    }
    fp = null;
    this.webappFolder = webappFolder;
}