Example usage for java.io FileReader close

List of usage examples for java.io FileReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:de.pdark.dsmp.ProxyDownload.java

/**
 * Do the download.//from  w  w  w .  java  2s .  co m
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in DSMP config");
    }

    // If there is a status file in the cache, return it instead of trying it again
    // As usual with caches, this one is a key area which will always cause
    // trouble.
    // TODO There should be a simple way to get rid of the cached statuses
    // TODO Maybe retry a download after a certain time?
    File statusFile = new File(dest.getAbsolutePath() + ".status");
    if (statusFile.exists()) {
        try {
            FileReader r = new FileReader(statusFile);
            char[] buffer = new char[(int) statusFile.length()];
            int len = r.read(buffer);
            r.close();
            String status = new String(buffer, 0, len);
            throw new DownloadFailed(status);
        } catch (IOException e) {
            log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
        }
    }

    mkdirs();

    HttpClient client = new HttpClient();

    String msg = "";
    if (config.useProxy(url)) {
        Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(),
                config.getProxyPassword());
        AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(config.getProxyHost(), config.getProxyPort());
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (0 == 1 && log.isDebugEnabled()) {
            Header[] header = get.getResponseHeaders();
            for (Header aHeader : header)
                log.debug(aHeader.toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            // Remember "File not found"
            if (status == HttpStatus.SC_NOT_FOUND) {
                try {
                    FileWriter w = new FileWriter(statusFile);
                    w.write(get.getStatusLine().toString());
                    w.close();
                } catch (IOException e) {
                    log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
                }
            }
            throw new DownloadFailed(get);
        }

        File dl = new File(dest.getAbsolutePath() + ".new");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        IOUtils.copy(get.getResponseBodyAsStream(), out);
        out.close();

        File bak = new File(dest.getAbsolutePath() + ".bak");
        if (bak.exists())
            bak.delete();
        if (dest.exists())
            dest.renameTo(bak);
        dl.renameTo(dest);
    } finally {
        get.releaseConnection();
    }
}

From source file:org.faul.jql.core.JCommon.java

/**
 * Load data from a file into a List of HashMaps.
 * @param fr FileReader. The filereader to load the data from.
 * @return List. The database table, a List of Maps.
 * @throws Exception. throws exceptions on File IO and Gson encoding errors.
 *//*from  www.j  a  v  a2s  . c  o  m*/
List loadFile(FileReader fr) throws Exception {
    char[] buf = new char[4096];
    String data = null;
    int rc = fr.read(buf);
    fr.close();
    data = new String(buf, 0, rc);
    Object rets = mapper.readValue((String) data, Object.class);
    if (rets instanceof ArrayList == false) {
        throw new Exception("List class not returned!");
    }
    return (List) rets;
}

From source file:de.ingrid.codelistHandler.migrate.Migrator.java

@SuppressWarnings("unchecked")
public void run() {
    // since v4.4.0 we separated the codelists so that we need to read the codelist.xml file and store it
    // in separate files under a new directory
    File oldCodelistsFile = new File("data/codelists.xml");
    if (oldCodelistsFile.exists() && oldCodelistsFile.isFile()) {
        FileReader codelistReader;
        try {/*from   ww  w. ja  v  a  2 s.  co m*/
            codelistReader = new FileReader(oldCodelistsFile);
            XStream xStream = new XStream();
            List<CodeList> oldCodelists = (List<CodeList>) xStream.fromXML(codelistReader);
            codeListService.persistToAll(oldCodelists);
            codelistReader.close();

            log.info("Successfully migrated old codelists");

            boolean deleteSuccess = oldCodelistsFile.delete();
            if (!deleteSuccess) {
                log.warn("Couldn't delete file: " + oldCodelistsFile.getName());
            }

        } catch (FileNotFoundException e) {
            log.error("Could not migrate old codelists", e);
        } catch (IOException e) {
            log.error("Problem during migration of old codelists.", e);
        }
    }
}

From source file:com.appcelerator.titanium.desktop.ui.wizard.TiManifestTest.java

protected void assertTiManifestContents(File file, final String appId, final String appName, final String guid,
        final String version, final String description, final String publisher, final String url,
        Set<String> platforms, String runtime, boolean release, String visibility, boolean showSplash)
        throws IOException, ParseException, FileNotFoundException {
    JSONParser parser = new JSONParser();
    JSONObject resultJSON = null;/*from w  w  w  .jav a  2s . co m*/
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        resultJSON = (JSONObject) parser.parse(reader);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    assertNotNull(resultJSON);
    assertEquals("App ID didn't match", appId, resultJSON.get(TiManifest.APPID));
    assertEquals("App name didn't match", appName, resultJSON.get(TiManifest.APPNAME));
    assertEquals("App version didn't match", version, resultJSON.get(TiManifest.APPVERSION));
    assertEquals("App description didn't match", description, resultJSON.get(TiManifest.DESC));
    assertEquals("App GUID didn't match", guid, resultJSON.get(TiManifest.GUID));
    assertEquals("MID didn't match", TitaniumCorePlugin.getMID(), resultJSON.get(TiManifest.MID));
    assertEquals("'noinstall' value was incorrect", !showSplash, resultJSON.get(TiManifest.NO_INSTALL));
    JSONArray platformsArray = (JSONArray) resultJSON.get(TiManifest.PLATFORMS);
    assertEquals("'platforms' array size didn't match", platforms.size(), platformsArray.size());
    for (String platform : platforms) {
        assertTrue("'platforms' array didn't contain expected value: " + platform,
                platformsArray.contains(platform));
    }
    assertEquals("App publisher didn't match", publisher, resultJSON.get(TiManifest.PUBLISHER));
    assertEquals("'release' boolean didn't match", release, resultJSON.get(TiManifest.RELEASE));
    JSONObject runtimeObj = (JSONObject) resultJSON.get(TiManifest.RUNTIME);
    assertEquals("'runtime' didn't match", runtime, runtimeObj.get(TiManifest.PACKAGE));
    assertEquals("App URL didn't match", url, resultJSON.get(TiManifest.URL));
    assertEquals("Visibility is incorrect", visibility, resultJSON.get(TiManifest.VISIBILITY));
}

From source file:org.geotools.gce.imagemosaic.FootprintUtils.java

/**
 * Given a footprint summary file (.fpt), populate the provided
 * footprints <ID-Geometry> pairs Map
 * //from  w  w  w.jav  a  2  s  . co  m
 * @param footprintSummaryFile
 *            the footprint summary file.
 * @param footprintsIDGeometryMap
 *            the Map to be populated
 */
static void initFootprintsGranuleIDGeometryMap(final File footprintSummaryFile,
        final Map<String, Geometry> footprintsIDGeometryMap) {
    Utilities.ensureNonNull("footprintSummaryFile", footprintSummaryFile);
    if (!footprintSummaryFile.exists() || !footprintSummaryFile.canRead()) {
        throw new IllegalArgumentException(
                "Unable to access to the provided footprint file " + footprintSummaryFile.getAbsolutePath());
    }
    Utilities.ensureNonNull("footprintsID_GeometryMap", footprintsIDGeometryMap);

    FileReader reader = null;
    try {
        reader = new FileReader(footprintSummaryFile);
        BufferedReader bReader = new BufferedReader(reader);
        String footprint;

        final WKTReader geometryReader = new WKTReader();
        while ((footprint = bReader.readLine()) != null) {
            String fpt[] = footprint.split("=");
            if (fpt.length == 2) {
                // parse the geometry
                footprintsIDGeometryMap.put(fpt[0], geometryReader.read(fpt[1]));
            }
        }
        bReader.close();
    } catch (IOException e) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
        }
    } catch (ParseException e) {

        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
        }
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }
            IOUtils.closeQuietly(reader);
        }
    }
}

From source file:nl.systemsgenetics.cellTypeSpecificAlleleSpecificExpression.BetaBinomOverdispInSample.java

@SuppressWarnings({ "empty-statement", "empty-statement" })
public BetaBinomOverdispInSample(String filename) throws FileNotFoundException, IOException {

    sampleName = filename;/*from   w w  w .  jav  a2  s  .com*/

    if (GlobalVariables.verbosity >= 10) {
        System.out.println("\n--- Starting beta binomial dispersion estimate ---");
        System.out.println("AS File: " + sampleName);
        System.out.println("--------------------------------------------------");
    }

    ArrayList<IndividualSnpData> allSnps = new ArrayList<IndividualSnpData>();

    File file = new File(filename);
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line;
    while ((line = br.readLine()) != null) {
        allSnps.add(new IndividualSnpData(file.getAbsolutePath(), line));
    }
    br.close();
    fr.close();

    ArrayList<IndividualSnpData> hets;
    hets = UtilityMethods.isolateHeterozygotesFromIndividualSnpData(allSnps);

    int numOfHets = hets.size();

    int[] asRef = new int[numOfHets];
    int[] asAlt = new int[numOfHets];

    int totalRef = 0;
    int totalAlt = 0;

    for (int i = 0; i < numOfHets; i++) {
        asRef[i] = hets.get(i).getRefNum();
        asAlt[i] = hets.get(i).getAltNum();

        totalRef += asRef[i];
        totalAlt += asAlt[i];

    }
    if (GlobalVariables.verbosity >= 10) {
        System.out.println("sample loaded");

        System.out.println("\ttotal_ref = " + totalRef);
        System.out.println("\ttotal_alt = " + totalAlt);
    }

    BetaBinomLikelihoodForOverdispersion betaBinom = new BetaBinomLikelihoodForOverdispersion(asRef, asAlt);
    NelderMeadSimplex simplex;
    simplex = new NelderMeadSimplex(1);
    SimplexOptimizer optimizer = new SimplexOptimizer(GlobalVariables.simplexThreshold,
            GlobalVariables.simplexThreshold); //numbers are to which precision you want it to be done.
    PointValuePair solution = optimizer.optimize(new ObjectiveFunction(betaBinom),
            new MaxEval(GlobalVariables.maximumIterations), simplex, GoalType.MINIMIZE,
            new InitialGuess(new double[] { 0.5 }), new SearchInterval(0.0, 1.0));

    overdispersion = solution.getFirst();
    if (GlobalVariables.verbosity >= 10) {
        System.out.println("Log likelihood converged to a threshold of "
                + Double.toString(GlobalVariables.simplexThreshold));
        System.out.println("\tDispersion sigma: " + Double.toString(overdispersion[0]));
        System.out.println("\tLog likelihood:   " + Double.toString(betaBinom.value(overdispersion)));
    }

}

From source file:org.accada.reader.hal.impl.sim.BatchSimulator.java

/**
 * initializes the fields and starts the simulator.
 *
 * @throws SimulatorException if the event input file could not be opened.
 *///from   ww  w.  ja  va  2  s .  co  m
private void initSimulator() throws SimulatorException {
    // load properties from properties file
    Properties props = new Properties();
    try {
        props.load(this.getClass().getResourceAsStream(PROPERTIES_FILE_LOCATION));
    } catch (IOException e) {
        throw new SimulatorException("Could not load the properties from properties file.");
    }

    // check properties
    if (!props.containsKey("batchfile")) {
        throw new SimulatorException("Property 'batchfile' not found.");
    }
    if (!props.containsKey("iterations")) {
        throw new SimulatorException("Property 'iterations' not found.");
    }

    // get properties
    String file = props.getProperty("batchfile");
    cycles = Long.parseLong(props.getProperty("iterations"));

    eventFile = new File(file);
    rfidThread = null;
    threadRunning = false;
    stopRequested = false;

    try {
        // tries to open file
        FileReader in = new FileReader(eventFile);
        in.close();

        // start simulator thread
        start();
    } catch (IOException e) {
        throw new SimulatorException("Cannot open event file '" + file + "': " + e);
    }
}

From source file:org.apache.hadoop.mapred.UtilsForTests.java

/**
 * Get PID from a pid-file.// w w w  .  ja va 2s. c o m
 * 
 * @param pidFileName
 *          Name of the pid-file.
 * @return the PID string read from the pid-file. Returns null if the
 *         pidFileName points to a non-existing file or if read fails from the
 *         file.
 */
public static String getPidFromPidFile(String pidFileName) {
    BufferedReader pidFile = null;
    FileReader fReader = null;
    String pid = null;

    try {
        fReader = new FileReader(pidFileName);
        pidFile = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        LOG.debug("PidFile doesn't exist : " + pidFileName);
        return pid;
    }

    try {
        pid = pidFile.readLine();
    } catch (IOException i) {
        LOG.error("Failed to read from " + pidFileName);
    } finally {
        try {
            if (fReader != null) {
                fReader.close();
            }
            try {
                if (pidFile != null) {
                    pidFile.close();
                }
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + pidFile);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }
    return pid;
}

From source file:com.enigmastation.ml.bayes.CorpusTest.java

private String readFile(File file) throws IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr, 16384);
    StringBuilder sb = new StringBuilder();
    String s;/*from   w ww  .j  a  v a  2  s.  co m*/
    while ((s = br.readLine()) != null) {
        sb.append(s);
    }
    br.close();
    fr.close();
    return sb.toString();
}

From source file:marytts.tools.voiceimport.PraatPitchmarker.java

/**
 * Convert Praat PointProcess files to EST pm files
 * //from w  w w  .j  a  v  a  2s. c o  m
 * @param basename of files to process
 * @throws IOException
 */
protected void estPitchmarks(String basename) throws IOException {
    String pointprocessFilename = getProp(PRAATPMDIR) + basename + pointpExt;
    String pmFilename = getProp(PRAATPMDIR) + basename + db.getProp(PMEXT);
    FileReader pmReader = new FileReader(pointprocessFilename);
    double[] pm = new PraatTextfileDoubleDataSource(pmReader).getAllData();
    pmReader.close();
    float[] pitchmarks = ArrayUtils.copyDouble2Float(pm);
    new ESTTrackWriter(pitchmarks, null, "pitchmarks").doWriteAndClose(pmFilename, false, false);
}