List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:cn.dreampie.common.plugin.coffeescript.compiler.CoffeeCompiler.java
private void init() throws IOException { InputStream inputStream = coffeeJs.openConnection().getInputStream(); try {// w w w . j a va2s. 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); } 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:edu.washington.gs.skyline.model.quantification.QuantificationTest.java
private List<ReplicateData> readReplicates(String filename) throws Exception { Map<String, ReplicateData> replicates = new LinkedHashMap<>(); Reader reader = new InputStreamReader(QuantificationTest.class.getResourceAsStream(filename)); try {//from ww w . j a va 2 s . c o m CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader()); for (CSVRecord record : parser.getRecords()) { String fileName = record.get("FileName"); ReplicateData replicate = replicates.get(fileName); if (replicate == null) { replicate = new ReplicateData(); replicates.put(fileName, replicate); } } } finally { reader.close(); } throw new NotImplementedException(); }
From source file:co.cask.cdap.gateway.collector.NettyFlumeCollectorTest.java
@Test public void testFlumeEnqueue() throws Exception { CConfiguration cConfig = GatewayTestBase.getInjector().getInstance(CConfiguration.class); cConfig.setInt(Constants.Gateway.STREAM_FLUME_PORT, 0); NettyFlumeCollector flumeCollector = GatewayTestBase.getInjector().getInstance(NettyFlumeCollector.class); flumeCollector.startAndWait();//from www . ja v a 2 s. c o m int port = flumeCollector.getPort(); String streamName = "flume-stream"; // Create new stream. HttpResponse response = GatewayFastTestsSuite.doPut("/v2/streams/" + streamName); Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); // Send flume events int totalEvents = 12; // Send 6 events one by one for (int i = 0; i < totalEvents / 2; i++) { sendFlumeEvent(port, createFlumeEvent(i, streamName)); } // Send 6 events in a batch sendFlumeEvents(port, streamName, totalEvents / 2, totalEvents); flumeCollector.stopAndWait(); // Get all stream events response = GatewayFastTestsSuite.doGet("/v2/streams/" + streamName + "/events?limit=13"); Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode()); long lastEventTime = 0L; Reader reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8); try { List<StreamEvent> events = GSON.fromJson(reader, new TypeToken<List<StreamEvent>>() { }.getType()); Assert.assertEquals(totalEvents, events.size()); for (int i = 0; i < totalEvents; i++) { StreamEvent event = events.get(i); Assert.assertEquals(Integer.toString(i), event.getHeaders().get("messageNumber")); Assert.assertEquals("This is a message " + i, Charsets.UTF_8.decode(event.getBody()).toString()); lastEventTime = event.getTimestamp(); } } finally { reader.close(); } // Fetch again, there should be no more events response = GatewayFastTestsSuite .doGet("/v2/streams/" + streamName + "/events?start=" + (lastEventTime + 1L)); Assert.assertEquals(HttpResponseStatus.NO_CONTENT.getCode(), response.getStatusLine().getStatusCode()); }
From source file:com.mousefeed.eclipse.preferences.PreferenceAccessor.java
/** * Loads preferences for the {@link #getOnWrongInvocationMode(String)}. *//*from w ww .ja v a2 s . c o m*/ private void loadActionsOnWrongInvocationMode() { final File file = getActionsWrongInvocationModeFile(); if (!file.exists() || file.length() == 0) { // the file not initialized yet return; } Reader reader = null; try { reader = new FileReader(file); final XMLMemento memento = XMLMemento.createReadRoot(reader); loadActionsOnWrongInvocationMode(memento); } catch (final FileNotFoundException ignore) { // the file does not exist yet } catch (final WorkbenchException e) { throw new RuntimeException(e); } finally { try { if (reader != null) { reader.close(); } } catch (final IOException e) { throw new RuntimeException(e); } } }
From source file:com.sfs.jbtimporter.JBTProcessor.java
/** * Load xml data from the supplied file. * /*www .ja v a 2 s . com*/ * @param filepath the filepath * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public final String loadXmlDataFile(final String filepath) throws IOException { StringBuffer contents = new StringBuffer(); Reader reader = new InputStreamReader(new FileInputStream(filepath), "UTF-8"); int ch; do { ch = reader.read(); if (ch != -1) { contents.append((char) ch); } } while (ch != -1); reader.close(); return contents.toString(); }
From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java
/** * Sends request to Equifax.//w w w. jav a2s. c o m * @param server {@link String} * @param send {@link String} * @return {@link String} * @throws IOException IOException */ public String sendToEquifax(final String server, final String send) throws IOException { String params = "InputSegments=" + URLEncoder.encode(send, "UTF-8") + "&cmdSubmit=Submit"; byte[] postData = params.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; URL url = new URL(server); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); conn.setUseCaches(false); Reader in = null; DataOutputStream wr = null; try { wr = new DataOutputStream(conn.getOutputStream()); wr.write(postData); StringBuilder sb = new StringBuilder(); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (int c = in.read(); c != -1; c = in.read()) { sb.append((char) c); } String receive = sb.toString(); return receive; } finally { if (in != null) { in.close(); } if (wr != null) { wr.close(); } } }
From source file:im.delight.android.webrequest.WebRequest.java
protected String parseResponse(HttpResponse response) throws Exception { final Header contentEncoding = response.getFirstHeader("Content-Encoding"); // if we have a compressed response (GZIP) if (contentEncoding != null && contentEncoding.getValue() != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { // get the entity and the content length (if any) from the response final HttpEntity entity = response.getEntity(); long contentLength = entity.getContentLength(); // handle too large or undefined content lengths if (contentLength > Integer.MAX_VALUE) { throw new Exception("Response too large"); } else if (contentLength < 0) { // use an arbitrary buffer size contentLength = 4096;/*from ww w . j a v a2 s .c om*/ } // construct a GZIP input stream from the response InputStream responseStream = entity.getContent(); if (responseStream == null) { return null; } responseStream = new GZIPInputStream(responseStream); // read from the stream Reader reader = new InputStreamReader(responseStream, mCharset); CharArrayBuffer buffer = new CharArrayBuffer((int) contentLength); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } finally { reader.close(); } // return the decompressed response text as a string return buffer.toString(); } // if we have an uncompressed response else { // return the response text as a string return EntityUtils.toString(response.getEntity(), mCharset); } }
From source file:com.zimbra.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./*ww w . j a v a2 s . c om*/ * * @param reader the content source * @param length number of characters to read, or <tt>-1</tt> for no limit * @param close <tt>true</tt> to close the <tt>Reader</tt> when done * @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, 0, numToRead); if (numRead < 0) break; retVal.append(buf, 0, numRead); totalRead += numRead; } return retVal.toString(); } finally { if (close) { try { reader.close(); } catch (IOException e) { ZimbraLog.misc.warn("Unable to close Reader", e); } } } }
From source file:com.bigdata.gom.TestRemoteGOM.java
void print(final URL n3) throws IOException { if (log.isInfoEnabled()) { InputStream in = n3.openConnection().getInputStream(); Reader reader = new InputStreamReader(in); try {/*from ww w.j ava 2 s . c om*/ char[] buf = new char[256]; int rdlen = 0; while ((rdlen = reader.read(buf)) > -1) { if (rdlen == 256) System.out.print(buf); else System.out.print(new String(buf, 0, rdlen)); } } finally { reader.close(); } } }
From source file:cn.dreampie.coffeescript.compiler.CoffeeCompiler.java
private void init() throws IOException { InputStream inputStream = null; if (coffeeJs == null) { logger.info("coffee-script file not found"); inputStream = this.getClass().getResourceAsStream("/lib/coffee-script-1.7.1.min.js"); } else/*from w w w. ja v a2 s. co m*/ inputStream = coffeeJs.openConnection().getInputStream(); try { 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); } 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 } }