Example usage for java.io FileNotFoundException FileNotFoundException

List of usage examples for java.io FileNotFoundException FileNotFoundException

Introduction

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

Prototype

public FileNotFoundException(String s) 

Source Link

Document

Constructs a FileNotFoundException with the specified detail message.

Usage

From source file:com.google.gerrit.server.documentation.MarkdownFormatter.java

private static String readPegdownCss(AtomicBoolean file) throws IOException {
    String name = "pegdown.css";
    URL url = MarkdownFormatter.class.getResource(name);
    if (url == null) {
        throw new FileNotFoundException("Resource " + name);
    }/*from w  ww.ja  v a 2  s  . c  o m*/
    file.set("file".equals(url.getProtocol()));
    try (InputStream in = url.openStream(); TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(128 * 1024)) {
        tmp.copy(in);
        return new String(tmp.toByteArray(), UTF_8);
    }
}

From source file:fm.last.moji.local.LocalMojiFile.java

@Override
public void modifyStorageClass(String newStorageClass) throws IOException {
    if (storageClass == null) {
        throw new IllegalArgumentException("storageClass == null");
    }/*from  w  w w .  j ava 2s  . co m*/
    if (!file.exists()) {
        throw new FileNotFoundException(file.getCanonicalPath());
    }
    file.renameTo(new File(baseDir, namingStrategy.newFileName(domain, key, newStorageClass)));
    this.storageClass = newStorageClass;
}

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

public void updateStringValue(String key, String value) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("Plist file '" + plist + "' not found.");
    }/*from  w ww . j ava  2 s.co  m*/

    try {
        String command = "/usr/libexec/PlistBuddy -x -c \"Set :" + key + " " + value + "\" \""
                + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Set command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.uzk.hki.da.cb.PrepareSendToPresenterAction.java

static Object readRightsFromPREMIS(File premisXML) throws IOException {

    if (premisXML == null)
        throw new IllegalArgumentException("premisXML is null");
    if (!premisXML.exists())
        throw new FileNotFoundException("Missing file or directory: " + premisXML);

    Object premisObject = null;// w  ww .j  av  a2 s.com
    try {

        premisObject = new ObjectPremisXmlReader().deserialize(premisXML);

    } catch (ParseException pe) {
        throw new RuntimeException("error while parsing PREMIS-file", pe);
    }
    return premisObject;
}

From source file:it.geosolutions.unredd.stats.impl.StatsRunner.java

/**
 * This method is the main entry point for Statistics Calculation. 
 * Its purpose is to process the provided StatisticConfiguration object and instantiate and run a RasterClassifiedStatistics object 
 * that is "StatisticConfiguration unaware". The results provided by RasterClassifiedStatistics object is stored in an output file.
 * /*from w  w  w . jav a  2s  .c o  m*/
 * @throws IOException
 */
public void run() throws IOException {

    LOGGER.info("Preparing stats...");
    boolean deferredMode = cfg.isDeferredMode();

    DataFile data = new DataFile();
    File dataF = new File(cfg.getDataLayer().getFile());
    if (!dataF.exists())
        throw new FileNotFoundException("Data layer file not found: " + dataF.getAbsolutePath());
    else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Stats data file: " + dataF.getAbsolutePath());
    }
    data.setFile(dataF);
    data.setNoValue(cfg.getDataLayer().getNodata()); // may be null
    data.setRanges(cfg.getDataLayer().getRanges());

    int cnt = -1;
    int pivotIndex = -1;

    List<DataFile> cls = new ArrayList<DataFile>(cfg.getClassifications().size());
    for (ClassificationLayer cl : cfg.getClassifications()) {
        cnt++;
        if (cl.isPivotDefined())
            pivotIndex = cnt;
        DataFile df = new DataFile();
        File file = new File(cl.getFile()); // we're assuming they're all files
        if (!file.exists())
            throw new FileNotFoundException("Classification layer file not found: " + file.getAbsolutePath());
        else if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Stats classification file: " + file.getAbsolutePath());
        }
        df.setFile(file);
        df.setNoValue(cl.getNodata());
        cls.add(df);
        LOGGER.info("Added classification layer " + file.getName() + " order " + cnt + " pivot:"
                + cl.isPivotDefined());
    }

    List<Statistic> stats = new ArrayList<Statistic>();
    for (int i = 0; i < cfg.getStats().size(); i++) {
        StatsType statsType = cfg.getStats().get(i);
        switch (statsType) {
        case COUNT:
            countIndex = i;
            break;
        case MIN:
            stats.add(Statistic.MIN);
            statsIndexes.put(Statistic.MIN, i);
            break;
        case MAX:
            stats.add(Statistic.MAX);
            statsIndexes.put(Statistic.MAX, i);
            break;
        case SUM:
            stats.add(Statistic.SUM);
            statsIndexes.put(Statistic.SUM, i);
            break;
        default:
            throw new IllegalStateException("Unknown statstype " + statsType);
        }
    }

    LOGGER.info("Running stats...");
    RasterClassifiedStatistics rcs = new RasterClassifiedStatistics();
    rcs.setRoiGeom(roiGeom);
    Map<MultiKey, List<Result>> results = rcs.execute(deferredMode, data, cls, stats);

    LOGGER.info("Outputting stats results...");

    Map<Integer, List<Double>> pivot = new TreeMap<Integer, List<Double>>();

    if (pivotIndex == -1 || pivotIndex == 0) { // no pivotting
        outputStats(results);
    } else {
        LOGGER.info("Pivoting...");
        pivot(results, pivotIndex, cfg.getClassifications().get(pivotIndex).getPivot());
    }

}

From source file:com.remobile.file.AssetFilesystem.java

private long getAssetSize(String assetPath) throws FileNotFoundException {
    if (assetPath.startsWith("/")) {
        assetPath = assetPath.substring(1);
    }/* w w w  .  j av  a 2s. c o m*/
    lazyInitCaches();
    if (lengthCache != null) {
        Long ret = lengthCache.get(assetPath);
        if (ret == null) {
            throw new FileNotFoundException("Asset not found: " + assetPath);
        }
        return ret;
    }
    CordovaResourceApi.OpenForReadResult offr = null;
    try {
        offr = resourceApi.openForRead(nativeUriForFullPath(assetPath));
        long length = offr.length;
        if (length < 0) {
            // available() doesn't always yield the file size, but for assets it does.
            length = offr.inputStream.available();
        }
        return length;
    } catch (IOException e) {
        throw new FileNotFoundException("File not found: " + assetPath);
    } finally {
        if (offr != null) {
            try {
                offr.inputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.ning.maven.plugins.duplicatefinder.ClasspathDescriptor.java

public void add(File element) throws IOException {
    if (!element.exists()) {
        throw new FileNotFoundException("Path " + element + " doesn't exist");
    }/*from  ww w. j a va2 s. com*/
    if (element.isDirectory()) {
        addDirectory(element);
    } else {
        addArchive(element);
    }
}

From source file:read.taz.TazDownloader.java

private void downloadFile() throws ClientProtocolException, IOException {
    if (tazFile.file.exists()) {
        Log.w(getClass().getSimpleName(), "File " + tazFile + " exists.");
        return;/*ww  w . j  a  v a2 s.c o m*/
    }
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    HttpConnectionParams.setSoTimeout(httpParams, 15000);

    DefaultHttpClient client = new DefaultHttpClient(httpParams);

    Credentials defaultcreds = new UsernamePasswordCredentials(uname, passwd);

    client.getCredentialsProvider()
            .setCredentials(new AuthScope(/* FIXME DRY */"dl.taz.de", 80, AuthScope.ANY_REALM), defaultcreds);

    URI uri = tazFile.getDownloadURI();
    Log.d(getClass().getSimpleName(), "Downloading taz from " + uri);
    HttpGet get = new HttpGet(uri);
    HttpResponse response = client.execute(get);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Download failed with HTTP Error" + response.getStatusLine().getStatusCode());
    }

    String contentType = response.getEntity().getContentType().getValue();
    if (contentType.startsWith("text/html")) {
        Log.d(getClass().getSimpleName(),
                "Content type: " + contentType + " encountered. Assuming a non exisiting file");

        ByteArrayOutputStream htmlOut = new ByteArrayOutputStream();
        response.getEntity().writeTo(htmlOut);
        String resp = new String(htmlOut.toByteArray());
        Log.d(getClass().getSimpleName(), "Response: " + resp);
        throw new FileNotFoundException("No taz found for date " + tazFile.date.getTime());
    } else {
        FileOutputStream tazOut = new FileOutputStream(tazFile.file);
        try {
            response.getEntity().writeTo(tazOut);
        } finally {
            tazOut.close();
        }
    }

    // InputStream docStream = response.getEntity().getContent();
    // FileOutputStream out = null;
    // try {
    // out = tazOut;
    // byte[] buf = new byte[4096];
    // for (int read = docStream.read(buf); read != -1; read = docStream
    // .read(buf)) {
    // out.write(buf, 0, read);
    // }
    // } finally {
    // docStream.close();
    // if (out != null) {
    // out.close();
    // }
    // }

}

From source file:las.DBConnector.java

/**
 * Load CSV test data into SQL Table/*from w  ww . j a v a2 s . co  m*/
 *
 * example for clearFirst: boolean check =
 * DBConnector.checkDataExistedInTable("MEMBERS");
 *
 * if (check) { DBConnector.loadCSVIntoTable("src/resources/members.csv",
 * "MEMBERS", true); System.out.println("Test data inserted into MEMBERS
 * table"); }
 *
 * ignore createNewReader, since it uses for loadCSVIntoTable, don't modify
 * it
 *
 * Getter and Setter provided for Separator to set your own separator inside
 * your CSV File
 *
 * @param csvFile : src/resources/xxx.csv (put your csv file under this
 * path)
 * @param tableName: TABLENAME (All in capital letters)
 * @param clearFirst true = if data not existed in SQL Table, write test
 * data inside false = if data exisited in SQL Table, don't write again.
 * @throws java.lang.Exception
 */
public static void loadCSVIntoTable(String csvFile, String tableName, boolean clearFirst) throws Exception {

    CSVReader csvReader = null;
    if (null == DBConnector.conn) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = DBConnector.getInstance().createNewReader(csvFile);

    } catch (ClassNotFoundException | SQLException | FileNotFoundException e) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. " + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);

    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    String[] nextLine;
    PreparedStatement ps = null;
    try {
        conn.setAutoCommit(false);
        ps = conn.prepareStatement(query);

        if (clearFirst) {
            //delete data from table before loading csv
            conn.createStatement().execute("DELETE FROM " + tableName);
        }

        final int batchSize = 1000;
        int count = 0;
        Date date = null;
        while ((nextLine = csvReader.readNext()) != null) {

            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    date = DateUtil.convertToDate(string);
                    if (null != date) {
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                    } else {
                        ps.setString(index++, string);
                    }
                }
                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
            }
        }
        ps.executeBatch(); // insert remaining records
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        e.printStackTrace();
        throw new Exception("Error occured while loading data from file to database." + e.getMessage());
    } finally {
        if (null != ps) {
            ps.close();
        }

        csvReader.close();
    }
}

From source file:com.codefollower.lealone.omid.OmidTestBase.java

private static void delete(File f) throws IOException {
    if (f.isDirectory()) {
        for (File c : f.listFiles())
            delete(c);//from ww w  .  j  a  va 2s.com
    }
    if (!f.delete())
        throw new FileNotFoundException("Failed to delete file: " + f);
}