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:net.hamnaberg.json.parser.CollectionParser.java

public Template parseTemplate(Reader reader) throws IOException {
    try {//from ww w .  ja v  a2s. co  m
        return parseTemplate(mapper.readTree(reader));
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:fr.opensagres.odfdom.converter.core.utils.IOUtils.java

/**
 * Unconditionally close an <code>Reader</code>.
 * <p>//from  w  ww.  j  av a 2  s.com
 * Equivalent to {@link Reader#close()}, except any exceptions will be ignored. This is typically used in finally
 * blocks.
 * 
 * @param input the Reader to close, may be null or already closed
 */
public static void closeQuietly(Reader input) {
    try {
        if (input != null) {
            input.close();
        }
    } catch (IOException ioe) {
        //logger.warning( "Reader - exception ignored - exception: " + ioe ); //$NON-NLS-1$

        // ignore
    }
}

From source file:com.seajas.search.contender.service.modifier.ModifierFilterProcessor.java

/**
 * Process the given reader using this filter.
 * /*w ww .  j  a v a2 s .c om*/
 * @param filter
 * @param reader
 * @return Reader
 * @throws IOException
 */
public Reader process(final ModifierFilter filter, final Reader reader) throws IOException {
    StringBuffer stringBuffer = new StringBuffer();

    for (int c; (c = reader.read()) != -1;)
        stringBuffer.append((char) c);

    reader.close();

    if (!filter.getIsExpression()) {
        Pattern pattern = Pattern.compile(
                Pattern.quote(filter.getFragmentStart()) + ".*" + Pattern.quote(filter.getFragmentEnd()),
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE);

        return new StringReader(
                pattern.matcher(stringBuffer).replaceAll(filter.getFragmentStart() + filter.getFragmentEnd()));
    } else {
        Matcher startMatcher = Pattern.compile(filter.getFragmentStart(), Pattern.CASE_INSENSITIVE)
                .matcher(stringBuffer),
                endMatcher = Pattern.compile(filter.getFragmentEnd(), Pattern.CASE_INSENSITIVE)
                        .matcher(stringBuffer);

        while (startMatcher.find() && endMatcher.find(startMatcher.end()))
            if (startMatcher.end() != endMatcher.start()) {
                stringBuffer.delete(startMatcher.end(), endMatcher.start());

                startMatcher.reset();
                endMatcher.reset();
            }

        // Store the result

        return new StringReader(stringBuffer.toString());
    }
}

From source file:org.openscada.da.server.spring.tools.csv.CSVLoader.java

private void load() throws IOException {
    if (this.resource != null) {
        final Reader reader = new InputStreamReader(this.resource.getInputStream());
        load(reader, this.resource.toString());
        reader.close();
    }/*from  ww w.  j  ava  2 s .  c om*/
    if (this.data != null) {
        final Reader reader = new StringReader(this.data);
        load(reader, "inline data");
        reader.close();
    }
}

From source file:org.apache.ibatis.submitted.foreach.Issue67Test.java

private SqlSessionFactory pureMyBatisSetup() throws Exception {
    // create a SqlSessionFactory
    Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/foreach/mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    reader.close();

    // populate in-memory database
    SqlSession session = sqlSessionFactory.openSession();
    Connection conn = session.getConnection();
    reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/foreach/CreateDB.sql");
    ScriptRunner runner = new ScriptRunner(conn);
    runner.setLogWriter(null);/*from w  w  w  .j  a v  a 2s. c  om*/
    runner.runScript(reader);
    reader.close();
    session.close();

    return sqlSessionFactory;
}

From source file:com.feathercoin.wallet.feathercoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {// w w  w  .  j  a  va 2 s .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 String rate = o.optString("15m", null);

                if (rate != null)
                    rates.put(currencyCode,
                            new ExchangeRate(currencyCode, Utils.toNanoCoins(rate), 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:com.github.codingtogenomic.CodingToGenomic.java

private static String getContent(final String endpoint)
        throws MalformedURLException, IOException, InterruptedException {

    if (requestCount == 15) { // check every 15
        final long currentTime = System.currentTimeMillis();
        final long diff = currentTime - lastRequestTime;
        //if less than a second then sleep for the remainder of the second
        if (diff < 1000) {
            Thread.sleep(1000 - diff);
        }/*from  w  ww  . j a  va  2 s .c o  m*/
        //reset
        lastRequestTime = System.currentTimeMillis();
        requestCount = 0;
    }

    final URL url = new URL(SERVER + endpoint);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    httpConnection.setRequestProperty("Content-Type", "application/json");

    final InputStream response = httpConnection.getInputStream();
    int responseCode = httpConnection.getResponseCode();

    if (responseCode != 200) {
        if (responseCode == 429 && httpConnection.getHeaderField("Retry-After") != null) {
            double sleepFloatingPoint = Double.valueOf(httpConnection.getHeaderField("Retry-After"));
            double sleepMillis = 1000 * sleepFloatingPoint;
            Thread.sleep((long) sleepMillis);
            return getContent(endpoint);
        }
        throw new RuntimeException("Response code was not 200. Detected response was " + responseCode);
    }

    String output;
    Reader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[8192];
        int read;
        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
            builder.append(buffer, 0, read);
        }
        output = builder.toString();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException logOrIgnore) {
                logOrIgnore.printStackTrace();
            }
        }
    }

    return output;
}

From source file:com.hexidec.ekit.component.ExtendedHTMLEditorKit.java

public StyleSheet getStyleSheet() {
    try {/* w  w w . j a  va 2 s. c o  m*/
        StyleSheet defaultStyles = new StyleSheet();
        InputStream is = getClass().getResourceAsStream("/ekit.css");
        Reader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));
        defaultStyles.loadRules(r, null);
        r.close();

        return defaultStyles;
    } catch (Throwable e) {
        log.error("Falha ao ler ekit.css. Utilizando estilos padro.", e);
        return super.getStyleSheet();
    }
}

From source file:jease.cmf.service.Backup.java

/**
 * Restore node-graph from file dump.//w  w  w. j av a2 s  .c om
 */
public Node restore(File dumpFile) {
    if (dumpFile == null) {
        return null;
    }
    try {
        Reader reader = Files.newBufferedReader(Zipfiles.unzip(dumpFile).toPath());
        Node node = fromXML(reader);
        node.setId(Filenames.asId(dumpFile.getName()).replace(".xml.zip", ""));
        reader.close();
        return node;
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

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

protected void populate(final @Nonnull String htmlResourceName, final @Nonnull Map<String, String> attributes)
        throws IOException {
    final Resource htmlResource = new ClassPathResource(htmlResourceName, getClass());
    final @Cleanup Reader r = new InputStreamReader(htmlResource.getInputStream());
    final CharBuffer charBuffer = CharBuffer.allocate((int) htmlResource.contentLength());
    final int length = r.read(charBuffer);
    r.close();
    final String html = new String(charBuffer.array(), 0, length);

    ST template = new ST(html, '$', '$');

    for (final Entry<String, String> entry : attributes.entrySet()) {
        template = template.add(entry.getKey(), entry.getValue());
    }//from w  w w  .  ja va 2  s .c  o  m

    view.setContent(template.render());
}