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:com.googlecode.fascinator.common.PythonUtils.java

/*****
 * Parse RDF data from an inputstream/*w  w  w  .  ja va  2 s.  c  om*/
 * 
 * @param rdfIn, the inputstream to read and parse
 * @return Model object after parsing
 */
public Model getRdfModel(InputStream rdfIn) {
    Model model = null;
    Reader reader = null;
    try {
        reader = new InputStreamReader(rdfIn, "UTF-8");
        model = new ModelImplJena24(Reasoning.rdfs);
        model.open();
        model.readFrom(reader);
    } catch (ModelRuntimeException mre) {
        log.error("Failed to create RDF model", mre);
    } catch (IOException ioe) {
        log.error("Failed to read RDF input", ioe);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
            }
        }
    }
    return model;
}

From source file:com.aurel.track.lucene.index.associatedFields.textExctractor.RTFExtractor.java

/**
 * Gets the text from file content //from w  w  w . j a va 2  s . c  o m
 * @param file
 * @param fileExtension
 * @return
 */
@Override
public String getText(File file, String fileExtension) {
    FileInputStream fis = null;
    Reader reader = null;
    try {
        DefaultStyledDocument dsd = new DefaultStyledDocument();
        RTFEditorKit rtfEditorKit = new RTFEditorKit();

        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            LOGGER.info("File " + file.getName() + " not found. " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(fis));
        rtfEditorKit.read(reader, dsd, 0);
        return dsd.getText(0, dsd.getLength());
    } catch (Exception e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(
                    "Extracting text from the .rtf  file " + file.getName() + " failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        return null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                LOGGER.debug(
                        "Closing the reader for file " + file.getName() + "  failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                LOGGER.debug("Closing the FileInputStream for file " + file.getName() + " failed with "
                        + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

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

private static void loadDiskCacheMap(File applicationFolder) throws IOException, JSONException {
    File configFile = FileFinder.getDiskCacheFile(applicationFolder);

    Reader reader = null;
    try {/*from  w  ww  .  j av a 2 s .co  m*/
        reader = new FileReader(configFile);
        diskCacheMap = new JSONObject(new JSONTokener(reader));
    } catch (Exception ex) {
        diskCacheMap = new JSONObject();
        LOGGER.log(Level.SEVERE, "Can not load the cache map. The cache has been reset.");
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "Can not close the cache map reader: {0}",
                        Utils.getExceptionMessage(ex));
                LOGGER.log(Level.FINE, "Stack trace:", ex);
            }
        }
    }

    loadedTime = new Date().getTime();
    purgeCache(applicationFolder);
}

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

private static Object getCoinValueBTC() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;/*  w w w .  ja  v a2  s .  c o  m*/
    String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency;
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid="
            + CoinDefinition.cryptsyMarketId;

    HttpURLConnection connectionCryptsy = null;
    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        connectionCryptsy = (HttpURLConnection) URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            Io.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());
            JSONObject returnObject = head.getJSONObject("return");
            JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker);

            JSONArray recenttrades = coinInfo.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double coinTraded = 0.0;

            for (int i = 0; i < recenttrades.length(); ++i) {
                JSONObject trade = (JSONObject) recenttrades.get(i);

                btcTraded += trade.getDouble("total");
                coinTraded += trade.getDouble("quantity");

            }

            Double averageTrade = btcTraded / coinTraded;

            //Double lastTrade = GLD.getDouble("lasttradeprice");

            //String euros = String.format("%.7f", averageTrade);
            // Fix things like 3,1250
            //euros = euros.replace(",", ".");
            //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost()));
            if (currencyCryptsy.equalsIgnoreCase("BTC"))
                btcRate = averageTrade;

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException x) {
                    // swallow
                }
            }
        }
        return btcRate;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    } finally {
        if (connectionCryptsy != null)
            connectionCryptsy.disconnect();
    }

    return null;
}

From source file:com.cloudera.oryx.als.serving.ServerRecommender.java

@Override
public void ingest(File file) throws IOException {
    Reader reader = null;
    try {/*  w w  w .j av  a 2  s .  c  om*/
        reader = IOUtils.openReaderMaybeDecompressing(file);
        ingest(reader);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.syncope.core.workflow.ActivitiUserWorkflowAdapter.java

@Override
public WorkflowDefinitionTO getDefinition() throws WorkflowException {

    ProcessDefinition procDef;//from w w w .j ava2s. c om
    try {
        procDef = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(ActivitiUserWorkflowAdapter.WF_PROCESS_ID).latestVersion().singleResult();
    } catch (ActivitiException e) {
        throw new WorkflowException(e);
    }

    InputStream procDefIS = repositoryService.getResourceAsStream(procDef.getDeploymentId(),
            WF_PROCESS_RESOURCE);
    Reader reader = null;
    Writer writer = new StringWriter();
    try {
        reader = new BufferedReader(new InputStreamReader(procDefIS));

        int n;
        char[] buffer = new char[1024];
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (IOException e) {
        LOG.error("While reading workflow definition {}", procDef.getKey(), e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (procDefIS != null) {
                procDefIS.close();
            }
        } catch (IOException ioe) {
            LOG.error("While closing input stream for {}", procDef.getKey(), ioe);
        }
    }

    WorkflowDefinitionTO definitionTO = new WorkflowDefinitionTO();
    definitionTO.setId(ActivitiUserWorkflowAdapter.WF_PROCESS_ID);
    definitionTO.setXmlDefinition(writer.toString());

    return definitionTO;
}

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

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

From source file:com.googlecode.psiprobe.Utils.java

public static String getJSPEncoding(InputStream is) throws IOException {

    String encoding = null;//from  ww  w.j a  v a 2  s . c o  m
    String contentType = null;

    Tokenizer jspTokenizer = new Tokenizer();
    jspTokenizer.addSymbol("\n", true);
    jspTokenizer.addSymbol(" ", true);
    jspTokenizer.addSymbol("\t", true);
    jspTokenizer.addSymbol(new TokenizerSymbol("dir", "<%@", "%>", false, false, true, false));

    StringTokenizer directiveTokenizer = new StringTokenizer();
    directiveTokenizer.addSymbol("\n", true);
    directiveTokenizer.addSymbol(" ", true);
    directiveTokenizer.addSymbol("\t", true);
    directiveTokenizer.addSymbol("=");
    directiveTokenizer.addSymbol("\"", "\"", false);
    directiveTokenizer.addSymbol("'", "'", false);

    StringTokenizer contentTypeTokenizer = new StringTokenizer();
    contentTypeTokenizer.addSymbol(" ", true);
    contentTypeTokenizer.addSymbol(";", true);

    Reader reader = new InputStreamReader(is, "ISO-8859-1");
    try {
        jspTokenizer.setReader(reader);
        while (jspTokenizer.hasMore()) {
            Token token = jspTokenizer.nextToken();
            if ("dir".equals(token.getName())) {
                directiveTokenizer.setString(token.getInnerText());
                if (directiveTokenizer.hasMore() && directiveTokenizer.nextToken().getText().equals("page")) {
                    while (directiveTokenizer.hasMore()) {
                        Token dTk = directiveTokenizer.nextToken();
                        if ("pageEncoding".equals(dTk.getText())) {
                            if (directiveTokenizer.hasMore()
                                    && "=".equals(directiveTokenizer.nextToken().getText())) {
                                if (directiveTokenizer.hasMore()) {
                                    encoding = directiveTokenizer.nextToken().getInnerText();
                                    break;
                                }
                            }
                        } else if ("contentType".equals(dTk.getText())) {
                            if (directiveTokenizer.hasMore()
                                    && "=".equals(directiveTokenizer.nextToken().getText())) {
                                if (directiveTokenizer.hasMore()) {
                                    contentType = directiveTokenizer.nextToken().getInnerText();
                                }
                            }
                        }
                    }
                }
            }
        }
    } finally {
        reader.close();
    }

    if (encoding == null && contentType != null) {
        contentTypeTokenizer.setString(contentType);
        while (contentTypeTokenizer.hasMore()) {
            String token = contentTypeTokenizer.nextToken().getText();
            if (token.startsWith("charset=")) {
                encoding = token.substring("charset=".length());
                break;
            }
        }
    }

    return encoding != null ? encoding : "ISO-8859-1";
}

From source file:me.xiaopan.android.gohttp.JsonHttpResponseHandler.java

private String toString(HttpRequest httpRequest, final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    InputStream inputStream = entity.getContent();
    if (inputStream == null) {
        return "";
    }// w  w w  . j  a v a2 s  . com
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    int contentLength = (int) entity.getContentLength();
    if (contentLength < 0) {
        contentLength = 4096;
    }
    String charset = StringHttpResponseHandler.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    long averageLength = contentLength / httpRequest.getProgressCallbackNumber();
    int callbackNumber = 0;
    Reader reader = new InputStreamReader(inputStream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(contentLength);
    HttpRequest.ProgressListener progressListener = httpRequest.getProgressListener();
    try {
        char[] tmp = new char[1024];
        int readLength;
        long completedLength = 0;
        while (!httpRequest.isStopReadData() && (readLength = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, readLength);
            completedLength += readLength;
            if (progressListener != null && !httpRequest.isCanceled()
                    && (completedLength >= (callbackNumber + 1) * averageLength
                            || completedLength == contentLength)) {
                callbackNumber++;
                new HttpRequestHandler.UpdateProgressRunnable(httpRequest, contentLength, completedLength)
                        .execute();
            }
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}