List of usage examples for java.io InputStreamReader close
public void close() throws IOException
From source file:com.ericsson.research.trap.spi.transports.ApacheClientHttpTransport.java
@Override protected void internalConnect() throws TrapException { this.updateConfig(); // Make a request to get a new TransportID if (!this.isClientConfigured()) { this.logger.debug( "HTTP Transport not properly configured... Unless autoconfigure is enabled (and another transport succeeds) this transport will not be available."); this.setState(TrapTransportState.ERROR); return;/*w ww . ja v a2 s . com*/ } try { this.running = true; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = this.openGet(this.connectUrl); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, Charset.forName("UTF-8")); StringWriter sr = new StringWriter(); int ch = 0; while ((ch = isr.read()) != -1) sr.write(ch); String rawUrl = sr.toString(); String urlBase = this.connectUrl.toString(); if (urlBase.endsWith("/")) urlBase += rawUrl; else urlBase += "/" + rawUrl; this.activeUrl = URI.create(urlBase); // Start a new thread for polling Thread t = new Thread(this); t.setDaemon(true); t.start(); this.postclient = new DefaultHttpClient(); // Change state to connected this.setState(TrapTransportState.CONNECTED); } finally { if (is != null) is.close(); if (isr != null) isr.close(); } } } catch (Exception e) { this.setState(TrapTransportState.ERROR); throw new TrapException(e); } }
From source file:com.fujitsu.dc.core.rs.cell.MessageODataResource.java
/** * HttpResponse?JSON??./* www . j ava 2 s . c om*/ * @param objResponse HttpResponse * @return */ private JSONObject bodyAsJson(HttpResponse objResponse) { JSONObject body = null; InputStream is = null; InputStreamReader isr = null; BufferedReader reader = null; String bodyString = null; try { objResponse.getHeaders("Content-Encoding"); is = objResponse.getEntity().getContent(); isr = new InputStreamReader(is, "UTF-8"); reader = new BufferedReader(isr); StringBuffer sb = new StringBuffer(); int chr; while ((chr = is.read()) != -1) { sb.append((char) chr); } bodyString = sb.toString(); } catch (IllegalStateException e) { log.info(e.getMessage()); } catch (IOException e) { log.info(e.getMessage()); } finally { try { if (reader != null) { reader.close(); } if (isr != null) { isr.close(); } if (is != null) { is.close(); } } catch (IOException e) { log.info(e.getMessage()); } } try { if (bodyString != null) { body = (JSONObject) new JSONParser().parse(bodyString); } } catch (ParseException e) { log.info(e.getMessage()); } return body; }
From source file:com.gamingmesh.jobs.config.ConfigManager.java
/** * Method to load the jobs configuration * /* w w w . j a v a 2s . co 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; } finally { s.close(); } //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)) { // Ignoring example job if (jobKey.equalsIgnoreCase("exampleJob")) continue; ConfigurationSection jobSection = jobsSection.getConfigurationSection(jobKey); String jobName = jobSection.getString("fullname", null); // 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", null); 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!"); } } String bossbar = null; if (jobSection.contains("BossBarColour")) { bossbar = jobSection.getString("BossBarColour", ""); if (bossbar == null) { color = ChatColor.WHITE; Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid BossBarColour property."); } } 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 = new Parser("0"); if (jobSection.isString("income-progression-equation")) { 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; } Parser pointsEquation = new Parser("0"); if (jobSection.isString("points-progression-equation")) { String pointsEquationInput = jobSection.getString("points-progression-equation"); try { pointsEquation = new Parser(pointsEquationInput); // test equation pointsEquation.setVariable("numjobs", 1); pointsEquation.setVariable("joblevel", 1); pointsEquation.setVariable("basepoints", 1); pointsEquation.getValue(); } catch (Exception e) { Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid points-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 = null; if (itemSection.isString("name")) name = itemSection.getString("name"); List<String> lore = new ArrayList<String>(); if (itemSection.getStringList("lore") != null) for (String eachLine : itemSection.getStringList("lore")) { lore.add(org.bukkit.ChatColor.translateAlternateColorCodes('&', eachLine)); } HashMap<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>(); if (itemSection.getStringList("enchants") != null) for (String eachLine : itemSection.getStringList("enchants")) { if (!eachLine.contains("=")) continue; Enchantment ench = Enchantment.getByName(eachLine.split("=")[0]); Integer level = -1; try { level = Integer.parseInt(eachLine.split("=")[1]); } catch (NumberFormatException e) { continue; } if (ench != null && level != -1) enchants.put(ench, level); } BoostMultiplier b = new BoostMultiplier(); if (itemSection.isDouble("moneyBoost")) b.add(CurrencyType.MONEY, itemSection.getDouble("moneyBoost") - 1); if (itemSection.isDouble("pointBoost")) b.add(CurrencyType.POINTS, itemSection.getDouble("pointBoost") - 1); if (itemSection.isDouble("expBoost")) b.add(CurrencyType.EXP, itemSection.getDouble("expBoost") - 1); jobItems.add(new JobItems(node, id, 0, 1, name, lore, enchants, b)); } } // Limited Items ArrayList<JobLimitedItems> jobLimitedItems = new ArrayList<JobLimitedItems>(); ConfigurationSection LimitedItemsSection = jobSection.getConfigurationSection("limitedItems"); if (LimitedItemsSection != null) { for (String itemKey : LimitedItemsSection.getKeys(false)) { ConfigurationSection itemSection = LimitedItemsSection.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 = null; if (itemSection.isString("name")) name = itemSection.getString("name"); List<String> lore = new ArrayList<String>(); if (itemSection.getStringList("lore") != null) for (String eachLine : itemSection.getStringList("lore")) { lore.add(org.bukkit.ChatColor.translateAlternateColorCodes('&', eachLine)); } HashMap<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>(); if (itemSection.getStringList("enchants") != null) for (String eachLine : itemSection.getStringList("enchants")) { if (!eachLine.contains("=")) continue; Enchantment ench = Enchantment.getByName(eachLine.split("=")[0]); Integer level = -1; try { level = Integer.parseInt(eachLine.split("=")[1]); } catch (NumberFormatException e) { continue; } if (ench != null && level != -1) enchants.put(ench, level); } int level = itemSection.getInt("level"); jobLimitedItems.add(new JobLimitedItems(node, id, name, lore, enchants, level)); } } Job job = new Job(jobName, jobShortName, description, color, maxExpEquation, displayMethod, maxLevel, vipmaxLevel, maxSlots, jobPermissions, jobCommand, jobConditions, jobItems, jobLimitedItems, JobsCommandOnJoin, JobsCommandOnLeave, GUIitem, bossbar); 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 (actionType == ActionType.EXPLORE) material = null; 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(); // using breeder finder if (actionType == ActionType.BREED) Jobs.getGCManager().setBreederFinder(true); } switch (key.toLowerCase()) { case "skeletonwither": type = "SkeletonWither"; id = 51; meta = "1"; break; case "skeletonstray": type = "SkeletonStray"; id = 51; meta = "2"; break; case "zombievillager": type = "ZombieVillager"; id = 54; meta = "1"; break; case "zombiehusk": type = "ZombieHusk"; id = 54; meta = "2"; break; case "horseskeleton": type = "HorseSkeleton"; id = 100; meta = "1"; break; case "horsezombie": type = "HorseZombie"; id = 100; meta = "2"; break; case "guardianelder": type = "GuardianElder"; id = 68; meta = "1"; break; } } else if (actionType == ActionType.ENCHANT) { 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; } else if (actionType == ActionType.EXPLORE) { type = myKey; int amount = 10; try { amount = Integer.valueOf(myKey); } catch (NumberFormatException e) { Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + "!"); continue; } Jobs.getExplore().setExploreEnabled(); Jobs.getExplore().setPlayerAmount(amount + 1); } if (type == null) { Jobs.getPluginLogger().warning("Job " + jobKey + " has an invalid " + actionType.getName() + " type property: " + key + "!"); continue; } if (actionType == ActionType.TNTBREAK) Jobs.getGCManager().setTntFinder(true); double income = section.getDouble("income", 0.0); double points = section.getDouble("points", 0.0); double experience = section.getDouble("experience", 0.0); int fromlevel = 1; if (section.isInt("from-level")) fromlevel = section.getInt("from-level"); int untilLevel = -1; if (section.isInt("until-level")) { untilLevel = section.getInt("until-level"); if (untilLevel < fromlevel) { Jobs.getPluginLogger() .warning("Job " + jobKey + " has an invalid until-level in " + actionType.getName() + " for type property: " + key + "! It will be not set."); untilLevel = -1; } } jobInfo.add(new JobInfo(actionType, id, meta, type + subType, income, incomeEquation, experience, expEquation, pointsEquation, points, fromlevel, untilLevel)); } } job.setJobInfo(actionType, jobInfo); } if (jobKey.equalsIgnoreCase("none")) { Jobs.setNoneJob(job); } else { jobs.add(job); } } Bukkit.getConsoleSender() .sendMessage(ChatColor.YELLOW + "[Jobs] Loaded " + Jobs.getJobs().size() + " jobs!"); if (!Jobs.getExplore().isExploreEnabled()) { Bukkit.getConsoleSender().sendMessage(ChatColor.GOLD + "[Jobs] Explorer jobs manager are not enabled!"); } else Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Jobs] Explorer job manager registered!"); //try { // conf.save(f); //} catch (IOException e) { // e.printStackTrace(); //} }
From source file:at.pardus.android.browser.PardusMessageChecker.java
/** * Tries to get the msgFrame via an HTTP GET request, parses it for new * messages/logs and displays the result. * //from w w w . ja v a2 s . com * Does not need to be run on the UI thread. */ public void check() { if (universe == null) { return; } if (PardusConstants.DEBUG) { Log.v(this.getClass().getSimpleName(), "Checking for new messages/logs"); } InputStreamReader reader = null; try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity == null) { Log.w(this.getClass().getSimpleName(), "Could not check for messages (error in response)"); return; } reader = new InputStreamReader(entity.getContent()); StringBuilder sb = new StringBuilder(); char[] buffer = new char[2048]; int i = 0; while ((i = reader.read(buffer, 0, buffer.length)) >= 0) { if (i > 0) { sb.append(buffer, 0, i); } } String responseStr = sb.toString(); parseResponse(responseStr); } catch (ClientProtocolException e) { Log.e(this.getClass().getSimpleName(), "Could not check for messages (error in protocol)", e); } catch (IOException e) { Log.w(this.getClass().getSimpleName(), "Could not check for messages (error reading response)", e); } catch (Exception e) { Log.e(this.getClass().getSimpleName(), "Could not check for messages (unknown error)", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } }
From source file:com.linkedin.databus.core.TestDbusEventBufferMult.java
public PhysicalSourceConfig convertToPhysicalSourceConfig(String str) { _mapper = new ObjectMapper(); InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(str)); PhysicalSourceConfig pConfig = null; try {//from ww w. j a va 2 s . c o m pConfig = _mapper.readValue(isr, PhysicalSourceConfig.class); } catch (JsonParseException e) { fail("Failed parsing", e); } catch (JsonMappingException e) { fail("Failed parsing", e); } catch (IOException e) { fail("Failed parsing", e); } try { isr.close(); } catch (IOException e) { fail("Failed", e); } return pConfig; }
From source file:org.bonitasoft.engine.identity.OrganizationIT.java
private void importOrganization(final String fileName) throws IOException, OrganizationImportException { final InputStream xmlStream = OrganizationIT.class.getResourceAsStream(fileName); final InputStreamReader reader = new InputStreamReader(xmlStream); try {/*from w w w . j a v a2s . c om*/ final byte[] organisationContent = IOUtils.toByteArray(reader); getIdentityAPI().importOrganization(new String(organisationContent, UTF_8)); } finally { xmlStream.close(); reader.close(); } }
From source file:com.anthemengineering.mojo.infer.InferMojo.java
/** * Executes infer once for each source file and writes the output to {@code inferOutputDir}. * * @param classpath classpath used as an argument to the javac command given to Infer. * @param inferOutputDir directory where Infer will write its output * @param sourceFiles collection of files for Infer to analyze * @param numSourceFiles number of source files to analyze; used to make sure every Infer execution finishes * before moving on./*w w w .j a v a 2s .co m*/ */ private void completeInferExecutions(final String classpath, final File inferOutputDir, Collection<File> sourceFiles, int numSourceFiles) throws MojoExecutionException { // temporary directory for storing .class files created by {@code javac}; placed in build directory final File buildTmpDir = new File(project.getBuild().getDirectory(), JAVAC_OUTPUT_DIRECTORY_NAME); try { FileUtils.forceMkdir(buildTmpDir); } catch (final IOException e) { final String errMsg = String.format("Unable to make temp directory %s!", buildTmpDir.getAbsolutePath()); getLog().error(errMsg, e); throw new MojoExecutionException(errMsg, e); } buildTmpDir.deleteOnExit(); // used to wait for all processes running infer to complete final CountDownLatch doneSignal = new CountDownLatch(numSourceFiles); // TODO: optionally allow debugging info? Output directory? // TODO: a better way to do this may be to determine if there is an entry point that takes a set of source // files and the classpath and use this. @See mvn, inferj and inferlib in the infer repository. ExecutorService pool = null; try { pool = Executors.newFixedThreadPool(4); for (final File sourceFile : sourceFiles) { final Runnable r = new Runnable() { @Override public void run() { Process proc = null; try { // infer final List<String> command = new ArrayList<String>(); command.add(inferPath); command.add("-i"); command.add("-o"); command.add(inferOutputDir.getAbsolutePath()); command.add("--"); // javac command.add("javac"); command.add(sourceFile.getAbsolutePath()); command.add("-d"); command.add(buildTmpDir.getAbsolutePath()); command.add("-classpath"); command.add(classpath); final ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(System.getenv()); if (consoleOut) { builder.redirectErrorStream(true); proc = builder.start(); InputStreamReader isr = null; BufferedReader br = null; InputStream pis = null; try { pis = proc.getInputStream(); isr = new InputStreamReader(pis); br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { getLog().info(line); } } catch (final IOException e) { getLog().error(String.format("Error writing process output for file: %s.", sourceFile.getAbsolutePath()), e); } finally { if (isr != null) { isr.close(); } if (br != null) { br.close(); } if (pis != null) { pis.close(); } } } else { // no logging. proc = builder.start(); } // NOTE: most/all executions end in failure during analysis, however, // supported java bugs are still reported proc.waitFor(); } catch (final IOException e) { getLog().error( "Exception occurred while trying to perform Infer execution; output not complete" + "", e); } catch (final InterruptedException e) { getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e); } finally { try { // currently they all fail, although java bugs are still reported if (proc != null && proc.exitValue() != 0) { FAILED_CHECKS.put(sourceFile, proc.exitValue()); } } catch (final Exception e) { FAILED_CHECKS.put(sourceFile, -1); } doneSignal.countDown(); } } }; pool.submit(r); } } finally { if (pool != null) { pool.shutdown(); } } try { doneSignal.await(); } catch (final InterruptedException e) { getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e); } }
From source file:com.norconex.collector.http.robot.impl.StandardRobotsTxtProvider.java
RobotsTxt parseRobotsTxt(InputStream is, String url, String userAgent) throws IOException { String baseURL = getBaseURL(url); //--- Load matching data --- InputStreamReader isr = new InputStreamReader(is, CharEncoding.UTF_8); BufferedReader br = new BufferedReader(isr); RobotData data = new RobotData(); boolean parse = false; String line;// ww w . j ava 2 s .c o m while ((line = br.readLine()) != null) { if (ignoreLine(line)) continue; line = cleanLineFromComments(line); String key = line.replaceFirst("(.*?)(:.*)", "$1").trim(); String value = line.replaceFirst("(.*?:)(.*)", "$2").trim(); if ("sitemap".equalsIgnoreCase(key)) { data.sitemaps.add(value); } if ("user-agent".equalsIgnoreCase(key)) { // stop parsing if we have an exact match already if (data.precision == RobotData.Precision.EXACT) { break; } RobotData.Precision precision = matchesUserAgent(userAgent, value); if (precision.ordinal() > data.precision.ordinal()) { data.clear(); data.precision = precision; parse = true; } else { parse = false; } } else if (parse) { if ("crawl-delay".equalsIgnoreCase(key)) { data.crawlDelay = value; } else { data.rules.put(value, key); } } } isr.close(); return data.toRobotsTxt(baseURL); }
From source file:net.phalapi.sdk.PhalApiClient.java
protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception { String result = null;/*from w w w. j a va 2 s.c o m*/ URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); // ? connection.setUseCaches(false); connection.setConnectTimeout(timeoutMs); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //POST? String postContent = ""; Iterator<Entry<String, String>> iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); postContent += "&" + entry.getKey() + "=" + entry.getValue(); } out.writeBytes(postContent); out.flush(); out.close(); Log.d("[PhalApiClient requestUrl]", requestUrl + postContent); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); Log.d("[PhalApiClient apiResult]", result); if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:com.controller.CuotasController.java
@RequestMapping("cuotas.htm") public ModelAndView getCuotas(HttpServletRequest request) { sesion = request.getSession();//from w w w . ja v a 2s .com ModelAndView mav = new ModelAndView(); String mensaje = null; Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); String country = detalle.getCiudad(); String amount = "5"; String myURL = "http://192.168.5.39/app_dev.php/public/get/rates"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8"); data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String resultado = sb.toString(); if (sesion.getAttribute("usuario") == null) { mav.setViewName("login/login"); } else { sesionUser = sesion.getAttribute("usuario").toString(); //Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); mav.addObject("country", detalle.getCiudad()); mav.addObject("resultado", resultado); if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) { mav.setViewName("viewsAdmin/cuotasAdmin"); System.out.println("el usuario es administrador"); } else { mav.setViewName("panel/cuotas"); } } return mav; }