Example usage for java.io Reader close

List of usage examples for java.io Reader close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.i18n.VitroResourceBundle.java

private void loadProperties() throws IOException {
    String resourceName = control.toResourceName(bundleName, "properties");

    String defaultsPath = joinPath(appI18nPath, resourceName);
    String propertiesPath = joinPath(themeI18nPath, resourceName);
    File defaultsFile = locateFile(defaultsPath);
    File propertiesFile = locateFile(propertiesPath);

    if ((defaultsFile == null) && (propertiesFile == null)) {
        throw new FileNotFoundException(
                "Property file not found at '" + defaultsPath + "' or '" + propertiesPath + "'");
    }/*from  w  w  w  .j av  a 2  s.c  om*/

    if (defaultsFile != null) {
        log.debug("Loading bundle '" + bundleName + "' defaults from '" + defaultsPath + "'");
        FileInputStream stream = new FileInputStream(defaultsFile);
        Reader reader = new InputStreamReader(stream, "UTF-8");
        try {
            this.defaults.load(reader);
        } finally {
            reader.close();
        }
    }
    if (propertiesFile != null) {
        log.debug("Loading bundle '" + bundleName + "' overrides from '" + propertiesPath + "'");
        FileInputStream stream = new FileInputStream(propertiesFile);
        Reader reader = new InputStreamReader(stream, "UTF-8");
        try {
            this.properties.load(reader);
        } finally {
            reader.close();
        }
    }
}

From source file:com.fbartnitzek.tasteemall.data.csv.CsvFileReader.java

/**
 * reads CSV file in data and headers with same count, uses CSV_Format RFC4180 (, and "")
 * @param file file to read//from  w  w w.  j av  a2  s  . c o  m
 * @param headers expected columns
 * @return data
 */
public static List<List<String>> readCsvFileHeadingAndData(File file, List<String> headers) {

    List<List<String>> data = new ArrayList<>();

    CSVParser csvParser = null;
    Reader csvReader = null;
    try {
        csvReader = new FileReader(file);
        csvParser = new CSVParser(csvReader, CsvFileWriter.CSV_FORMAT_RFC4180.withHeader());
        Map<String, Integer> headerMap = csvParser.getHeaderMap();

        // print headerMap
        for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
            System.out.println(entry.getValue() + ": " + entry.getKey());
        }

        // should be same order!

        // 0 columns seems impossible, but valid

        // ordered columns instead unordered set (for insert)!
        headers.addAll(headerMap.keySet());
        for (CSVRecord record : csvParser) {
            List<String> dataEntry = new ArrayList<>();
            for (int i = 0; i < headers.size(); ++i) {
                if (i < record.size()) {
                    dataEntry.add(record.get(i));
                }
                //                    dataEntry.add(record.get(headers.get(i)));
            }
            data.add(dataEntry);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (csvReader != null) {
                csvReader.close();
            }
            if (csvParser != null) {
                csvParser.close();
            }
        } catch (IOException e) {
            //                System.out.println("Error while closing fileReader/csvFileParser !!!");
            e.printStackTrace();
        }
    }

    return data;
}

From source file:de.hstsoft.sdeep.Configuration.java

public void load() throws IOException, ParseException {

    Reader reader = new BufferedReader(new FileReader(configFile));
    JSONParser jsonParser = new JSONParser();
    JSONObject json = (JSONObject) jsonParser.parse(reader);
    saveGamePath = json.get(PREF_SAVEGAME_PATH).toString();
    autorefresh = Boolean.parseBoolean(json.get(PREF_AUTOREFRESH).toString());
    reader.close();
}

From source file:org.callimachusproject.xml.XdmNodeFactory.java

public XdmNode parse(String systemId, Reader in) throws SAXException, IOException {
    if (in == null)
        return null;
    try {//from  ww w  .j av  a2  s  . co m
        InputSource source = new InputSource(in);
        source.setSystemId(systemId);
        return parse(source);
    } finally {
        in.close();
    }
}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {//from   w  w w  . ja v  a2s . c  o  m
        final URL URL = new URL("https://blockchain.info/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                final Double drate = o.getDouble("15m") * LycBtcRate;
                String rate = String.format("%.8f", drate);
                rate = rate.replace(",", ".");
                if (rate != null)
                    rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate),
                            "cryptsy.com and " + URL.getHost()));
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:de.schildbach.wallet.marscoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getmarscoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;//  w  ww .j a va 2 s  .c om
    try {
        String currencies[] = { "BTC" };
        //String urls[] = {"https://cryptorush.in/api.php?get=market&m=mrs&b=btc&json=true"};
        String urls[] = { "http://hlds.ws/marscoinj/api" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                //JSONObject ticker = head.getJSONObject("ticker");
                //rate = Float.parseFloat(head.getString("current_ask"));
                Double avg = head.getDouble("current_ask");
                //Double avg = Float.parseFloat(head.getString("current_ask"));
                String euros = String.format("%.8f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode,
                        new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
                if (currencyCode.equalsIgnoreCase("BTC"))
                    btcRate = avg;
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        // Handle LTC/EUR special since we have to do maths
        final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want MRS!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:org.openmrs.module.logmanager.web.controller.ConfigController.java

/**
 * Handles an import configuration request
 * @param request the http request/*from  w  ww  . ja  va  2s. com*/
 */
private void importConfiguration(HttpServletRequest request) {
    if (request instanceof MultipartHttpServletRequest) {
        // Spring will have detected a multipart request and wrapped it
        MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
        MultipartFile importFile = mpRequest.getFile("importFile");

        // Check file exists and isn't empty
        if (importFile == null || importFile.isEmpty()) {
            log.error("Uploaded file is empty or invalid");
            return;
        }

        String filename = importFile.getOriginalFilename();

        // Check for xml extension
        if (!filename.toLowerCase().endsWith(".xml")) {
            WebUtils.setErrorMessage(request, Constants.MODULE_ID + ".error.invalidConfigurationFile",
                    new Object[] { filename });
            return;
        }

        // Parse as an XML configuration
        try {
            LogManagerService svc = Context.getService(LogManagerService.class);
            Reader reader = new InputStreamReader(importFile.getInputStream());
            Document document = LogManagerUtils.readDocument(reader, new Log4jEntityResolver());
            reader.close();

            StringWriter str = new StringWriter();
            LogManagerUtils.writeDocument(document, str);

            log.warn(str.toString());

            if (document != null) {
                svc.loadConfiguration(document);

                WebUtils.setInfoMessage(request, Constants.MODULE_ID + ".config.importSuccess",
                        new Object[] { filename });
            } else
                WebUtils.setErrorMessage(request, Constants.MODULE_ID + ".error.invalidConfigurationFile",
                        new Object[] { filename });
        } catch (IOException e) {
            log.error(e);
        }
    }
}

From source file:com.streamsets.datacollector.util.TestConfiguration.java

@Test
public void testIncludes() throws Exception {
    File dir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(dir.mkdirs());/*from  w  ww.j a  va  2  s  .c o m*/
    Configuration.setFileRefsBaseDir(dir);

    Writer writer = new FileWriter(new File(dir, "config.properties"));
    IOUtils.write("a=A\nconfig.includes=include1.properties , ", writer);
    writer.close();

    writer = new FileWriter(new File(dir, "include1.properties"));
    IOUtils.write("b=B\nconfig.includes=include2.properties , ", writer);
    writer.close();

    writer = new FileWriter(new File(dir, "include2.properties"));
    IOUtils.write("c=C\n", writer);
    writer.close();

    Configuration conf = new Configuration();
    Reader reader = new FileReader(new File(dir, "config.properties"));
    conf.load(reader);
    reader.close();

    Assert.assertEquals("A", conf.get("a", null));
    Assert.assertEquals("B", conf.get("b", null));
    Assert.assertEquals("C", conf.get("c", null));
    Assert.assertNull(conf.get(Configuration.CONFIG_INCLUDES, null));
}

From source file:it.tidalwave.northernwind.frontend.ui.component.htmltemplate.TextHolder.java

private void loadTemplate() throws IOException {
    // FIXME: this should be done only once...
    Resource resource = null;/*ww  w .  j a va2 s  .c  o m*/

    for (Class<?> clazz = getClass(); clazz.getSuperclass() != null; clazz = clazz.getSuperclass()) {
        final String templateName = clazz.getSimpleName() + ".txt";
        resource = new ClassPathResource(templateName, clazz);

        if (resource.exists()) {
            break;
        }
    }

    try {
        if (resource == null) {
            throw new FileNotFoundException();
        }

        final @Cleanup Reader r = new InputStreamReader(resource.getInputStream());
        final CharBuffer charBuffer = CharBuffer.allocate((int) resource.contentLength());
        final int length = r.read(charBuffer);
        r.close();
        template = new String(charBuffer.array(), 0, length);
    } catch (FileNotFoundException e) // no specific template, fallback
    {
        log.warn("No template for {}, using default", getClass().getSimpleName());
        template = "$content$\n";
    }
}

From source file:com.streamsets.datacollector.util.TestConfiguration.java

@Test
public void testFileRefs() throws IOException {
    File dir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(dir.mkdirs());/*from w  ww. ja  v a2s . c om*/
    Configuration.setFileRefsBaseDir(dir);

    Writer writer = new FileWriter(new File(dir, "hello.txt"));
    IOUtils.write("secret\nfoo\n", writer);
    writer.close();
    Configuration conf = new Configuration();

    conf.set("a", "@hello.txt@");
    Assert.assertEquals("secret\nfoo\n", conf.get("a", null));

    conf.set("aa", "${file(\"hello.txt\")}");
    Assert.assertEquals("secret\nfoo\n", conf.get("aa", null));

    conf.set("aaa", "${file('hello.txt')}");
    Assert.assertEquals("secret\nfoo\n", conf.get("aaa", null));

    writer = new FileWriter(new File(dir, "config.properties"));
    conf.save(writer);
    writer.close();

    conf = new Configuration();
    Reader reader = new FileReader(new File(dir, "config.properties"));
    conf.load(reader);
    reader.close();

    Assert.assertEquals("secret\nfoo\n", conf.get("a", null));

    reader = new FileReader(new File(dir, "config.properties"));
    StringWriter stringWriter = new StringWriter();
    IOUtils.copy(reader, stringWriter);
    reader.close();
    Assert.assertTrue(stringWriter.toString().contains("@hello.txt@"));
    Assert.assertTrue(stringWriter.toString().contains("${file(\"hello.txt\")}"));
    Assert.assertTrue(stringWriter.toString().contains("${file('hello.txt')}"));
    Assert.assertFalse(stringWriter.toString().contains("secret\nfoo\n"));
}