List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:com.clican.pluto.common.resource.MapResource.java
private void setResource(Resource resource) { Reader reader = null; try {/*from ww w. j ava 2s . c o m*/ reader = new InputStreamReader(resource.getInputStream(), "utf-8"); load(reader); } catch (Exception e) { log.error("", e); throw new RuntimeException(e); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } }
From source file:com.matthewmitchell.nubits_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null; try {/*from w ww . ja va 2s.co m*/ connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:jfix.util.Urls.java
/** * Returns content from given url as string. The url can contain * username:password after the protocol, so that basic authorization is * possible./*ww w.j a v a2 s . c o m*/ * * Example for url with basic authorization: * * http://username:password@www.domain.org/index.html */ public static String readString(String url, int timeout) { Reader reader = null; try { URLConnection uc = new URL(url).openConnection(); if (uc instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) uc; httpConnection.setConnectTimeout(timeout * 1000); httpConnection.setReadTimeout(timeout * 1000); } Matcher matcher = Pattern.compile("://(\\w+:\\w+)@").matcher(url); if (matcher.find()) { String auth = matcher.group(1); String encoding = Base64.getEncoder().encodeToString(auth.getBytes()); uc.setRequestProperty("Authorization", "Basic " + encoding); } String charset = (uc.getContentType() != null && uc.getContentType().contains("charset=")) ? uc.getContentType().split("charset=")[1] : "utf-8"; reader = new BufferedReader(new InputStreamReader(uc.getInputStream(), charset)); StringBuilder sb = new StringBuilder(); for (int chr; (chr = reader.read()) != -1;) { sb.append((char) chr); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } }
From source file:com.lexicalintelligence.admin.save.SaveRequest.java
public SaveResponse execute() { SaveResponse saveResponse;/*from www. j a v a2 s. co m*/ Reader reader = null; try { HttpResponse response = client.getHttpClient().execute(new HttpGet(client.getUrl() + PATH + getPath())); reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8); saveResponse = new SaveResponse(Boolean.valueOf(IOUtils.toString(reader))); } catch (Exception e) { saveResponse = new SaveResponse(false); log.error(e); } finally { try { reader.close(); } catch (Exception e) { log.error(e); } } return saveResponse; }
From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null; try {/*w w w.j a v a2s . co m*/ connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, BTCE_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + BTCE_URL, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java
protected DesignMetadata readMetaData() throws FileNotFoundException, IOException, InstantiationException, IllegalAccessException, WGDesignSyncException { FileObject metadataFile = getMetadataFile(); // If not exists we return a default if (!metadataFile.exists()) { return createDefaultMetadata(); }/*from w ww . j a v a 2s. com*/ // If the file exists, but is empty, we put default metadata information into it if (metadataFile.getContent().getSize() == 0) { createMetadataFile(metadataFile); } String metaXML; Reader reader = createReader(metadataFile); try { metaXML = WGUtils.readString(reader); } finally { reader.close(); metadataFile.close(); } DesignMetadata metaData; if (metaXML.trim().equals("")) { createMetadataFile(metadataFile); metaData = createDefaultMetadata(); } else { DesignMetadataInfo info = (DesignMetadataInfo) DesignSyncManager.getXstream().fromXML(metaXML); if (info instanceof TMLMetadataInfo) { metaData = new TMLMetadata(); } else if (info instanceof FCMetadataInfo) { metaData = new FCMetadata(); } else if (info instanceof ScriptMetadataInfo) { metaData = new ScriptMetadata(); } else { metaData = new DesignMetadata(); } metaData.setInfo(info); } return metaData; }
From source file:co.cask.cdap.gateway.handlers.metrics.MetricsDiscoveryQueryTest.java
@Test public void testFilters() throws Exception { JsonArray expected = new JsonArray(); JsonArray contexts = children(node("app", "WordCount", children(node("flow", "WordCounter", children(node("flowlet", "splitter")))))); JsonObject expectedReads = new JsonObject(); expectedReads.addProperty("metric", "reads"); expectedReads.add("contexts", contexts); expected.add(expectedReads);/* www . j a v a2 s. c o m*/ expected.add(expectedWrites()); HttpResponse response = doGet("/v2/metrics/available/apps/WordCount/flows/WordCounter/flowlets/splitter"); Reader reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8); try { Assert.assertEquals("did not return 200 status.", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); JsonArray json = new Gson().fromJson(reader, JsonArray.class); Assert.assertEquals(expected, json); } finally { reader.close(); } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public static void writeFile(File file, String content, String author, Map<String, Object> jalopySettings) throws IOException { String packagePath = "com/krawler/esp/hibernate/impl";//_getPackagePath(file); String className = file.getName(); className = className.substring(0, className.length() - 5); content = SourceFormatter.stripImports(content, packagePath, className); File tempFile = new File("ServiceBuilder.temp"); Writer output = new BufferedWriter(new FileWriter(tempFile)); output.write(content);//from ww w.j av a 2s . co m output.close(); StringBuffer sb = new StringBuffer(); Jalopy jalopy = new Jalopy(); jalopy.setFileFormat(FileFormat.UNIX); jalopy.setInput(tempFile); jalopy.setOutput(sb); // try { // Jalopy.setConvention("../tools/jalopy.xml"); // } // catch (FileNotFoundException fnne) { // System.out.print(fnne.getMessage()); // } // try { // Jalopy.setConvention("../../misc/jalopy.xml"); // } // catch (FileNotFoundException fnne) { // System.out.print(fnne.getMessage()); // } if (jalopySettings == null) { jalopySettings = new HashMap<String, Object>(); } Environment env = Environment.getInstance(); // Author author = GetterUtil.getString((String) jalopySettings.get("author"), author); env.set("author", author); // File name env.set("fileName", file.getName()); Convention convention = Convention.getInstance(); String classMask = "/**\n" + " * <a href=\"$fileName$.html\"><b><i>View Source</i></b></a>\n" + " *\n" + " * @author $author$\n" + " *\n" + "*/"; convention.put(ConventionKeys.COMMENT_JAVADOC_TEMPLATE_CLASS, env.interpolate(classMask)); convention.put(ConventionKeys.COMMENT_JAVADOC_TEMPLATE_INTERFACE, env.interpolate(classMask)); jalopy.format(); String newContent = sb.toString(); /* // Remove blank lines after try { newContent = StringUtil.replace(newContent, "try {\n\n", "try {\n"); // Remove blank lines after ) { newContent = StringUtil.replace(newContent, ") {\n\n", ") {\n"); // Remove blank lines empty braces { } newContent = StringUtil.replace(newContent, "\n\n\t}", "\n\t}"); // Add space to last } newContent = newContent.substring(0, newContent.length() - 2) + "\n\n}"; */ // Write file if and only if the file has changed String oldContent = null; if (file.exists()) { // Read file Reader reader = new BufferedReader(new FileReader(file)); CharBuffer cbuf = new CharBuffer(reader); oldContent = cbuf.toString(); reader.close(); // Keep old version number int x = oldContent.indexOf("@version $Revision:"); if (x != -1) { int y = oldContent.indexOf("$", x); y = oldContent.indexOf("$", y + 1); String oldVersion = oldContent.substring(x, y + 1); newContent = com.krawler.portal.util.StringUtil.replace(newContent, "@version $Rev: $", oldVersion); } } else { // newContent = com.krawler.portal.util.StringUtil.replace( // newContent, "@version $Rev: $", "@version $Revision: 1.183 $"); file.createNewFile(); } if (oldContent == null || !oldContent.equals(newContent)) { output = new BufferedWriter(new FileWriter(file)); output.write(content); output.close(); // FileUtil.write(file, newContent); System.out.println("Writing " + file); // Workaround for bug with XJavaDoc file.setLastModified(System.currentTimeMillis() - (Time.SECOND * 5)); } tempFile.deleteOnExit(); }
From source file:com.npower.cp.xmlinventory.OTATemplateItem.java
/** * Set the content by filename./*from www . java 2s.c om*/ * The method will be called in Common Digester * @param filename * @throws IOException */ public void setFilename(String filename) throws IOException { if (StringUtils.isEmpty(filename)) { return; } String baseDir = System.getProperty(OTAInventoryImpl.CP_TEMPLATE_RESOURCE_DIR); File file = new File(baseDir, filename); Reader reader = new FileReader(file); StringWriter writer = new StringWriter(); int c = reader.read(); while (c > 0) { writer.write(c); c = reader.read(); } this.content = writer.toString(); reader.close(); }
From source file:com.migratebird.script.repository.impl.ArchiveScriptLocation.java
/** * Creates the jar containing the scripts and stores it in the file with the given file name * * @param jarFile Path where the jar file is stored *//*from w ww .jav a2 s . c o m*/ public void writeToJarFile(File jarFile) { JarOutputStream jarOutputStream = null; try { jarOutputStream = new JarOutputStream(new FileOutputStream(jarFile)); Reader propertiesAsFile = getPropertiesAsFile(getJarProperties()); writeJarEntry(jarOutputStream, LOCATION_PROPERTIES_FILENAME, System.currentTimeMillis(), propertiesAsFile); propertiesAsFile.close(); for (Script script : getScripts()) { Reader scriptContentReader = null; try { scriptContentReader = script.getScriptContentHandle().openScriptContentReader(); writeJarEntry(jarOutputStream, script.getFileName(), script.getFileLastModifiedAt(), scriptContentReader); } finally { closeQuietly(scriptContentReader); } } } catch (IOException e) { throw new MigrateBirdException("Error while writing archive file " + jarFile, e); } finally { closeQuietly(jarOutputStream); } }