List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java
/** * Test a feed by retrieving the content and then discarding it. * /*from w w w. j av a 2 s . c o m*/ * @param uri * @param encodingOverride * @param userAgent * @return boolean */ public boolean testConnection(final URI uri, final String encodingOverride, final String userAgent) { try { // Retrieve the reader, then close the stream logger.info("Retrieving testing content for feed with URI " + uri); Reader result = getContent(uri, encodingOverride, userAgent, null); if (result != null) result.close(); else { logger.error("Could not retrieve testing content for feed with URI " + uri); return false; } return true; } catch (IOException e) { logger.error("Could not retrieve testing content for feed with URI " + uri, e); return false; } }
From source file:com.lexicalintelligence.admin.add.AddRequest.java
public AddResponse execute() { List<BasicNameValuePair> params = Collections .singletonList(new BasicNameValuePair(getName(), StringUtils.join(items, ","))); AddResponse addResponse;/* ww w . ja v a 2 s .c o m*/ Reader reader = null; try { HttpResponse response = client.getHttpClient().execute(new HttpGet(client.getUrl() + PATH + getPath() + "?" + URLEncodedUtils.format(params, StandardCharsets.UTF_8))); reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8); addResponse = new AddResponse(Boolean.valueOf(IOUtils.toString(reader))); } catch (Exception e) { addResponse = new AddResponse(false); log.error(e); } finally { try { reader.close(); } catch (Exception e) { log.error(e); } } return addResponse; }
From source file:com.krawler.common.util.ByteUtil.java
/** * Reads a <tt>String</tt> from the given <tt>Reader</tt>. Reads until * the either end of the stream is hit or until <tt>length</tt> characters * are read./*from www . ja va 2 s.c om*/ * * @return the content or an empty <tt>String</tt> if no content is * available */ public static String getContent(Reader reader, int length, boolean close) throws IOException { if (reader == null || length == 0) { return ""; } if (length < 0) { length = Integer.MAX_VALUE; } char[] buf = new char[Math.min(1024, length)]; int totalRead = 0; StringBuilder retVal = new StringBuilder(buf.length); try { while (true) { int numToRead = Math.min(buf.length, length - totalRead); if (numToRead <= 0) { break; } int numRead = reader.read(buf); if (numRead < 0) { break; } retVal.append(buf, 0, numRead); totalRead += numRead; } return retVal.toString(); } finally { if (close) { try { reader.close(); } catch (IOException e) { KrawlerLog.misc.warn("Unable to close Reader", e); } } } }
From source file:edu.washington.gs.skyline.model.quantification.QuantificationTest.java
private Map<RecordKey, Double> readExpectedRows(String filename) throws Exception { Map<RecordKey, Double> map = new HashMap<>(); Reader reader = new InputStreamReader(QuantificationTest.class.getResourceAsStream(filename)); try {/*from w w w.j a va 2 s . co m*/ CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader()); for (CSVRecord record : parser.getRecords()) { map.put(new RecordKey(record), parseNullableDouble(record.get("NormalizedArea"))); } } finally { reader.close(); } return map; }
From source file:fr.paris.lutece.plugins.helpdesk.modules.solr.search.SolrHelpdeskIndexer.java
/** * Builds a {@link SolrItem} which will be used by Solr during the indexing of the question/answer list * * @param nIdFaq The {@link Faq} Id// w ww.ja va2s . co m * @param questionAnswer the {@link QuestionAnswer} to index * @param strUrl the url of the subject * @param strRoleKey The role key * @param plugin The {@link Plugin} * @return A Solr {@link SolrItem} containing QuestionAnswer Data * @throws IOException The IO Exception */ private SolrItem getDocument(int nIdFaq, QuestionAnswer questionAnswer, String strUrl, String strRoleKey, Plugin plugin) throws IOException { // make a new, empty document SolrItem item = new SolrItem(); // Setting the Id faq field item.addDynamicField(HelpdeskSearchItem.FIELD_FAQ_ID, String.valueOf(nIdFaq)); // Setting the Role field item.setRole(strRoleKey); // Setting the URL field item.setUrl(strUrl); // Setting the subject field item.addDynamicField(HelpdeskSearchItem.FIELD_SUBJECT, String.valueOf(questionAnswer.getIdSubject())); // Setting the Uid field String strIdQuestionAnswer = String.valueOf(questionAnswer.getIdQuestionAnswer()); item.setUid( getResourceUid(strIdQuestionAnswer, HelpdeskIndexerUtils.CONSTANT_QUESTION_ANSWER_TYPE_RESOURCE)); // Setting the Date field // Add the last modified date of the file a field named "modified". item.setDate(questionAnswer.getCreationDate()); //Setting the Content field String strContentToIndex = getContentToIndex(questionAnswer, plugin); StringReader readerPage = new StringReader(strContentToIndex); HTMLParser parser = new HTMLParser(readerPage); Reader reader = parser.getReader(); int c; StringBuffer sb = new StringBuffer(); while ((c = reader.read()) != -1) { sb.append(String.valueOf((char) c)); } reader.close(); item.setContent(sb.toString()); // Setting the Title field item.setTitle(questionAnswer.getQuestion()); // Setting the Site field item.setSite(SolrIndexerService.getWebAppName()); // Setting the Type field item.setType(HelpdeskPlugin.PLUGIN_NAME); // return the document return item; }
From source file:kindleclippings.quizlet.QuizletSync.java
private static Map<String, List<Clipping>> readClippingsFile() throws IOException { // try to find it File cl = new File("/Volumes/Kindle/documents/My Clippings.txt"); if (!cl.canRead()) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileNameExtensionFilter("Kindle Clippings", "txt")); int result = fc.showOpenDialog(null); if (result != JFileChooser.APPROVE_OPTION) { return null; }/*from ww w .ja v a 2s . c o m*/ cl = fc.getSelectedFile(); } Reader f = new InputStreamReader(new FileInputStream(cl), "UTF-8"); try { MyClippingsReader r = new MyClippingsReader(f); Map<String, List<Clipping>> books = new TreeMap<String, List<Clipping>>(); Clipping l; while ((l = r.readClipping()) != null) { if (l.getType() != ClippingType.highlight && l.getType() != ClippingType.note) { System.err.println("ignored " + l.getType() + " [" + l.getBook() + "]"); continue; } String lct = l.getContent().trim(); if (lct.length() == 0) { System.err.println("ignored empty " + l.getType() + " [" + l.getBook() + "]"); continue; } if (lct.length() < 10 || !lct.contains(" ")) { System.err.println( "ignored too short " + l.getType() + " " + l.getContent() + " [" + l.getBook() + "]"); continue; } List<Clipping> clippings = books.get(l.getBook()); if (clippings == null) { clippings = new ArrayList<Clipping>(); books.put(l.getBook(), clippings); } clippings.add(l); } return books; } finally { f.close(); } }
From source file:com.lexicalintelligence.admin.remove.RemoveRequest.java
public RemoveResponse execute() { List<BasicNameValuePair> params = Collections .singletonList(new BasicNameValuePair(getName(), StringUtils.join(items, ","))); RemoveResponse removeResponse;//from w w w . j ava 2 s . c om Reader reader = null; try { HttpResponse response = client.getHttpClient().execute(new HttpGet(client.getUrl() + PATH + getPath() + "?" + URLEncodedUtils.format(params, StandardCharsets.UTF_8))); reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8); removeResponse = new RemoveResponse(Boolean.valueOf(IOUtils.toString(reader))); } catch (Exception e) { removeResponse = new RemoveResponse(false); log.error(e); } finally { try { reader.close(); } catch (Exception e) { log.error(e); } } return removeResponse; }
From source file:com.stratuscom.harvester.liaison.VirtualFileSystemConfiguration.java
public VirtualFileSystemConfiguration(String[] options, ClassLoader cl) throws ConfigurationException { /* no options; just delegate. */ if (options == null || options.length == 0) { delegate = new MyConfigurationFile(options, cl); return;//from w ww. j a va 2 s. c o m } /* No file called for; just delegate. */ if (Strings.DASH.equals(options[0])) { delegate = new MyConfigurationFile(options, cl); return; } /* Else, find the configuration file inside the working directory and open it. TODO: Should probably check to make sure that the supplied file name does not include absolute path or '..' path, i.e. make sure that the resolved file is actually a descendant of the working directory. */ Reader reader = null; try { FileObject configFile = rootDirectory.resolveFile(options[0]); reader = new InputStreamReader(configFile.getContent().getInputStream()); delegate = new MyConfigurationFile(reader, options, cl); } catch (FileSystemException ex) { throw new ConfigurationNotFoundException(options[0], ex); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { throw new ConfigurationException(Strings.ERROR_CLOSING_FILE, ex); } } } }
From source file:jp.go.aist.six.util.core.xml.castor.CastorXmlMapper.java
public Object unmarshal(final Reader reader) { Object obj = null;//from w w w . j a v a 2 s . co m Reader r = ((reader instanceof BufferedReader) ? reader : (new BufferedReader(reader))); try { obj = _unmarshaller.unmarshal(new StreamSource(r)); //@throws IOException //@throws XmlMappingException } catch (Exception ex) { throw new XmlException(ex); } finally { try { reader.close(); } catch (IOException ex) { //ignorable } } return obj; }
From source file:magoffin.matt.sobriquet.web.ImportController.java
/** * Begin the import process.//from w w w. java2s . co m * * @param form * The import data. * @param session * The HTTP session. This is required so we can store the parsed data * in memory to verify. * @return The response. * @throws IOException * If any IO error occurs. */ @RequestMapping(method = RequestMethod.POST, params = "_to=verify") @ResponseBody public Response<List<Alias>> verify(@ModelAttribute("importForm") ImportForm form, HttpSession session) throws IOException { Reader reader = null; if (form.getFile() != null && form.getFile().getSize() > 0) { reader = new InputStreamReader(form.getFile().getInputStream(), "UTF-8"); } else { reader = new StringReader(form.getAliasData()); } List<Alias> results = new ArrayList<Alias>(); try { for (Alias alias : ioService.parseAliasRecords(reader)) { results.add(alias); } form.setAliases(results); } finally { try { reader.close(); } catch (IOException e) { // ignore } } //form.setFile(null); return Response.response(results); }