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:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {/*from w w w .j  a  v  a 2  s  .  c o  m*/
        Double btcRate = 0.0;

        Object result = getCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("https://blockchain.info/ticker");
        final HttpURLConnection connection = (HttpURLConnection) URL.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            //Add Bitcoin information
            rates.put(CoinDefinition.cryptsyMarketCurrency,
                    new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                            Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")),
                            "pubapi.cryptsy.com"));

            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 String rate = o.optString("15m", null);

                double rateForBTC = o.getDouble("15m") * btcRate;

                final String rate = String.format("%.8f", rateForBTC); //o.optString("15m", null);

                if (rate != null) {
                    try {
                        rates.put(currencyCode, new ExchangeRate(currencyCode,
                                Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
                    } catch (final ArithmeticException x) {
                        log.debug("problem reading exchange rate: " + currencyCode, x);
                    }
                }
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    }

    return null;
}

From source file:de.interactive_instruments.ShapeChange.BasicTest.java

private String readFile(String fileName) throws Exception {
    InputStream stream = new FileInputStream(new File(fileName));

    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    Reader reader = null;
    try {//from  w w w .  ja v  a 2s.co m
        reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        if (reader != null)
            reader.close();
    }
    return writer.toString();
}

From source file:au.gov.aims.atlasmapperserver.URLCache.java

private static JSONObject parseFile(File jsonFile, String urlStr) {
    JSONObject jsonResponse = null;//from  w ww  . j  a va 2s  .co  m
    Reader reader = null;
    try {
        reader = new FileReader(jsonFile);
        jsonResponse = new JSONObject(new JSONTokener(reader));
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Can not load the JSON Object returning from the URL {0}: {1}",
                new String[] { urlStr, Utils.getExceptionMessage(ex) });
        LOGGER.log(Level.FINE, "Stack trace:", ex);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "Can not close the JSON file {0}: {1}", new String[] {
                        jsonFile.getAbsoluteFile().getAbsolutePath(), Utils.getExceptionMessage(ex) });
                LOGGER.log(Level.FINE, "Stack trace:", ex);
            }
        }
    }

    return jsonResponse;
}

From source file:com.bt.aloha.testing.JdbcHelper.java

private String readContent(String filename) {
    Reader r = null;
    BufferedReader br = null;//  w  w  w  . ja  v a 2  s.co m
    InputStream is = null;
    try {
        is = JdbcHelper.class.getClassLoader().getResourceAsStream(filename);
        r = new InputStreamReader(is);
        br = new BufferedReader(r);
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            if (line.indexOf(SERIAL) != -1)
                sb.append(line.replaceAll(SERIAL, INT_IDENTITY));
            else
                sb.append(line);
        }
        String content = sb.toString();
        return content;
    } catch (Throwable e) {
        throw new IllegalArgumentException(String.format("Couldn't read content of create script %s", filename),
                e);
    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException e) {
            log.error(String.format(ERROR_CLOSING_S, br.getClass().getSimpleName()), e);
        }
        try {
            if (r != null)
                r.close();
        } catch (IOException e) {
            log.error(String.format(ERROR_CLOSING_S, r.getClass().getSimpleName()), e);
        }
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            log.error(String.format(ERROR_CLOSING_S, is.getClass().getSimpleName()), e);
        }
    }
}

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

private static Object getCoinValueBTC_cryptopia() {
    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;// www .jav a  2s  .  c om
    String currency = "BTC";
    String url = "https://www.cryptopia.co.nz/api/GetMarket/2623";

    try {
        // final String currencyCode = currencies[i];
        final URL URL_bter = new URL(url);
        final HttpURLConnection connection = (HttpURLConnection) URL_bter.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        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());

            /*{
               "Success":true,
                  "Message":null,
                  "Data":{
             "TradePairId":100,
             "Label":"LTC/BTC",
             "AskPrice":0.00006000,
             "BidPrice":0.02000000,
             "Low":0.00006000,
             "High":0.00006000,
             "Volume":1000.05639978,
             "LastPrice":0.00006000,
             "LastVolume":499.99640000,
             "BuyVolume":67003436.37658233,
             "SellVolume":67003436.37658233,
             "Change":-400.00000000
                  }
            }*/
            String result = head.getString("Success");
            if (result.equals("true")) {
                JSONObject dataObject = head.getJSONObject("Data");

                Double averageTrade = Double.valueOf(0.0);
                if (dataObject.get("Label").equals("GLD/BTC"))
                    averageTrade = dataObject.getDouble("LastPrice");

                if (currency.equalsIgnoreCase("BTC"))
                    btcRate = averageTrade;
            }
            return btcRate;
        } finally {
            if (reader != null)
                reader.close();
        }

    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:gate.corpora.FastInfosetDocumentFormat.java

/**
 * Unpacks markup in the GATE-specific standoff XML markup format.
 * // w  w  w  . j  av  a  2  s  .  co  m
 * @param doc
 *          the document to process
 * @param statusListener
 *          optional status listener to receive status messages
 * @throws DocumentFormatException
 *           if a fatal error occurs during parsing
 */
private void unpackGateFormatMarkup(Document doc, StatusListener statusListener)
        throws DocumentFormatException {
    boolean docHasContentButNoValidURL = hasContentButNoValidUrl(doc);

    try {
        Reader inputReader = null;
        InputStream inputStream = null;
        XMLStreamReader xsr = null;
        String encoding = ((TextualDocument) doc).getEncoding();
        if (docHasContentButNoValidURL) {
            xsr = new StAXDocumentParser(IOUtils.toInputStream(doc.getContent().toString(), encoding),
                    getStAXManager());
        } else {
            inputStream = doc.getSourceUrl().openStream();
            xsr = new StAXDocumentParser(inputStream, getStAXManager());
        }

        // find the opening GateDocument tag
        xsr.nextTag();

        // parse the document
        try {
            DocumentStaxUtils.readGateXmlDocument(xsr, doc, statusListener);
        } finally {
            xsr.close();
            if (inputStream != null) {
                inputStream.close();
            }
            if (inputReader != null) {
                inputReader.close();
            }
        }
    } catch (XMLStreamException e) {
        doc.getFeatures().put("parsingError", Boolean.TRUE);

        Boolean bThrow = (Boolean) doc.getFeatures().get(GateConstants.THROWEX_FORMAT_PROPERTY_NAME);

        if (bThrow != null && bThrow.booleanValue()) {
            // the next line is commented to avoid Document creation fail on
            // error
            throw new DocumentFormatException(e);
        } else {
            Out.println("Warning: Document remains unparsed. \n" + "\n  Stack Dump: ");
            e.printStackTrace(Out.getPrintWriter());
        } // if
    } catch (IOException ioe) {
        throw new DocumentFormatException("I/O exception for " + doc.getSourceUrl().toString(), ioe);
    }
}

From source file:gov.nih.nci.cabig.caaers.dataimport.AgentSpecificTermsImporter.java

public Map<String, Object> importFile() throws Exception {

    POIFSFileSystem poifs;/*from w w  w  .  j av a2  s  .c  o  m*/
    HSSFWorkbook wb;
    HSSFSheet sh = null;

    boolean isExcel = file.getName().endsWith(".xls");
    boolean isCSV = file.getName().endsWith(".csv");

    Map<String, Object> results = new HashMap<String, Object>();
    int rowCount = 0;
    int columnsCount = 0;
    Map<String, Agent> agents = new HashMap<String, Agent>();
    Map<String, Agent> missingAgents = new HashMap<String, Agent>();
    Set<String> missingTerms = new HashSet<String>();
    Map<String, String> asaelCache = new HashMap<String, String>();
    int asael;

    // wipe out the table
    agentSpecificTermDao.deleteAll();
    studyDao.deleteAllExpectedTerms();
    // if (true) return null;

    // get needed headers
    if (isExcel) {
        poifs = new POIFSFileSystem(new FileInputStream(file));
        wb = new HSSFWorkbook(poifs);
        sh = wb.getSheetAt(0);
        rowCount = sh.getLastRowNum();
        columnsCount = sh.getRow(0).getLastCellNum();

        for (byte i = 0; i < columnsCount; i++) {
            HSSFCell cell = sh.getRow(0).getCell(i);
            if (headers.containsKey(cell.getStringCellValue())) {
                headers.remove(cell.getStringCellValue());
                headers.put(cell.getStringCellValue(), Short.valueOf(i));
            }
        }
    }

    InputStream ir = null;
    Reader r = null;
    BufferedReader br = null;

    if (isCSV) {
        // readLines
        rowCount = 0;
        ir = new FileInputStream(file);
        r = new InputStreamReader(ir);
        br = new BufferedReader(r);
        String s = br.readLine();
        while (s != null) {
            if (rowCount == 0) {
                String[] _s = s.split("[\\|]{1}");
                for (byte j = 0; j < _s.length; j++) {
                    // System.out.println(_s[j]);
                    if (headers.containsKey(_s[j])) {
                        headers.remove(_s[j]);
                        headers.put(_s[j], Short.valueOf(j));
                    }
                }
            }
            rowCount++;
            s = br.readLine();
        }
        br.close();
        r.close();
        ir.close();

        ir = new FileInputStream(file);
        r = new InputStreamReader(ir);
        br = new BufferedReader(r);
    }

    /*
            System.out.println(rowCount);
            for (Map.Entry e : headers.entrySet()) {
    System.out.println(e.getKey() + "=>" + e.getValue());
            }
    */

    agents.clear();
    missingTerms.clear();
    missingAgents.clear();
    asael = 0;
    int duplicateAgentTerms = 0;

    //
    String nsc = "";
    String ctcae_category = "";
    String ctcae_version = "0.0";
    String ae_term = "";
    String other_toxicity = "";

    // Loading ASAE list
    // if (true) {  return null; }

    int i = 1;
    while (i <= rowCount) {

        nsc = "";

        if (isExcel) {
            HSSFRow row = sh.getRow(i);
            if (row != null) {
                nsc = getCellData("", i, row.getCell((short) headers.get("NSC")));
                ctcae_category = getCellData("", i, row.getCell((short) headers.get("CTCAE_CATEGORY")));
                ctcae_version = getCellData("", i, row.getCell((short) headers.get("CTCAE_VERSION")));
                ae_term = getCellData("", i, row.getCell((short) headers.get("AE_TERM")));
                other_toxicity = getCellData("", i, row.getCell((short) headers.get("OTHER_TOXICITY")));
            }
        } else {
            String s;
            s = br.readLine();
            if (s != null) {
                String[] _s = s.split("[\\|]{1}");
                if (i > 1 && _s.length > 1) {
                    nsc = _s[headers.get("NSC")];
                    ctcae_category = _s[headers.get("CTCAE_CATEGORY")];
                    try {
                        ctcae_version = _s[headers.get("CTCAE_VERSION")].trim();
                    } catch (NumberFormatException e) {
                        //                                System.out.println(s);
                        return null;
                    }
                    ae_term = _s[headers.get("AE_TERM")];
                    if (_s.length - 1 >= headers.get("OTHER_TOXICITY"))
                        other_toxicity = _s[headers.get("OTHER_TOXICITY")];
                    else
                        other_toxicity = "";
                }
            }
        }

        if (nsc.trim().equals("")) {
            i++;
            continue;
        } else {
            // System.out.println(String.format("%s). NSC:%s,   V:%s,   C:%s,   T:%s", i, nsc, ctcae_version, ctcae_category, ae_term));
        }

        Agent a = agents.get(nsc);
        if (a == null) {
            a = agentDao.getByNscNumber(nsc);
            // System.out.println(asael + ". OK. Found agent [" + a.getName() + "] for NSC: [" + nsc + "]");
            agents.put(nsc, a);
        }

        if (a != null) {
            AgentSpecificCtcTerm t = new AgentSpecificCtcTerm();
            t.setAgent(a);
            t.setOtherToxicity(other_toxicity);

            List<CtcTerm> list = terminologyRepository.getCtcTerm(ctcae_category, ctcae_version, ae_term);
            if (list.size() == 0) {
                // System.out.println("<ERROR>: Term not found: " + ae_term + ", Category: " + ctcae_category + ", CTCAE Version: " + ctcae_version);
                missingTerms.add("Term not found: " + ae_term + ", Category: " + ctcae_category
                        + ", CTCAE Version: " + ctcae_version);
            } else {
                t.setCtcTerm(list.get(0));
                if (persistASAE(t))
                    asael++;
                else
                    duplicateAgentTerms++;
            }

            agentSpecificTermDao.evict(t);

        } else {
            if (!missingAgents.containsKey(nsc)) {
                // System.out.println("<ERROR>: The agent was not found by its NSC: " + nsc);
                missingAgents.put(nsc, null);
            }
        }

        i++;
    }

    if (isCSV) {
        br.close();
        r.close();
        ir.close();
    }

    results.put(KEY_MISSING_TERMS, missingTerms);
    results.put(KEY_PROCESSED_AGENTS, agents.size() - missingAgents.size());
    results.put(KEY_PROCESSED_AGENTTERMS, asael);
    results.put(KEY_MISSING_AGENTS, missingAgents);
    results.put(KEY_DUPLICATE_AGENT_TERMS, duplicateAgentTerms);

    return results;
}

From source file:AIR.Common.xml.XmlReader.java

public XmlReader(Reader file) throws IOException, JDOMException {
    // Start hack! Shiva: I am not sure why this is happening. but this happened
    // with the earlier .NET code as well.
    // why am I seeing a special character if I directly pass a
    // InputStreamReader to SAXBuilder. I had to do the same hack in
    // ItemScoringHandler.ProcessRequest.
    // I see this message as well
    // "warning: line 6050: incompatible stripping characters and condition"
    // Further information: Elena found two additional links:
    // http://mark.koli.ch/resolving-orgxmlsaxsaxparseexception-content-is-not-allowed-in-prolog
    // and/*from  ww  w .  j  a v a 2 s  . c  om*/
    // http://stackoverflow.com/questions/5138696/org-xml-sax-saxparseexception-content-is-not-allowed-in-prolog
    BufferedReader bfr = new BufferedReader(file);
    StringBuilder strinBuilder = new StringBuilder();
    String line = "";
    while ((line = bfr.readLine()) != null)
        strinBuilder.append(line);
    file.close();
    String fileContent = strinBuilder.toString();
    int indexOfBegin = fileContent.indexOf('<');
    if (indexOfBegin > 0)
        fileContent = fileContent.substring(indexOfBegin);
    file = new StringReader(fileContent);
    // End hack!
    buildDocument(file);
}

From source file:com.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java

public void exportSearchPdf(OutputStream outputStream) throws FOPException, IOException, TransformerException {

    setupSearchForm();/*from   www . j a va2 s. c o m*/

    loadObjects();

    setupTableForm4ExportAll(Mode.VIEW);

    FopFactory fopFactory = FopFactory.newInstance();
    // hongliangpan add
    try {
        String fopConfig = "fop.xml";
        String filePath = CrudAction4ItsProject.class.getClassLoader().getResource(fopConfig).getPath();
        fopFactory.setUserConfig(filePath);
        // String fonts = "/fonts"; 
        fopFactory.setFontBaseURL(new File(filePath).getParent());
    } catch (SAXException e) {
        logger.error(e.getMessage(), e);
    }
    InputStream xsltStream = null;
    try {
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputStream);

        xsltStream = getSearchPdfXsltStream();

        // Setup XSLT
        TransformerFactory Factory = TransformerFactory.newInstance();
        Transformer transformer = Factory.newTransformer(new StreamSource(xsltStream));

        // Set the value of a <param> in the stylesheet
        transformer.setParameter("versionParam", "2.0");

        // Setup input for XSLT transformation
        Reader reader = composeXmlSearch();
        Source src = new StreamSource(reader);

        // Resulting SAX events (the generated FO) must be piped through to
        // FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
        reader.close();

        outputStream.flush();
    } finally {
        IOUtils.closeQuietly(xsltStream);
    }
}

From source file:com.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java

public void exportReadPdf(File tempPdfFile) throws FOPException, IOException, TransformerException {
    setupSearchForm();//from w  w w  .  j a v a  2 s  .c  o  m

    loadObjects();

    setupTableForm(Mode.VIEW);

    FopFactory fopFactory = FopFactory.newInstance();

    FileOutputStream out = null;
    InputStream xsltStream = null;
    try {
        out = new FileOutputStream(tempPdfFile);

        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

        xsltStream = getXsltStream(TEMPLATE_FOP_READ);

        // Setup XSLT
        TransformerFactory Factory = TransformerFactory.newInstance();
        Transformer transformer = Factory.newTransformer(new StreamSource(xsltStream));

        // Set the value of a <param> in the stylesheet
        transformer.setParameter("versionParam", "2.0");

        // Setup input for XSLT transformation
        Reader reader = composeXmlPort();
        Source src = new StreamSource(reader);

        // Resulting SAX events (the generated FO) must be piped through to
        // FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);

        reader.close();
        out.flush();
    } catch (Exception e) {
        logger.warn("IOException", e);
        SessionMessages.addErrorMessage(e.getMessage());
    } finally {
        IOUtils.closeQuietly(xsltStream);
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            logger.warn("IOException", e);
            SessionMessages.addErrorMessage(e.getMessage());
        }
    }
}