List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getLitecoinChartsOld() { final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the BTC rate around for a bit Double ltcRate = getGoldCoinValueLTC(); Double btcRate = 0.0;/* w ww.ja v a 2 s .com*/ try { String currencies[] = { "USD", "BTC" };//, "RUR"}; String urls[] = { "https://btc-e.com/api/2/14/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker" }; for (int i = 0; i < currencies.length; ++i) { final String currencyCode = currencies[i]; final URL URL = new URL(urls[i]); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg") * ltcRate; String euros = String.format("%.7f", avg); // Fix things like 3,1250 euros = euros.replace(",", "."); rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost())); if (currencyCode.equalsIgnoreCase("BTC")) btcRate = avg; } finally { if (reader != null) reader.close(); } } // Handle LTC/EUR special since we have to do maths final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker"); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is bitcoins priced in euros. We want GLD! avg *= btcRate; String s_avg = String.format("%.8f", avg).replace(',', '.'); rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost())); //Add LTC information s_avg = String.format("%.8f", ltcRate); rates.put("LTC", new ExchangeRate("LTC", Utils.toNanoCoins(s_avg.replace(",", ".")), URL.getHost())); } finally { if (reader != null) reader.close(); } return rates; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:edu.ucsd.sbrg.escher.utilities.EscherParser.java
/** * @param inputStream//from w w w . j a v a 2 s. c o m * @param defaultMapId * @return * @throws IOException * @throws ParseException */ public EscherMap parse(InputStream inputStream, String defaultMapId) throws IOException, ParseException { // Read JSON file JSONParser parser = new JSONParser(); Reader reader = new BufferedReader(new InputStreamReader(inputStream)); Object obj = parser.parse(reader); reader.close(); if (!(obj instanceof JSONArray)) { logger.warning(MessageFormat.format(bundle.getString("EscherParser.JSONObjectExpected"), obj, obj.getClass().getName(), JSONArray.class.getName())); return null; } JSONArray json = (JSONArray) obj; JSONObject map = (JSONObject) json.get(0); /* * Create the EscherMap object. */ EscherMap escherMap = new EscherMap(); Object id = map.get(EscherKeywords.map_id.name()); escherMap.setId(id != null ? id.toString() : defaultMapId); escherMap.setName(map.get(EscherKeywords.map_name.name()).toString()); escherMap.setDescription(map.get(EscherKeywords.map_description.name()).toString()); escherMap.setSchema(map.get(EscherKeywords.schema.name()).toString()); escherMap.setURL(map.get(EscherKeywords.homepage.name()).toString()); JSONObject parts = (JSONObject) json.get(1); Canvas canvas = parseCanvas((JSONObject) parts.get(EscherKeywords.canvas.name())); escherMap.setCanvas(canvas); /* * Nodes */ JSONObject mapNode = (JSONObject) parts.get(EscherKeywords.nodes.name()); if (mapNode != null) { for (Object object : mapNode.keySet()) { Node node = parseNode(object, (JSONObject) mapNode.get(object)); escherMap.addNode(node); if (node.isSetCompartment()) { try { EscherCompartment compartment = escherMap.getCompartment(node.getCompartment()); double x = node.getX(); // - node.getWidth()/2d; double y = node.getY(); // - node.getHeight()/2d; if (compartment == null) { compartment = new EscherCompartment(); compartment.setId(node.getCompartment()); compartment.setX(x); compartment.setY(y); compartment.setWidth(0d); //node.getWidth()); compartment.setHeight(0d); //node.getHeight()); escherMap.addCompartment(compartment); } else { if (x < compartment.getX()) { compartment.setX(x); } else if (x /*+ node.getWidth()*/ > compartment.getX() + compartment.getWidth()) { compartment.setWidth(x /* + node.getWidth()*/); } if (y < compartment.getY()) { compartment.setY(y); } else if (y /*+ node.getHeight()*/ > compartment.getY() + compartment.getHeight()) { compartment.setHeight(y /* + node.getHeight()*/); } } } catch (Throwable t) { t.printStackTrace(); } } } } /* * Reactions */ JSONObject mapReactions = (JSONObject) parts.get(EscherKeywords.reactions.name()); if (mapReactions != null) { for (Object object : mapReactions.keySet()) { for (EscherReaction reaction : parseReaction(object, (JSONObject) mapReactions.get(object), escherMap)) { escherMap.addReaction(reaction); } } } /* * Labels */ JSONObject mapText = (JSONObject) parts.get(EscherKeywords.text_labels.name()); if (mapText != null) { for (Object object : mapText.keySet()) { escherMap.addTextLabel(parseTextLabel(object, (JSONObject) mapText.get(object))); } } return escherMap; }
From source file:com.cdd.bao.importer.KeywordMapping.java
public KeywordMapping(String mapFN) { file = new File(mapFN); // try to load the file, but it's OK if it fails JSONObject json = null;//from www .j av a 2 s . c o m try { Reader rdr = new FileReader(file); json = new JSONObject(new JSONTokener(rdr)); rdr.close(); } catch (JSONException ex) { Util.writeln("NOTE: reading file " + file.getAbsolutePath() + " failed: " + ex.getMessage()); } catch (IOException ex) { return; } // includes file not found, which is OK try { for (JSONObject obj : json.optJSONArrayEmpty("identifiers").toObjectArray()) { Identifier id = new Identifier(); id.regex = regexOrName(obj.optString("regex"), obj.optString("name")); id.prefix = obj.optString("prefix"); identifiers.add(id); } for (JSONObject obj : json.optJSONArrayEmpty("textBlocks").toObjectArray()) { TextBlock txt = new TextBlock(); txt.regex = regexOrName(obj.optString("regex"), obj.optString("name")); txt.title = obj.optString("title"); textBlocks.add(txt); } for (JSONObject obj : json.optJSONArrayEmpty("properties").toObjectArray()) { Property prop = new Property(); prop.regex = regexOrName(obj.optString("regex"), obj.optString("name")); prop.propURI = obj.optString("propURI"); prop.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray(); properties.add(prop); } for (JSONObject obj : json.optJSONArrayEmpty("values").toObjectArray()) { Value val = new Value(); val.regex = regexOrName(obj.optString("regex"), obj.optString("name")); val.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName")); val.valueURI = obj.optString("valueURI"); val.propURI = obj.optString("propURI"); val.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray(); values.add(val); } for (JSONObject obj : json.optJSONArrayEmpty("literals").toObjectArray()) { Literal lit = new Literal(); lit.regex = regexOrName(obj.optString("regex"), obj.optString("name")); lit.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName")); lit.propURI = obj.optString("propURI"); lit.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray(); literals.add(lit); } for (JSONObject obj : json.optJSONArrayEmpty("references").toObjectArray()) { Reference ref = new Reference(); ref.regex = regexOrName(obj.optString("regex"), obj.optString("name")); ref.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName")); ref.prefix = obj.optString("prefix"); ref.propURI = obj.optString("propURI"); ref.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray(); references.add(ref); } for (JSONObject obj : json.optJSONArrayEmpty("assertions").toObjectArray()) { Assertion asrt = new Assertion(); asrt.propURI = obj.optString("propURI"); asrt.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray(); asrt.valueURI = obj.optString("valueURI"); assertions.add(asrt); } } catch (JSONException ex) { Util.writeln("NOTE: parsing error"); ex.printStackTrace(); Util.writeln( "*** Execution will continue, but part of the mapping has not been loaded and may be overwritten."); } }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getLitecoinCharts() { final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the BTC rate around for a bit Double btcRate = 0.0;// w w w .j ava 2 s . c o m Object result = getGoldCoinValueBTC(); if (result == null) { return null; } else btcRate = (Double) result; //Double btcRate = 0.0; try { rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com")); String currencies[] = { "USD" };//, "BTC"};//, "RUR"}; String urls[] = { "https://btc-e.com/api/2/1/ticker" };//, "https://btc-e.com/api/2/14/ticker", "https://btc-e.com/api/2/ltc_rur/ticker"}; for (int i = 0; i < currencies.length; ++i) { final String currencyCode = currencies[i]; final URL URL = new URL(urls[i]); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg") * btcRate; String euros = String.format("%.8f", avg); // Fix things like 3,1250 euros = euros.replace(",", "."); rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost())); if (currencyCode.equalsIgnoreCase("BTC")) btcRate = avg; } finally { if (reader != null) reader.close(); } } // Handle LTC/EUR special since we have to do maths final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker"); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is bitcoins priced in euros. We want GLD! avg *= btcRate; String s_avg = String.format("%.8f", avg).replace(',', '.'); rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost())); //Add LTC information //s_avg = String.format("%.8f", ltcRate); //rates.put("LTC", new ExchangeRate("LTC", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } return rates; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:xdroid.ui.core.cache.LruDiskCache.java
private static String readFully(Reader reader) throws IOException { StringWriter writer = null;//from ww w. j a v a 2 s .c o m try { writer = new StringWriter(); char[] buffer = new char[1024]; int count; while ((count = reader.read(buffer)) != -1) { writer.write(buffer, 0, count); } return writer.toString(); } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (Exception e) { // TODO: handle exception } } }
From source file:com.cdd.bao.importer.ImportControlledVocab.java
public void exec() throws IOException, JSONException { File f = new File(srcFN); if (!f.exists()) throw new IOException("Source file not found: " + f.getCanonicalPath()); Reader rdr = new FileReader(srcFN); JSONObject json = new JSONObject(new JSONTokener(rdr)); rdr.close(); if (!json.has("columns") || !json.has("rows")) throw new IOException("Source JSON must have 'columns' and 'rows'."); srcColumns = json.getJSONArray("columns"); srcRows = json.getJSONArray("rows"); map = new KeywordMapping(mapFN); Util.writeln("Mapping file:"); Util.writeln(" # identifiers = " + map.identifiers.size()); Util.writeln(" # textblocks = " + map.textBlocks.size()); Util.writeln(" # properties = " + map.properties.size()); Util.writeln(" # values = " + map.values.size()); Util.writeln(" # literals = " + map.literals.size()); Util.writeln(" # references = " + map.references.size()); Util.writeln(" # assertions = " + map.assertions.size()); schema = ModelSchema.deserialise(new File(schemaFN)); assignments = schema.getRoot().flattenedAssignments(); InputStream istr = new FileInputStream(vocabFN); schvoc = SchemaVocab.deserialise(istr, new Schema[] { schema }); istr.close();//w w w . j a v a 2 s. c o m for (SchemaVocab.StoredTree stored : schvoc.getTrees()) treeCache.put(stored.assignment, stored.tree); if (hintFN != null) { rdr = new FileReader(hintFN); JSONObject jsonHints = new JSONObject(new JSONTokener(rdr)); rdr.close(); for (String key : jsonHints.keySet()) { String uri = ModelSchema.expandPrefix(jsonHints.getString(key)); hints.put(key, uri); invHints.put(uri, ArrayUtils.add(invHints.get(uri), key)); } Util.writeln(" # hints = " + hints.size()); } checkMappingProperties(); for (int n = 0; n < srcColumns.length(); n++) matchColumn(srcColumns.getString(n)); for (int n = 0; n < srcRows.length(); n++) { Util.writeln("---- Row#" + (n + 1) + " ----"); JSONObject row = srcRows.getJSONObject(n); for (String key : row.keySet()) { if (map.findIdentifier(key) != null) continue; Property prop = map.findProperty(key); if (prop == null || Util.isBlank(prop.propURI)) continue; // passed on the opportunity to map String val = row.optString(key, ""); if (map.findValue(key, val) != null || map.findLiteral(key, val) != null || map.findReference(key, val) != null) continue; // already mapped matchValue(prop, key, val); } } Util.writeln("Saving mapping file..."); map.save(); writeMappedAssays(); Util.writeln("Done."); }
From source file:de.codesourcery.eve.skills.ui.config.AppConfig.java
public void load() throws IOException { log.debug("load(): Loading app config from " + file); if (file.exists()) { final Properties props = new Properties(); final Reader instream = new FileReader(file); try {/*from w w w . j a v a 2 s . com*/ props.load(instream); clear(); setDefaults(); for (String key : props.stringPropertyNames()) { put(key, (String) props.get(key)); } } finally { instream.close(); } } }
From source file:gate.crowdsource.rest.CrowdFlowerClient.java
protected JsonElement request(String method, String uri, String... formData) throws IOException { if (log.isDebugEnabled()) { log.debug("URI: " + uri + ", formData: " + Arrays.toString(formData)); }//w w w . j a va 2 s . co m URL cfUrl = new URL(CF_ENDPOINT + uri + "?key=" + apiKey); HttpURLConnection connection = (HttpURLConnection) cfUrl.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Accept", "application/json"); if (formData != null && formData.length > 0) { // send the form data, URL encoded connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // annoyingly CrowdFlower doesn't support chunked streaming of // POSTs so we have to accumulate the content in a buffer, work // out its size and then POST with a Content-Length header ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096); PrintWriter writer = new PrintWriter(new OutputStreamWriter(buffer, "UTF-8")); try { for (int i = 0; i < formData.length; i++) { String fieldName = formData[i]; String fieldValue = formData[++i]; if (i > 0) { writer.write("&"); } writer.write(URLEncoder.encode(fieldName, "UTF-8")); writer.write("="); writer.write(URLEncoder.encode(fieldValue, "UTF-8")); } } finally { writer.close(); } connection.setFixedLengthStreamingMode(buffer.size()); OutputStream connectionStream = connection.getOutputStream(); buffer.writeTo(connectionStream); connectionStream.close(); } // parse the response as JSON JsonParser parser = new JsonParser(); Reader responseReader = new InputStreamReader(connection.getInputStream(), "UTF-8"); try { return parser.parse(responseReader); } finally { responseReader.close(); } }
From source file:net.solarnetwork.node.setup.auto.SettingsImporter.java
/** * Attempt to load the {@code settingsResource}. Does not throw any * exceptions if the resource is not available or cannot be read. *//*from w w w. j a va 2 s.c o m*/ public void loadSettings() { if (settingsResource == null) { return; } Reader in = null; try { in = new InputStreamReader(settingsResource.getInputStream(), "UTF-8"); log.info("Auto-importing settings from {}", settingsResource); SettingsImportOptions options = new SettingsImportOptions(); options.setAddOnly(true); if (settingsService != null) { settingsService.importSettingsCSV(in, options); } } catch (Exception e) { log.warn("Error importing settings resource {}: {}", settingsResource, e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore this } } } }
From source file:de.uzk.hki.da.metadata.LidoMetadataStructure.java
/** * Append to each administrativeMetadata in a Lido-File one RightsResourceType-Element and save it. * /*from ww w .j a va 2s .c o m*/ * @param targetLidoFile * @param licenseHref * @param displayLabel * @param text * @throws IOException * @throws JDOMException */ public void appendRightsResource(File targetLidoFile, String licenseHref, String displayLabel) throws IOException, JDOMException { SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder(); FileInputStream fileInputStream = new FileInputStream(Path.makeFile(workPath, targetLidoFile.getPath())); BOMInputStream bomInputStream = new BOMInputStream(fileInputStream); Reader reader = new InputStreamReader(bomInputStream, "UTF-8"); InputSource is = new InputSource(reader); is.setEncoding("UTF-8"); Document lidoDoc = builder.build(is); List<Element> lidoElems = lidoDoc.getRootElement().getChildren("lido", C.LIDO_NS); for (int i = 0; i < lidoElems.size(); i++) { appendRightsResourceToLido(lidoElems.get(i), licenseHref, displayLabel); } fileInputStream.close(); bomInputStream.close(); reader.close(); writeDocumentToFile(lidoDoc, Path.makeFile(workPath, targetLidoFile.getPath())); }