List of usage examples for java.io InputStreamReader close
public void close() throws IOException
From source file:com.breadwallet.tools.util.JsonParser.java
private static String callURL(String myURL) { // System.out.println("Requested URL_EA:" + myURL); StringBuilder sb = new StringBuilder(); HttpURLConnection urlConn = null; InputStreamReader in = null; try {//from w w w . jav a 2 s. co m URL url = new URL(myURL); urlConn = (HttpURLConnection) url.openConnection(); int versionNumber = 0; MainActivity app = MainActivity.app; if (app != null) { try { PackageInfo pInfo = null; pInfo = app.getPackageManager().getPackageInfo(app.getPackageName(), 0); versionNumber = pInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } int stringId = 0; String appName = ""; if (app != null) { stringId = app.getApplicationInfo().labelRes; appName = app.getString(stringId); } String message = String.format(Locale.getDefault(), "%s/%d/%s", appName.isEmpty() ? "breadwallet" : appName, versionNumber, System.getProperty("http.agent")); urlConn.setRequestProperty("User-agent", message); urlConn.setReadTimeout(60 * 1000); String strDate = urlConn.getHeaderField("date"); if (strDate == null || app == null) { Log.e(TAG, "callURL: strDate == null!!!"); } else { @SuppressWarnings("deprecation") long date = Date.parse(strDate) / 1000; SharedPreferencesManager.putSecureTime(app, date); Assert.assertTrue(date != 0); } if (urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } assert in != null; in.close(); } catch (Exception e) { return null; } return sb.toString(); }
From source file:cn.leancloud.diamond.client.processor.ServerAddressProcessor.java
void reloadServerAddresses() { FileInputStream fis = null;/*from ww w.j a va 2 s . c o m*/ InputStreamReader reader = null; BufferedReader bufferedReader = null; try { File serverAddressFile = new File( generateLocalFilePath(this.diamondConfigure.getFilePath(), "ServerAddress")); if (!serverAddressFile.exists()) { return; } fis = new FileInputStream(serverAddressFile); reader = new InputStreamReader(fis); bufferedReader = new BufferedReader(reader); String address = null; while ((address = bufferedReader.readLine()) != null) { address = address.trim(); if (StringUtils.isNotBlank(address)) { diamondConfigure.getDomainNameList().add(address); } } bufferedReader.close(); reader.close(); fis.close(); } catch (Exception e) { log.error("???", e); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception e) { } } if (reader != null) { try { reader.close(); } catch (Exception e) { } } if (fis != null) { try { fis.close(); } catch (Exception e) { } } } }
From source file:com.farmerbb.notepad.activity.MainActivity.java
public String loadNote(String filename) throws IOException { // Initialize StringBuilder which will contain note StringBuilder note = new StringBuilder(); // Open the file on disk FileInputStream input = openFileInput(filename); InputStreamReader reader = new InputStreamReader(input); BufferedReader buffer = new BufferedReader(reader); // Load the file String line = buffer.readLine(); while (line != null) { note.append(line);/*from ww w . java 2s .co m*/ line = buffer.readLine(); if (line != null) note.append("\n"); } // Close file on disk reader.close(); return (note.toString()); }
From source file:com.codelanx.playtime.update.UpdateHandler.java
/** * Gets the {@link JSONObject} from the CurseAPI of the newest project version. * /* w w w. j ava 2 s .c o m*/ * @since 1.4.5 * @version 1.4.5 */ private void getJSON() { InputStream stream = null; InputStreamReader isr = null; BufferedReader reader = null; String json = null; try { URL call = new URL(this.VERSION_URL); stream = call.openStream(); isr = new InputStreamReader(stream); reader = new BufferedReader(isr); json = reader.readLine(); } catch (MalformedURLException ex) { plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : ""); this.result = Result.ERROR_BADID; this.latest = null; } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : ""); } finally { try { if (stream != null) { stream.close(); } if (isr != null) { isr.close(); } if (reader != null) { reader.close(); } } catch (IOException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error closing updater streams!", this.debug >= 3 ? ex : ""); } } if (json != null) { JSONArray arr = (JSONArray) JSONValue.parse(json); this.latest = (JSONObject) arr.get(arr.size() - 1); } else { this.latest = null; } }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param stream//from w w w .ja v a 2 s . c o m * @return * @throws IOException */ private String readStream(final InputStream stream) throws IOException { InputStreamReader reader = null; try { int count = 0; final char[] c = new char[BUFSIZE]; reader = new InputStreamReader(stream, GlobalConstants.UTF_8); if ((count = reader.read(c)) > 0) { final StringBuilder sb = new StringBuilder(STRBLD_SIZE); do { sb.append(c, 0, count); } while ((count = reader.read(c)) > 0); return sb.toString(); } return ""; } finally { if (null != reader) { try { reader.close(); } catch (final IOException e) { e.printStackTrace(); } } } }
From source file:com.allblacks.utils.web.HttpUtil.java
/** * Gets data from URL as String throws {@link RuntimeException} If anything * goes wrong/*from w w w .ja v a 2 s. co m*/ * * @return The content of the URL as a String * @throws java.io.IOException */ public String getDataAsString(String url) throws IOException { URLConnection urlc = null; InputStream is = null; InputStreamReader re = null; BufferedReader rd = null; String responseBody = ""; try { urlc = getConnection(new URL(url)); if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) { is = new GZIPInputStream(urlc.getInputStream()); } else { is = urlc.getInputStream(); } re = new InputStreamReader(is, Charset.forName(HttpUtil.UTF_8)); rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += HttpUtil.NL; line = null; } } catch (IOException exception) { throw exception; } finally { try { rd.close(); re.close(); } catch (Exception e) { // we do not care about this } } return responseBody; }
From source file:uta.ak.usttmp.common.textmining.FileExcludeStopWord.java
public FileExcludeStopWord() { //Load stopword file InputStreamReader isr = null; try {// ww w. j a v a2s.c o m stopWordsList = new CopyOnWriteArraySet<>(); Resource res = new ClassPathResource("StopWordTable2.txt"); // File stopwords=res.getFile(); // File stopwords=new File("/Users/zhangcong/dev/corpus/StopWordTable2.txt"); isr = new InputStreamReader(res.getInputStream()); BufferedReader stops = null; try { String tempString = null; stops = new BufferedReader(isr); tempString = stops.readLine(); while ((tempString = stops.readLine()) != null) { if (!tempString.isEmpty()) { stopWordsList.add(tempString.toLowerCase().trim()); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException ex) { Logger.getLogger(FileExcludeStopWord.class.getName()).log(Level.SEVERE, null, ex); } finally { try { isr.close(); } catch (IOException ex) { Logger.getLogger(FileExcludeStopWord.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.gamingmesh.jobs.config.JobConfig.java
/** * Method to load the jobs configuration * //ww w. j a va2 s. c o m * loads from Jobs/jobConfig.yml * @throws IOException */ @SuppressWarnings("deprecation") private void loadJobSettings() throws IOException { File f = new File(plugin.getDataFolder(), "jobConfig.yml"); InputStreamReader s = new InputStreamReader(new FileInputStream(f), "UTF-8"); ArrayList<Job> jobs = new ArrayList<Job>(); Jobs.setJobs(jobs); Jobs.setNoneJob(null); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { Jobs.getPluginLogger().severe("Unable to create jobConfig.yml! No jobs were loaded!"); s.close(); return; } } YamlConfiguration conf = new YamlConfiguration(); conf.options().pathSeparator('/'); try { conf.load(s); s.close(); } catch (Exception e) { Bukkit.getServer().getLogger().severe("==================== Jobs ===================="); Bukkit.getServer().getLogger().severe("Unable to load jobConfig.yml!"); Bukkit.getServer().getLogger().severe("Check your config for formatting issues!"); Bukkit.getServer().getLogger().severe("No jobs were loaded!"); Bukkit.getServer().getLogger().severe("Error: " + e.getMessage()); Bukkit.getServer().getLogger().severe("=============================================="); return; } //conf.options().header(new StringBuilder().append("Jobs configuration.").append(System.getProperty("line.separator")).append(System.getProperty("line.separator")).append("Stores information about each job.").append(System.getProperty("line.separator")).append(System.getProperty("line.separator")).append("For example configurations, visit http://dev.bukkit.org/bukkit-plugins/jobs-reborn/.").append(System.getProperty("line.separator")).toString()); ConfigurationSection jobsSection = conf.getConfigurationSection("Jobs"); //if (jobsSection == null) { // jobsSection = conf.createSection("Jobs"); //} for (String jobKey : jobsSection.getKeys(false)) { ConfigurationSection jobSection = jobsSection.getConfigurationSection(jobKey); String jobName = jobSection.getString("fullname"); // Translating unicode jobName = StringEscapeUtils.unescapeJava(jobName); if (jobName == null) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid fullname property. Skipping job!"); continue; } int maxLevel = jobSection.getInt("max-level", 0); if (maxLevel < 0) maxLevel = 0; int vipmaxLevel = jobSection.getInt("vip-max-level", 0); if (vipmaxLevel < 0) vipmaxLevel = 0; Integer maxSlots = jobSection.getInt("slots", 0); if (maxSlots.intValue() <= 0) { maxSlots = null; } String jobShortName = jobSection.getString("shortname"); if (jobShortName == null) { Jobs.getPluginLogger() .warning("Job " + jobKey + " is missing the shortname property. Skipping job!"); continue; } String description = org.bukkit.ChatColor.translateAlternateColorCodes('&', jobSection.getString("description", "")); ChatColor color = ChatColor.WHITE; if (jobSection.contains("ChatColour")) { color = ChatColor.matchColor(jobSection.getString("ChatColour", "")); if (color == null) { color = ChatColor.WHITE; Jobs.getPluginLogger().warning( "Job " + jobKey + " has an invalid ChatColour property. Defaulting to WHITE!"); } } DisplayMethod displayMethod = DisplayMethod.matchMethod(jobSection.getString("chat-display", "")); if (displayMethod == null) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid chat-display property. Defaulting to None!"); displayMethod = DisplayMethod.NONE; } Parser maxExpEquation; String maxExpEquationInput = jobSection.getString("leveling-progression-equation"); try { maxExpEquation = new Parser(maxExpEquationInput); // test equation maxExpEquation.setVariable("numjobs", 1); maxExpEquation.setVariable("joblevel", 1); maxExpEquation.getValue(); } catch (Exception e) { Jobs.getPluginLogger().warning( "Job " + jobKey + " has an invalid leveling-progression-equation property. Skipping job!"); continue; } Parser incomeEquation; String incomeEquationInput = jobSection.getString("income-progression-equation"); try { incomeEquation = new Parser(incomeEquationInput); // test equation incomeEquation.setVariable("numjobs", 1); incomeEquation.setVariable("joblevel", 1); incomeEquation.setVariable("baseincome", 1); incomeEquation.getValue(); } catch (Exception e) { Jobs.getPluginLogger().warning( "Job " + jobKey + " has an invalid income-progression-equation property. Skipping job!"); continue; } Parser expEquation; String expEquationInput = jobSection.getString("experience-progression-equation"); try { expEquation = new Parser(expEquationInput); // test equation expEquation.setVariable("numjobs", 1); expEquation.setVariable("joblevel", 1); expEquation.setVariable("baseexperience", 1); expEquation.getValue(); } catch (Exception e) { Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid experience-progression-equation property. Skipping job!"); continue; } // Gui item ItemStack GUIitem = new ItemStack(Material.getMaterial(35), 1, (byte) 13); if (jobSection.contains("Gui")) { ConfigurationSection guiSection = jobSection.getConfigurationSection("Gui"); if (guiSection.contains("Id") && guiSection.contains("Data") && guiSection.isInt("Id") && guiSection.isInt("Data")) { GUIitem = new ItemStack(Material.getMaterial(guiSection.getInt("Id")), 1, (byte) guiSection.getInt("Data")); } else Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid Gui property. Please fix this if you want to use it!"); } // Permissions ArrayList<JobPermission> jobPermissions = new ArrayList<JobPermission>(); ConfigurationSection permissionsSection = jobSection.getConfigurationSection("permissions"); if (permissionsSection != null) { for (String permissionKey : permissionsSection.getKeys(false)) { ConfigurationSection permissionSection = permissionsSection .getConfigurationSection(permissionKey); String node = permissionKey.toLowerCase(); if (permissionSection == null) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid permission key" + permissionKey + "!"); continue; } boolean value = permissionSection.getBoolean("value", true); int levelRequirement = permissionSection.getInt("level", 0); jobPermissions.add(new JobPermission(node, value, levelRequirement)); } } // Conditions ArrayList<JobConditions> jobConditions = new ArrayList<JobConditions>(); ConfigurationSection conditionsSection = jobSection.getConfigurationSection("conditions"); if (conditionsSection != null) { for (String ConditionKey : conditionsSection.getKeys(false)) { ConfigurationSection permissionSection = conditionsSection .getConfigurationSection(ConditionKey); String node = ConditionKey.toLowerCase(); if (permissionSection == null) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid condition key " + ConditionKey + "!"); continue; } if (!permissionSection.contains("requires") || !permissionSection.contains("perform")) { Jobs.getPluginLogger().warning( "Job " + jobKey + " has an invalid condition requirement " + ConditionKey + "!"); continue; } List<String> requires = permissionSection.getStringList("requires"); List<String> perform = permissionSection.getStringList("perform"); jobConditions.add(new JobConditions(node, requires, perform)); } } // Command on leave List<String> JobsCommandOnLeave = new ArrayList<String>(); if (jobSection.isList("cmd-on-leave")) { JobsCommandOnLeave = jobSection.getStringList("cmd-on-leave"); } // Command on join List<String> JobsCommandOnJoin = new ArrayList<String>(); if (jobSection.isList("cmd-on-join")) { JobsCommandOnJoin = jobSection.getStringList("cmd-on-join"); } // Commands ArrayList<JobCommands> jobCommand = new ArrayList<JobCommands>(); ConfigurationSection commandsSection = jobSection.getConfigurationSection("commands"); if (commandsSection != null) { for (String commandKey : commandsSection.getKeys(false)) { ConfigurationSection commandSection = commandsSection.getConfigurationSection(commandKey); String node = commandKey.toLowerCase(); if (commandSection == null) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid command key" + commandKey + "!"); continue; } String command = commandSection.getString("command"); int levelFrom = commandSection.getInt("levelFrom"); int levelUntil = commandSection.getInt("levelUntil"); jobCommand.add(new JobCommands(node, command, levelFrom, levelUntil)); } } // Items ArrayList<JobItems> jobItems = new ArrayList<JobItems>(); ConfigurationSection itemsSection = jobSection.getConfigurationSection("items"); if (itemsSection != null) { for (String itemKey : itemsSection.getKeys(false)) { ConfigurationSection itemSection = itemsSection.getConfigurationSection(itemKey); String node = itemKey.toLowerCase(); if (itemSection == null) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid item key " + itemKey + "!"); continue; } int id = itemSection.getInt("id"); String name = itemSection.getString("name"); List<String> lore = new ArrayList<String>(); for (String eachLine : itemSection.getStringList("lore")) { lore.add(org.bukkit.ChatColor.translateAlternateColorCodes('&', eachLine)); } List<String> enchants = new ArrayList<String>(); if (itemSection.getStringList("enchants") != null) for (String eachLine : itemSection.getStringList("enchants")) { enchants.add(eachLine); } Double moneyBoost = itemSection.getDouble("moneyBoost"); Double expBoost = itemSection.getDouble("expBoost"); jobItems.add(new JobItems(node, id, name, lore, enchants, moneyBoost, expBoost)); } } Job job = new Job(jobName, jobShortName, description, color, maxExpEquation, displayMethod, maxLevel, vipmaxLevel, maxSlots, jobPermissions, jobCommand, jobConditions, jobItems, JobsCommandOnJoin, JobsCommandOnLeave, GUIitem); for (ActionType actionType : ActionType.values()) { ConfigurationSection typeSection = jobSection.getConfigurationSection(actionType.getName()); ArrayList<JobInfo> jobInfo = new ArrayList<JobInfo>(); if (typeSection != null) { for (String key : typeSection.getKeys(false)) { ConfigurationSection section = typeSection.getConfigurationSection(key); String myKey = key; String type = null; String subType = ""; String meta = ""; int id = 0; if (myKey.contains("-")) { // uses subType subType = ":" + myKey.split("-")[1]; meta = myKey.split("-")[1]; myKey = myKey.split("-")[0]; } Material material = Material.matchMaterial(myKey); if (material == null) material = Material.getMaterial(myKey.replace(" ", "_").toUpperCase()); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.valueOf(myKey); } catch (NumberFormatException e) { } if (matId != null) { material = Material.getMaterial(matId); if (material != null) { Jobs.getPluginLogger().warning("Job " + jobKey + " " + actionType.getName() + " is using ID: " + key + "!"); Jobs.getPluginLogger().warning( "Please use the Material name instead: " + material.toString() + "!"); } } } if (material != null) { // Break and Place actions MUST be blocks if (actionType == ActionType.BREAK || actionType == ActionType.PLACE) { if (!material.isBlock()) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + "! Material must be a block!"); continue; } } // START HACK /* * Historically, GLOWING_REDSTONE_ORE would ONLY work as REDSTONE_ORE, and putting * GLOWING_REDSTONE_ORE in the configuration would not work. Unfortunately, this is * completely backwards and wrong. * * To maintain backwards compatibility, all instances of REDSTONE_ORE should normalize * to GLOWING_REDSTONE_ORE, and warn the user to change their configuration. In the * future this hack may be removed and anybody using REDSTONE_ORE will have their * configurations broken. */ if (material == Material.REDSTONE_ORE && actionType == ActionType.BREAK) { Jobs.getPluginLogger().warning("Job " + jobKey + " is using REDSTONE_ORE instead of GLOWING_REDSTONE_ORE."); Jobs.getPluginLogger().warning( "Automatically changing block to GLOWING_REDSTONE_ORE. Please update your configuration."); Jobs.getPluginLogger().warning( "In vanilla minecraft, REDSTONE_ORE changes to GLOWING_REDSTONE_ORE when interacted with."); Jobs.getPluginLogger().warning( "In the future, Jobs using REDSTONE_ORE instead of GLOWING_REDSTONE_ORE may fail to work correctly."); material = Material.GLOWING_REDSTONE_ORE; } // END HACK type = material.toString(); id = material.getId(); } else if (actionType == ActionType.KILL || actionType == ActionType.TAME || actionType == ActionType.BREED || actionType == ActionType.MILK) { // check entities EntityType entity = EntityType.fromName(key); if (entity == null) { try { entity = EntityType.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { } } if (entity != null && entity.isAlive()) { type = entity.toString(); id = entity.getTypeId(); } // Just to recognize wither skeleton if (key.equalsIgnoreCase("WitherSkeleton")) { type = "WitherSkeleton"; id = 51; meta = "1"; } // Just to recognize Zombie Villager if (key.equalsIgnoreCase("ZombieVillager")) { type = "ZombieVillager"; id = 54; meta = "1"; } // Just to recognize Elder Guardian if (key.equalsIgnoreCase("ElderGuardian")) { type = "ElderGuardian"; id = 68; meta = "1"; } } else if (actionType == ActionType.ENCHANT && material == null) { Enchantment enchant = Enchantment.getByName(myKey); if (enchant != null) id = enchant.getId(); type = myKey; } else if (actionType == ActionType.CUSTOMKILL || actionType == ActionType.SHEAR || actionType == ActionType.MMKILL) { type = myKey; } if (type == null) { Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + "!"); continue; } double income = section.getDouble("income", 0.0); double experience = section.getDouble("experience", 0.0); jobInfo.add(new JobInfo(actionType, id, meta, type + subType, income, incomeEquation, experience, expEquation)); } } job.setJobInfo(actionType, jobInfo); } if (jobKey.equalsIgnoreCase("none")) { Jobs.setNoneJob(job); } else { jobs.add(job); } } //try { // conf.save(f); //} catch (IOException e) { // e.printStackTrace(); //} }
From source file:org.cesecore.certificates.util.DnComponents.java
/** * Load DN ordering used in CertTools.stringToBCDNString etc. * Loads from file placed in src/dncomponents.properties * *//*from w w w . ja va 2s . c om*/ private static void loadOrdering() { // Read the file to an array of lines String line; LinkedHashMap<String, ASN1ObjectIdentifier> map = new LinkedHashMap<String, ASN1ObjectIdentifier>(); BufferedReader in = null; InputStreamReader inf = null; try { InputStream is = obj.getClass().getResourceAsStream("/dncomponents.properties"); //log.info("is is: " + is); if (is != null) { inf = new InputStreamReader(is); //inf = new FileReader("c:\\foo.properties"); in = new BufferedReader(inf); if (!in.ready()) { throw new IOException(); } String[] splits = null; while ((line = in.readLine()) != null) { if (!line.startsWith("#")) { // # is a comment line splits = StringUtils.split(line, '='); if ((splits != null) && (splits.length > 1)) { String name = splits[0].toLowerCase(); ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(splits[1]); map.put(name, oid); } } } in.close(); // Now we have read it in, transfer it to the main oid map log.info("Using DN components from properties file"); oids.clear(); oids.putAll(map); Set<String> keys = map.keySet(); // Set the maps to the desired ordering dNObjectsForward = (String[]) keys.toArray(new String[keys.size()]); } else { log.debug("Using default values for DN components"); } } catch (IOException e) { log.debug("Using default values for DN components"); } finally { try { if (inf != null) { inf.close(); } if (in != null) { in.close(); } } catch (IOException e) { } } }