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.lternet.pasta.portal.Harvester.java

/**
 *  Reads character data from the <code>Reader</code> provided, using a 
 *  buffered read. Returns data as a <code>StringBufer</code>
 *
 *  @param  reader              <code>Reader</code> object to be read
 *
 *  @param  closeWhenFinished   <code>boolean</code> value to indicate 
 *                              whether Reader should be closed when reading
 *                              finished
 *
 *  @return                     <code>StringBuffer</code> containing  
 *                              characters read from the <code>Reader</code>
 *
 *  @throws IOException if there are problems accessing or using the Reader.
 *//*from w  ww .j  a v  a  2  s  .c om*/
public StringBuffer getAsStringBuffer(Reader reader, boolean closeWhenFinished) throws IOException {
    if (reader == null)
        return null;

    StringBuffer sb = new StringBuffer();

    try {
        char[] buff = new char[4096];
        int numCharsRead;

        while ((numCharsRead = reader.read(buff, 0, buff.length)) != -1) {
            sb.append(buff, 0, numCharsRead);
        }
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (closeWhenFinished) {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException ce) {
                ce.printStackTrace();
            }
        }
    }

    return sb;
}

From source file:com.joliciel.frenchTreebank.search.XmlPatternSearchImpl.java

public void setXmlPatternFile(String xmlPatternFile) {
    try {/*w ww .  j  a  v  a 2  s. co m*/
        StringBuffer fileData = new StringBuffer(1000);
        Reader reader = new UnicodeReader(new FileInputStream(xmlPatternFile), "UTF-8");

        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();

        xmlPattern = fileData.toString();
        LOG.debug(xmlPattern);
    } catch (FileNotFoundException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }

}

From source file:facebook4j.internal.http.HttpResponse.java

/**
 * Returns the response body as facebook4j.internal.org.json.JSONArray.<br>
 * Disconnects the internal HttpURLConnection silently.
 *
 * @return response body as facebook4j.internal.org.json.JSONArray
 * @throws FacebookException/*from   ww w . j  a  va2  s  .  co m*/
 */
public JSONArray asJSONArray() throws FacebookException {
    if (jsonArray == null) {
        Reader reader = null;
        try {
            if (responseAsString == null) {
                reader = asReader();
                jsonArray = new JSONArray(new JSONTokener(reader));
            } else {
                jsonArray = new JSONArray(responseAsString);
            }
            if (CONF.isPrettyDebugEnabled()) {
                logger.debug(jsonArray.toString(1));
            } else {
                logger.debug(responseAsString != null ? responseAsString : jsonArray.toString());
            }
        } catch (JSONException jsone) {
            if (logger.isDebugEnabled()) {
                throw new FacebookException(jsone.getMessage() + ":" + this.responseAsString, jsone);
            } else {
                throw new FacebookException(jsone.getMessage(), jsone);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignore) {
                }
            }
            disconnectForcibly();
        }
    }
    return jsonArray;
}

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

/**
 * Test a given feed modifier chain by its (feed) modifier ID.
 * // w w w  . ja  v  a2  s  .com
 * @param id
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @throws Exception
 * @return List<String, Boolean>
 */
public Map<String, Boolean> testModifier(Integer id, URI uri, String encodingOverride, String userAgent)
        throws Exception {
    WebResolverSettings settings = new WebResolverSettings();
    settings.setMaximumContentLength(maximumContentLength);
    settings.setUserAgent(userAgent);

    Map<String, Boolean> result = new HashMap<String, Boolean>();

    logger.info("Testing feed modifier with ID " + id + " and URI " + uri);

    try {
        Modifier modifier = modifierCache.getFeedModifierById(id);

        if (!Pattern.matches(modifier.getUrlExpression(), uri.toString()))
            throw new Exception("The given testing feed URI is not covered by the modifier expression");

        Reader reader = getContent(uri, encodingOverride, userAgent, null);

        if (reader != null) {
            // Run it through the modifier

            for (ModifierFilter filter : modifier.getFilters()) {
                StringBuffer current = new StringBuffer(), updated = new StringBuffer();

                reader = readerToBuffer(current, reader, false);
                reader = modifierFilterProcessor.process(filter, reader);
                reader = readerToBuffer(updated, reader, false);

                result.put("Filter_" + filter.getId(), !current.toString().equals(updated.toString()));

                reader.close();
            }

            for (ModifierScript script : modifier.getScripts()) {
                StringBuffer current = new StringBuffer(), updated = new StringBuffer();

                reader = readerToBuffer(current, reader, false);
                reader = modifierScriptProcessor.process(script, extractAndClose(reader), uri, settings, false);
                reader = readerToBuffer(updated, reader, false);

                result.put("Script_" + script.getId(), !current.toString().equals(updated.toString()));

                reader.close();
            }
        } else
            throw new Exception("Could not retrieve the result feed content");
    } catch (ScriptException e) {
        throw new Exception("Could not test the given feed: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new Exception("Could not test the given feed: " + e.getMessage(), e);
    }

    return result;
}

From source file:cn.vlabs.umt.common.mail.MessageFormatter.java

private String readTemplate(Locale locale, String templateName) throws TemplateNotFound {
    StringBuffer content = new StringBuffer();
    Reader reader = null;
    String templateFileDir = path;
    try {/* w  w w. ja  va  2 s.  co  m*/
        templateFileDir = path + "/" + locale.toString();
        File f = new File(templateFileDir);
        if (!f.exists()) {
            templateFileDir = path + "/en_US";
        }
        templateFileDir = templateFileDir + "/" + templateName;
        reader = new InputStreamReader(new FileInputStream(templateFileDir), "UTF-8");

        int num = 0;
        while ((num = reader.read(buff)) != -1) {
            content.append(buff, 0, num);
        }
    } catch (FileNotFoundException e) {
        throw new TemplateNotFound(templateFileDir);
    } catch (UnsupportedEncodingException e) {
        log.error("????");
        log.debug("?", e);
    } catch (IOException e) {
        log.error("????");
        log.debug("?", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.debug("??");
            }
        }
    }
    return content.toString();
}

From source file:com.intel.diceros.test.securerandom.DRNGTest.java

private List<Reader> getReaders(String... filenames) {
    String resource = RESOURCES_PREFIX.startsWith("/") ? RESOURCES_PREFIX.substring(1) : RESOURCES_PREFIX;
    Enumeration<URL> urls;
    List<Reader> readers = new ArrayList<Reader>();
    for (String filename : filenames) {
        try {/*from  w  w w. j  av a2 s  .  c om*/
            urls = getClass().getClassLoader().getResources(resource + filename);
        } catch (IOException e) {
            throw new RuntimeException("IOException while obtaining resource: " + resource + filename, e);
        }
        if (urls != null) {
            URL url = null;
            try {
                while (urls.hasMoreElements()) {
                    url = urls.nextElement();
                    InputStream stream = url.openStream();
                    readers.add(new InputStreamReader(stream));
                }
            } catch (IOException e) {
                for (Reader r : readers) {
                    try {
                        r.close();
                    } catch (IOException e1) {
                        // ignore
                    }
                }
                throw new RuntimeException("IOException while opening resource: " + url, e);
            }
        } else {
            throw new RuntimeException("Unable to find the resource: " + resource + filename);
        }
    }
    return readers;
}

From source file:com.ning.billing.recurly.RecurlyClient.java

private String buildUserAgent() {
    final String defaultVersion = "0.0.0";
    final String defaultJavaVersion = "0.0.0";

    try {/*w  ww. j  ava 2 s  . c o  m*/
        final Properties gitRepositoryState = new Properties();
        final URL resourceURL = Resources.getResource(GIT_PROPERTIES_FILE);
        final CharSource charSource = Resources.asCharSource(resourceURL, Charset.forName("UTF-8"));

        Reader reader = null;
        try {
            reader = charSource.openStream();
            gitRepositoryState.load(reader);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        final String version = Objects.firstNonNull(getVersionFromGitRepositoryState(gitRepositoryState),
                defaultVersion);
        final String javaVersion = Objects.firstNonNull(StandardSystemProperty.JAVA_VERSION.value(),
                defaultJavaVersion);
        return String.format("KillBill/%s; %s", version, javaVersion);
    } catch (final Exception e) {
        return String.format("KillBill/%s; %s", defaultVersion, defaultJavaVersion);
    }
}

From source file:CsvConverter.java

public CsvConverter(Reader in) {
    String line = "";
    boolean doHeader = true;
    StringTokenizer st = null;/*from ww w.j  av  a2 s.  c om*/

    try {
        BufferedReader br = new BufferedReader(in);

        while ((line = br.readLine()) != null) {
            if (line == null) {
                throw new IOException("Empty Data Source");
            }

            if (doHeader) {
                headers = breakCSVStringApart(line);
                doHeader = false;
            } else {
                String[] rowArray = breakCSVStringApart(line);

                if ((rowArray.length < headers.length) && (rowArray.length < 2)) {
                    //skip as blank row
                } else {
                    data.add(rowArray);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            ;
        }
    }
}

From source file:com.p000ison.dev.simpleclans2.updater.bamboo.BambooBuild.java

@Override
public void fetchInformation() throws IOException, FailedBuildException {
    Reader reader;
    JSONObject content;//from w w  w.  j a  v a  2  s.co m

    String latestBuild = updateType == UpdateType.LATEST ? String.format(LATEST_BUILD, job)
            : String.format(LATEST_BUILD_BY_LABEL, job, updateType.toString());
    try {
        reader = connect(latestBuild);
    } catch (FileNotFoundException e) {
        Logging.debug("No build found in this channel!");
        return;
    }
    content = parseJSON(reader);
    JSONObject results = (JSONObject) content.get("results");
    JSONArray result = (JSONArray) results.get("result");
    if (result.isEmpty()) {
        Logging.debug("No build found in this channel!");
        return;
    }

    JSONObject firstResult = (JSONObject) result.get(0);
    int buildNumberToFetch = ((Long) firstResult.get("number")).intValue();
    String state = (String) firstResult.get("state");
    if (!state.equalsIgnoreCase("Successful")) {
        throw new FailedBuildException("The last build failed!");
    }

    reader.close();
    reader = connect(String.format(API_FILE, job, buildNumberToFetch));
    content = parseJSON(reader);

    try {
        this.started = DATE_FORMATTER.parse((String) content.get("buildStartedTime")).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    this.duration = (Long) content.get("buildDuration");

    this.buildNumber = ((Long) content.get("number")).intValue();
    this.commitId = (String) content.get("vcsRevisionKey");

    JSONArray changes = (JSONArray) ((JSONObject) content.get("changes")).get("change");

    if (!changes.isEmpty()) {
        JSONObject change = (JSONObject) changes.get(0);
        pusher = (String) change.get("userName");
    }

    reader.close();
}

From source file:com.jakewharton.DiskLruCacheTest.java

private String readFile(File file) throws Exception {
    Reader reader = new FileReader(file);
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;/*from w  w  w . j av a2  s  . c o  m*/
    while ((count = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, count);
    }
    reader.close();
    return writer.toString();
}