List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:com.seajas.search.contender.jms.processor.TestElementProcessor.java
/** * Process the given archive.// www . j a va 2 s.c o m * * @param element * @param testType * @param rendezvousId */ public void process(final TestElement element, final TestType testType, final String rendezvousId) { TestResult result; if (logger.isInfoEnabled()) logger.info("Received test processing request of type " + testType.name() + " and rendezvous ID " + rendezvousId); switch (testType) { case EXPLORE: Map<String, Boolean> explorationResults = new HashMap<String, Boolean>(); String explorationStatus = "No links could be found within this indirect content"; // Try to retrieve an actual feed first try { SyndFeed deepFeed = feedModifierService.getFeed(element.getTestingUri(), element.getFeedEncodingOverride(), element.getPreferredUserAgent(), null, null, true); if (deepFeed != null) { explorationResults.put(element.getTestingUri().toString(), true); explorationStatus = RESULT_STATUS_OK; } else if (logger.isInfoEnabled()) logger.info( "Exploration URL is not a direct URL - will attempt to find indirect links instead"); } catch (Exception e) { logger.debug("Ignored", e); } // And if that fails, retrieve the content regularly and determine if we can scan it for indirect links if (explorationResults.size() == 0) { SourceElementModifierService.Content content = sourceElementModifierService.getContent( element.getTestingUri(), element.getResultEncodingOverride(), null, element.getPreferredUserAgent()); // We allow the encoding to be overridden if (content != null) { if (content.getContentType() == null || !content.getContentType().contains("html")) logger.error( "The given document does not have a content type, or the content type is not an HTML-type"); else { Reader reader = convertStructedContentInputStreamToReader(content.getInputStream(), content.getContentType(), element.getResultEncodingOverride()); try { List<String> indirectLinks = explorationService.getIndirectlyAccessibleFeedLinks( element.getTestingUri(), IOUtils.toString(reader)); if (indirectLinks.size() != 0) { for (String indirectLink : indirectLinks) explorationResults.put(indirectLink, false); explorationStatus = RESULT_STATUS_OK; } } catch (IOException e) { logger.error("Could not convert the given reader to a string", e); } finally { try { reader.close(); } catch (IOException e) { logger.error("Unable to close the given reader", e); } } } } } result = new TestResultImpl(explorationStatus.equals(RESULT_STATUS_OK), explorationStatus, explorationResults); break; case DEEP: Map<String, Boolean> deepModifierResults = new HashMap<String, Boolean>(); String deepStatus = RESULT_STATUS_OK; try { // Retrieve the feed first SyndFeed deepFeed = feedModifierService.getFeed(element.getTestingUri(), element.getFeedEncodingOverride(), element.getPreferredUserAgent(), null, null, false); // Then determine the URL to test with, if any if (deepFeed != null) { URI deepResultUri = sourceElementModifierService.getResultUri(element.getTestingUri(), deepFeed); if (deepResultUri != null) { deepModifierResults.putAll( sourceElementModifierService.testModifier(element.getModifierId(), deepResultUri, element.getResultEncodingOverride(), element.getPreferredUserAgent())); for (Entry<String, Boolean> modifierResult : deepModifierResults.entrySet()) if (!modifierResult.getValue()) { deepStatus = "Not all modifiers could be successfully applied to the given content"; break; } } else deepStatus = "No result to test with could be taken from the testing feed"; } else deepStatus = "The testing feed could not be constructed"; } catch (Exception e) { deepStatus = e.getMessage(); } result = new TestResultImpl(deepStatus.equals(RESULT_STATUS_OK), deepStatus, deepModifierResults); break; case SHALLOW: Map<String, Boolean> shallowModifierResults = new HashMap<String, Boolean>(); String shallowStatus = RESULT_STATUS_OK; try { shallowModifierResults .putAll(feedModifierService.testModifier(element.getModifierId(), element.getTestingUri(), element.getFeedEncodingOverride(), element.getPreferredUserAgent())); for (Entry<String, Boolean> modifierResult : shallowModifierResults.entrySet()) if (!modifierResult.getValue()) { shallowStatus = "Not all modifiers could be successfully applied to the given content"; break; } } catch (Exception e) { shallowStatus = e.getMessage(); } result = new TestResultImpl(shallowStatus.equals(RESULT_STATUS_OK), shallowStatus, shallowModifierResults); break; default: boolean connectionSuccess; if (element.isArchive()) connectionSuccess = archiveModifierService.testConnection(element.getTestingUri()); else connectionSuccess = feedModifierService.testConnection(element.getTestingUri(), element.getFeedEncodingOverride(), element.getPreferredUserAgent()); result = new TestResultImpl(connectionSuccess, RESULT_STATUS_OK, new HashMap<String, Boolean>()); break; } if (logger.isInfoEnabled()) logger.info( "Injecting result of test processing request of type " + testType.name() + " and rendezvous ID " + rendezvousId + ", which: " + (result.isSuccess() ? "succeeded" : "failed")); injectionService.injectTestResult(result, rendezvousId); }
From source file:com.amazonaws.a2s.AmazonA2SClient.java
/** * Reads stream into String/*from ww w .j ava2 s. co m*/ */ private String readStream(InputStream input) throws IOException { StringBuffer stringBuffer = new StringBuffer(); Reader reader = new BufferedReader(new InputStreamReader(input, "UTF8")); int ch; while ((ch = reader.read()) > -1) { stringBuffer.append((char) ch); } reader.close(); input.close(); return stringBuffer.toString(); }
From source file:com.newrelic.agent.Obfuscation.Proguard.java
private boolean fetchConfiguration() { /* */ try { /* 105 */ Reader propsReader = new BufferedReader( new FileReader(getProjectRoot() + File.separator + "newrelic.properties")); /* 106 */ Properties newRelicProps = new Properties(); /* 107 */ newRelicProps.load(propsReader); /* */ /* 109 */ this.licenseKey = newRelicProps.getProperty("com.newrelic.application_token"); /* 110 */ this.uploadingEnabled = newRelicProps .getProperty("com.newrelic.enable_proguard_upload", "true").equals("true"); /* 111 */ this.mappingApiHost = newRelicProps.getProperty("com.newrelic.mapping_upload_host"); /* */ /* 113 */ if (this.licenseKey == null) { /* 114 */ this.log.error( "Unable to find a value for com.newrelic.application_token in your newrelic.properties"); /* 115 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* */ /* 117 */ return false; /* */ } /* */ /* 120 */ propsReader.close(); /* */ } catch (FileNotFoundException e) { /* 122 */ this.log.error("Unable to find your newrelic.properties in the project root (" + getProjectRoot() + "): " + e.getLocalizedMessage()); /* 123 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* */ /* 125 */ return false; /* */ } catch (IOException e) { /* 127 */ this.log.error("Unable to read your newrelic.properties in the project root (" + getProjectRoot() + "): " + e.getLocalizedMessage()); /* 128 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* */ /* 130 */ return false; /* */ } /* *//*from w ww . ja v a 2 s. c o m*/ /* 133 */ return true; /* */ }
From source file:com.springrts.springls.statistics.Statistics.java
/** * This will create "statistics.dat" file which will contain all records * from the last 7 days.//from w w w.ja va2 s.co m */ private boolean createAggregateFile() { String fileName = STATISTICS_FOLDER + "statistics.dat"; Writer outF = null; Writer out = null; try { // overwrite if it exists, or create new one outF = new FileWriter(fileName, false); out = new BufferedWriter(outF); String line; SimpleDateFormat formatter = new SimpleDateFormat("ddMMyy"); Date today = today(); long msPerDay = 1000 * 60 * 60 * 24; // get file names for last 7 days (that is today + previous 6 days) for (int i = 7; i > 0; i--) { Date day = new Date(); day.setTime(today.getTime() - (((long) i - 1) * msPerDay)); String dayStr = formatter.format(day); File fileDay = new File(STATISTICS_FOLDER + formatter.format(dayStr) + ".dat"); Reader inF = null; BufferedReader in = null; try { inF = new FileReader(fileDay); in = new BufferedReader(inF); LOG.trace("Found stats: <{}>", fileDay.getAbsolutePath()); while ((line = in.readLine()) != null) { out.write(dayStr); out.write(' '); out.write(line); out.write(Misc.EOL); } } catch (IOException ex) { LOG.trace("Skipped stats: <" + fileDay.getAbsolutePath() + ">", ex); } finally { if (in != null) { in.close(); } else if (inF != null) { inF.close(); } } } } catch (IOException ex) { LOG.error("Unable to access file <" + fileName + ">. Skipping ...", ex); return false; } finally { try { if (out != null) { out.close(); } else if (outF != null) { outF.close(); } } catch (IOException ex) { LOG.trace("Failed closing aggregate statistics file-writer for" + " file: " + fileName, ex); } } return true; }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Object getGoldCoinValueBTC() { Date date = new Date(); long now = date.getTime(); if ((now < (lastBitcoinValueCheck + 10 * 60)) && lastBitcoinValue > 0.0) return lastBitcoinValue; //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double btcRate = 0.0;//from ww w . ja v a 2 s . c o m String currencyCryptsy = "BTC"; String urlCryptsy2 = "http://pubapi.cryptsy.com/api.php?method=marketdata"; String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=30"; try { // final String currencyCode = currencies[i]; final URL URLCryptsy = new URL(urlCryptsy); final URLConnection connectionCryptsy = URLCryptsy.openConnection(); connectionCryptsy.setConnectTimeout(TIMEOUT_MS * 2); connectionCryptsy.setReadTimeout(TIMEOUT_MS * 2); connectionCryptsy.connect(); final StringBuilder contentCryptsy = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024)); IOUtils.copy(reader, contentCryptsy); final JSONObject head = new JSONObject(contentCryptsy.toString()); JSONObject returnObject = head.getJSONObject("return"); JSONObject markets = returnObject.getJSONObject("markets"); JSONObject GLD = markets.getJSONObject("GLD"); JSONArray recenttrades = GLD.getJSONArray("recenttrades"); double btcTraded = 0.0; double gldTraded = 0.0; for (int i = 0; i < recenttrades.length(); ++i) { JSONObject trade = (JSONObject) recenttrades.get(i); btcTraded += trade.getDouble("total"); gldTraded += trade.getDouble("quantity"); } Double averageTrade = btcTraded / gldTraded; //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; lastBitcoinValue = btcRate; lastBitcoinValueCheck = now; } finally { if (reader != null) reader.close(); } return btcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:com.recomdata.transmart.data.export.util.FileWriterUtil.java
public String getClobAsString(Clob clob) { String strVal = ""; Reader reader = null; StringBuffer strBuf = null;// w w w .ja v a 2 s . co m try { if (null != clob) { Long clobLength = (null != clob) ? clob.length() : 0; reader = clob.getCharacterStream(); if (null != clobLength && clobLength > 0 && null != reader) { //Here length of String is being rounded to 5000 * n, this is because the buffer size is 5000 //Sometimes the cloblength is less than 5000 * n char[] buffer = new char[clobLength.intValue()]; @SuppressWarnings("unused") int count = 0; strBuf = new StringBuffer(); while ((count = reader.read(buffer)) > 0) { strBuf.append(buffer); } strVal = strBuf.toString(); } } } catch (IOException e) { log.info(e.getMessage()); } catch (SQLException e2) { log.info("SQLException :: " + e2.getMessage()); } finally { try { if (null != reader) reader.close(); //Nullify the objects so they become ready for Garbage Collection reader = null; strBuf = null; clob = null; super.finalize(); } catch (IOException e) { log.info("Error closing Reader in getClobAsString"); } catch (Throwable e) { log.info("Error during super.finalize()"); } } return strVal; }
From source file:su90.etl.controller.SlaveController.java
private void _do_clicks() { Reader in = null; try {// w w w. j a v a 2 s .co m in = new FileReader(INPUTPATHSTR + System.getProperty("file.separator") + "facts" + System.getProperty("file.separator") + "clicks" + System.getProperty("file.separator") + FILENAME); Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in); for (CSVRecord record : records) { Result tmpresult = parse_clicks(record.iterator()); if (results.containsKey(tmpresult.hashCode())) { Result previousresult = results.get(tmpresult.hashCode()); previousresult.setClicks(previousresult.getClicks() + tmpresult.getClicks()); results.put(previousresult.hashCode(), previousresult); } else { results.put(tmpresult.hashCode(), tmpresult); } } } catch (FileNotFoundException ex) { Logger.getLogger(SlaveController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SlaveController.class.getName()).log(Level.SEVERE, null, ex); } finally { if (in != null) try { in.close(); } catch (IOException ex) { Logger.getLogger(SlaveController.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:org.onebusaway.siri.core.SiriCommon.java
protected Reader copyReaderToStringBuilder(Reader responseReader, StringBuilder b) throws IOException { char[] buffer = new char[1024]; while (true) { int rc = responseReader.read(buffer); if (rc == -1) break; b.append(buffer, 0, rc);/*from w w w.j av a 2 s . co m*/ } responseReader.close(); responseReader = new StringReader(b.toString()); return responseReader; }