List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:com.google.acre.script.NHttpAsyncUrlfetch.java
private Scriptable callback_result(long start_time, URL url, HttpResponse res, boolean system, boolean log_to_user, String response_encoding) { BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory(); CookieSpec cspec = bcsf.newInstance(null); String protocol = url.getProtocol(); boolean issecure = ("https".equals(protocol)); int port = url.getPort(); if (port == -1) port = 80;/*from w w w .j av a 2 s.co m*/ CookieOrigin origin = new CookieOrigin(url.getHost(), port, url.getPath(), issecure); Object body = ""; int status = res.getStatusLine().getStatusCode(); Context ctx = Context.getCurrentContext(); Scriptable out = ctx.newObject(_scope); Scriptable headers = ctx.newObject(_scope); Scriptable cookies = ctx.newObject(_scope); out.put("status", out, status); out.put("headers", out, headers); out.put("cookies", out, cookies); Header content_type_header = null; StringBuilder response_header_log = new StringBuilder(); for (Header h : res.getAllHeaders()) { if (h.getName().equalsIgnoreCase("set-cookie")) { String set_cookie = h.getValue(); Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie); while (m.find()) { Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end())); try { List<Cookie> pcookies = cspec.parse(ch, origin); for (Cookie c : pcookies) { cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope)); } } catch (MalformedCookieException e) { throw new RuntimeException(e); } } } else if (h.getName().equalsIgnoreCase("content-type")) { content_type_header = h; } response_header_log.append(h.getName() + ": " + h.getValue() + "\r\n"); headers.put(h.getName(), headers, h.getValue()); } String charset = null; if (content_type_header != null) { HeaderElement values[] = content_type_header.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset == null) charset = response_encoding; // read body HttpEntity ent = res.getEntity(); try { if (ent != null) { InputStream res_stream = ent.getContent(); Header cenc = ent.getContentEncoding(); if (cenc != null && res_stream != null) { HeaderElement[] codecs = cenc.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { res_stream = new GZIPInputStream(res_stream); } } } long first_byte_time = 0; long end_time = 0; if (content_type_header != null && (content_type_header.getValue().startsWith("image/") || content_type_header.getValue().startsWith("application/octet-stream") || content_type_header.getValue().startsWith("multipart/form-data"))) { // HttpClient's InputStream doesn't support mark/reset, so // wrap it with one that does. BufferedInputStream bufis = new BufferedInputStream(res_stream); bufis.mark(2); bufis.read(); first_byte_time = System.currentTimeMillis(); bufis.reset(); byte[] data = IOUtils.toByteArray(bufis); end_time = System.currentTimeMillis(); body = new JSBinary(); ((JSBinary) body).set_data(data); try { if (res_stream != null) res_stream.close(); } catch (IOException e) { // ignore } } else if (res_stream == null || charset == null) { first_byte_time = end_time = System.currentTimeMillis(); body = ""; } else { StringWriter writer = new StringWriter(); Reader reader = new InputStreamReader(res_stream, charset); int i = reader.read(); first_byte_time = System.currentTimeMillis(); writer.write(i); IOUtils.copy(reader, writer); end_time = System.currentTimeMillis(); body = writer.toString(); try { reader.close(); writer.close(); } catch (IOException e) { // ignore } } long reading_time = end_time - first_byte_time; long waiting_time = first_byte_time - start_time; String httprephdr = response_header_log.toString(); // XXX need to log start-time of request _logger.syslog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status", Integer.toString(status), "Headers", httprephdr, "Reading time", reading_time, "Waiting time", waiting_time); if (system && log_to_user) { _response.userlog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status", Integer.toString(status), "Headers", httprephdr); } // XXX seems like AcreResponse should be able to use // the statistics object to generate x-metaweb-cost // given a bit of extra information Statistics.instance().collectUrlfetchTime(start_time, first_byte_time, end_time); _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waiting_time); } } catch (IOException e) { throw new RuntimeException(e); } out.put("body", out, body); return out; }
From source file:espresso.CsCompiler.java
public CsCompiler() { InputStream inputStream = CsCompiler.class.getResourceAsStream("coffee-script.js"); try {//from w w w . j av a2 s .c o m try { Reader reader = new InputStreamReader(inputStream, "UTF-8"); try { Context context = Context.enter(); context.setOptimizationLevel(-1); // Without this, Rhino hits a 64K bytecode limit and fails try { globalScope = context.initStandardObjects(); context.evaluateReader(globalScope, reader, "coffee-script.js", 0, null); // Load base import. libraries.put(ESPRESSO_BASE, compileRaw(readEspressoBase(), globalScope)); } finally { Context.exit(); } } finally { reader.close(); } } catch (UnsupportedEncodingException e) { throw new Error(e); // This should never happen } finally { inputStream.close(); } } catch (IOException e) { throw new Error(e); // This should never happen } }
From source file:com.benfante.minimark.blo.AssessmentPdfBuilder.java
/** * Build the PDF for an assessment./* w w w. jav a2 s . co m*/ * * @param assessment The assessment * @param baseUrl The base URL for retrieving images and resource. If null it will not be set. * @param locale The locale for producing the document. Id null, the default locale will be used. * @return The PDF document. */ public byte[] buildPdf(AssessmentFilling assessment, String baseUrl, Locale locale) throws Exception { String xmlfo = assessmentXMLFOBuilder.makeXMLFO(assessment, locale != null ? locale : Locale.getDefault()); ByteArrayOutputStream pdfos = new ByteArrayOutputStream(); Reader foreader = null; try { foreader = new StringReader(xmlfo); FOUserAgent foua = fopFactory.newFOUserAgent(); if (baseUrl != null) { foua.setBaseURL(baseUrl); } Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foua, pdfos); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // identity transformer Source src = new StreamSource(foreader); Result result = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, result); } finally { if (foreader != null) { try { foreader.close(); } catch (IOException ioe) { } } if (pdfos != null) { try { pdfos.close(); } catch (IOException ioe) { } } } return pdfos.toByteArray(); }
From source file:com.microsoft.tfs.util.NewlineUtils.java
/** * Converts all of the line-endings in a file to the desired newline * sequence. The conversion is done using a temporary file which replaces * the original file before the method returns. * <p>// w ww . j a v a 2 s .co m * The character set to use for the input and output files may be specified, * or left null to use the default. * <p> * This method uses Java's {@link InputStreamReader} class to read the input * file, automatically detects the byte-encoding of the input file * (UTF-16LE, UTF-16BE, UTF-8, etc.). The ability of this method to read and * convert files is limited to those which can be read by the Java runtime * where it is run. * * @param file * the file to convert (which will be replaced by the converted file * when this method returns). Not null. * @param charset * the {@link Charset} to use to read the input file and write the * converted file, or null to use the default encoding. * @param desiredNewlineSequence * the desired newline sequence to write to the converted file. Not * null, but may be empty to remove newlines. See public members of * this class for pre-defined newline characters. * @throws UnsupportedEncodingException * if the encoding given is not supported by this Java environment. * @throws IOException * if an error occurred reading the file or writing the converted * file. This exception may also indicate an error reading the file * with the given character set. */ public static void convertFile(final File file, final Charset charset, final String desiredNewlineSequence) throws UnsupportedEncodingException, IOException { Check.notNull(file, "file"); //$NON-NLS-1$ Check.notNull(desiredNewlineSequence, "desiredNewlineSequence"); //$NON-NLS-1$ final File directory = file.getParentFile(); File temp = File.createTempFile("tfsEOL", ".tmp", directory); //$NON-NLS-1$ //$NON-NLS-2$ try { /* * Don't need a buffered reader because the conversion method uses * its own buffer. */ Reader reader = null; Writer writer = null; try { /* * The concept of the "default" character set is complicated, * since it means something different to the different stream * layers involved. It's simplest just to use the different * constructors. */ if (charset == null) { reader = new InputStreamReader(new FileInputStream(file)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(temp))); } else { final CharsetDecoder decoder = charset.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); reader = new InputStreamReader(new FileInputStream(file), decoder); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(temp), charset)); } replaceNewlines(reader, writer, desiredNewlineSequence, false); } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { log.error("Error closing reader", e); //$NON-NLS-1$ } } if (writer != null) { try { writer.close(); } catch (final IOException e) { log.error("Error closing writer", e); //$NON-NLS-1$ } } } /* * Replace the original with the temp file. Delete the original file * because renaming to an existing file which is read-only fails on * some platforms. Changing the original file to writeable requires * JNI methods not available in com.microsoft.tfs.util for * dependency reasons. */ if (file.delete() == false) { final String messageFormat = "Error deleting file '{0}' for replacement with EOL-converted file."; //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, file.getAbsolutePath()); log.error(message); throw new IOException(message); } if (temp.renameTo(file) == false) { final String messageFormat = "Error renaming temporary file '{0}' to '{1}' after EOL conversion."; //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, temp.getAbsolutePath(), file.getAbsolutePath()); log.error(message); throw new IOException(message); } /* * File no longer exists, we can skip the deletion for slight * performance increase. */ temp = null; } finally { if (temp != null) { temp.delete(); } } }
From source file:com.lucidtechnics.blackboard.util.Jsr223ScriptingUtil.java
public CompiledScript compileScript(String _scriptResource) { Reader reader = null; try {//from ww w . ja v a 2 s . c o m if (getScriptResourceMap().containsKey(_scriptResource) == false && getScriptEngine() instanceof javax.script.Compilable) { reader = new InputStreamReader(findScript(_scriptResource)); CompiledScript script = ((javax.script.Compilable) getScriptEngine()).compile(reader); synchronized (getScriptResourceMap()) { getScriptResourceMap().put(_scriptResource, script); } } } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } return getScriptResourceMap().get(_scriptResource); }
From source file:co.cask.cdap.gateway.handlers.metrics.MetricsQueryTest.java
@Test public void testGetMetric() throws Exception { // Insert some metric MetricsCollector collector = collectionService.getCollector(MetricsScope.SYSTEM, "WordCount.f.WordCounter.counter", "0"); collector.increment("reads", 10, "wordStats"); collector.increment("collect.events", 10, "wordStream"); collector = collectionService.getCollector(MetricsScope.SYSTEM, "-.cluster", "0"); collector.increment("resources.total.storage", 10); // Wait for collection to happen TimeUnit.SECONDS.sleep(2);//from w w w . j av a 2s.c o m for (String resource : validResources) { HttpResponse response = doGet("/v2/metrics" + resource); Reader reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8); try { Assert.assertEquals("GET " + resource + " did not return 200 status.", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); JsonObject json = new Gson().fromJson(reader, JsonObject.class); // Expected result looks like // { // "result":{"data":10} // } Assert.assertEquals("GET " + resource + " returned unexpected results.", 10, json.get("data").getAsInt()); } finally { reader.close(); } } }
From source file:org.archive.crawler.processor.LexicalCrawlMapper.java
/** * Retrieve and parse the mapping specification from a local path or * HTTP URL. /*from ww w . j av a 2 s.c om*/ * * @throws IOException */ protected void loadMap() throws IOException { map.clear(); String uri = getMapUri(); Reader reader = null; if (uri.trim().length() == 0) { File source = getMapPath().getFile(); reader = new FileReader(source); } else { URLConnection conn = (new URL(uri)).openConnection(); reader = new InputStreamReader(conn.getInputStream()); } reader = new BufferedReader(reader); Iterator<String> iter = new RegexLineIterator(new LineReadingIterator((BufferedReader) reader), RegexLineIterator.COMMENT_LINE, RegexLineIterator.TRIMMED_ENTRY_TRAILING_COMMENT, RegexLineIterator.ENTRY); while (iter.hasNext()) { String[] entry = ((String) iter.next()).split("\\s+"); map.put(entry[0], entry[1]); } reader.close(); }
From source file:name.vysoky.xhtml.Corrector.java
private void process(File inputFile, File outputFile, String codePage) { Reader reader = null; Writer writer = null;//from w w w . ja v a 2 s .co m try { reader = new InputStreamReader(new BufferedInputStream(new FileInputStream(inputFile)), codePage); writer = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(outputFile)), codePage); char c; int b = reader.read(); while (b != -1) { c = (char) b; writer.write(processChar(c)); b = reader.read(); } if (builder.length() > 0) writer.write(builder.toString().toCharArray()); } catch (IOException e) { System.err.println("Unable write streams!"); e.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e) { System.err.println("Unable to close streams!"); e.printStackTrace(); } } }
From source file:com.mirth.connect.connectors.file.FileMessageReceiver.java
/** Process a single file as a batched message source */ private void processBatch(FileInfo file) throws Exception { UMOEndpointURI uri = endpoint.getEndpointURI(); Protocol protocol = Protocol.valueOf(fileConnector.getInboundProtocol()); Adaptor adaptor = AdaptorFactory.getAdaptor(protocol); if (adaptor instanceof BatchAdaptor) { BatchAdaptor batchAdaptor = (BatchAdaptor) adaptor; FileSystemConnection con = fileConnector.getConnection(uri, null); Reader in = null; try {//from w w w. j a v a 2 s. com in = new InputStreamReader(con.readFile(file.getName(), readDir), fileConnector.getCharsetEncoding()); Map<String, String> protocolProperties = fileConnector.getProtocolProperties(); protocolProperties.put("batchScriptId", fileConnector.getChannelId()); batchAdaptor.processBatch(in, fileConnector.getProtocolProperties(), this, endpoint); } finally { if (in != null) { in.close(); } con.closeReadFile(); fileConnector.releaseConnection(uri, con, null); } } else { throw new Exception("Data type " + protocol + " does not support batch processing."); } }
From source file:de.uzk.hki.da.metadata.MetsMetadataStructure.java
public void makeReplacementsHrefInMetsFile(File targetMetsFile, String currentHref, String targetHref, String mimetype, String loctype) throws IOException, JDOMException { SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder(); logger.debug(":::" + workPath + ":::" + targetMetsFile.getPath()); FileInputStream fileInputStream = new FileInputStream(Path.makeFile(workPath, targetMetsFile.getPath())); BOMInputStream bomInputStream = new BOMInputStream(fileInputStream); Reader reader = new InputStreamReader(bomInputStream, "UTF-8"); InputSource is = new InputSource(reader); is.setEncoding("UTF-8"); Document metsDoc = builder.build(is); List<Element> metsFileElements = metsParser.getFileElementsFromMetsDoc(metsDoc); for (int i = 0; i < metsFileElements.size(); i++) { Element fileElement = (Element) metsFileElements.get(i); if (metsParser.getHref(fileElement).equals(currentHref)) { setHref(fileElement, targetHref); setMimetype(fileElement, mimetype); setLoctype(fileElement, loctype); }/* w w w . j a v a 2 s .c o m*/ } fileInputStream.close(); bomInputStream.close(); reader.close(); writeDocumentToFile(metsDoc, Path.makeFile(workPath, targetMetsFile.getPath())); }