List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void check_what_doclet_will_generate_correct_endpoints_order() throws Exception { // GIVEN/*from w w w. j a va 2 s . c o m*/ String parserFilePath = "./all-mappings-docs.json"; // WHEN runDoclet(); // THEN JSONParser parser = new JSONParser(); FileReader fileReader = null; try { fileReader = new FileReader(parserFilePath); JSONObject json = (JSONObject) parser.parse(fileReader); JSONArray arr = (JSONArray) json.get("endpoints"); JSONObject obj = (JSONObject) arr.get(0); JSONObject obj1 = (JSONObject) arr.get(1); Assert.assertEquals(obj.get("endpoint"), "/v1/twitter/followers/stream"); Assert.assertEquals(obj1.get("endpoint"), "/v1/twitter/followers/metrics"); } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:name.martingeisse.ecobuild.moduletool.output.OutputTool.java
@Override public void execute(IModuleToolContext context) throws IOException { FileReader buildScriptReader; try {//from w w w . jav a 2 s.c o m buildScriptReader = new FileReader(new File(context.getModuleSourceFolder(), "build.txt")); } catch (FileNotFoundException e) { throw new UserMessageBuildException( "Output build script 'build.txt' not found for module " + context.getModuleSourceFolder()); } LineNumberReader lineReader = new LineNumberReader(buildScriptReader); State state = new State(); state.currentFolder = context.getMainBuildFolder(); state.folderStack = new Stack<File>(); while (true) { String line = lineReader.readLine(); if (line == null) { break; } handleLine(context, state, line); } buildScriptReader.close(); }
From source file:edu.cudenver.bios.power.test.PowerChecker.java
/** * Create a power checker which compares the power * values against an XML formatted input file of SAS results. * The user may optionally disable simulation comparisons. * * @param sasOutputFile XML file of SAS power values * @param compareAgainstSimulation if true, power values * are compared against simulation.//w w w .ja va 2 s .co m */ public PowerChecker(String sasOutputFile, boolean compareAgainstSimulation) throws IllegalArgumentException { this.simulate = compareAgainstSimulation; //this.simulate = false; FileReader reader = null; // parse the sas xml file try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); reader = new FileReader(sasOutputFile); Document doc = builder.parse(new InputSource(reader)); sasPowers = SASOutputParser.parsePowerResults(doc); } catch (Exception e) { throw new IllegalArgumentException("Parsing of SAS XML failed: " + e.getMessage()); } finally { if (reader != null) try { reader.close(); } catch (Exception e) { } ; } }
From source file:com.netscape.cmstools.cert.CertFindCLI.java
public void execute(String[] args) throws Exception { // Always check for "--help" prior to parsing if (Arrays.asList(args).contains("--help")) { // Display usage printHelp();// w w w. ja v a 2 s .com System.exit(0); } CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); printHelp(); System.exit(-1); } String[] cmdArgs = cmd.getArgs(); if (cmdArgs.length != 0) { System.err.println("Error: Too many arguments specified."); printHelp(); System.exit(-1); } CertSearchRequest searchData = null; String fileName = null; if (cmd.hasOption("input")) { fileName = cmd.getOptionValue("input"); if (fileName == null || fileName.length() < 1) { System.err.println("Error: No file name specified."); printHelp(); System.exit(-1); } } if (fileName != null) { FileReader reader = null; try { reader = new FileReader(fileName); searchData = CertSearchRequest.valueOf(reader); } catch (FileNotFoundException e) { System.err.println("Error: " + e.getMessage()); System.exit(-1); } catch (JAXBException e) { System.err.println("Error: " + e.getMessage()); System.exit(-1); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } else { searchData = new CertSearchRequest(); } String s = cmd.getOptionValue("start"); Integer start = s == null ? null : Integer.valueOf(s); s = cmd.getOptionValue("size"); Integer size = s == null ? null : Integer.valueOf(s); addSearchAttribute(cmd, searchData); CertDataInfos certs = certCLI.certClient.findCerts(searchData, start, size); MainCLI.printMessage(certs.getTotal() + " entries found"); if (certs.getTotal() == 0) return; boolean first = true; Collection<CertDataInfo> entries = certs.getEntries(); for (CertDataInfo cert : entries) { if (first) { first = false; } else { System.out.println(); } CertCLI.printCertInfo(cert); } MainCLI.printMessage("Number of entries returned " + certs.getEntries().size()); }
From source file:au.com.jwatmuff.eventmanager.gui.main.LoadCompetitionWindow.java
private void saveBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBackupButtonActionPerformed DatabaseInfo info = (DatabaseInfo) competitionList.getSelectedValue(); if (info == null || !info.local) return;// ww w . j a va 2s . co m JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter("Event Manager Files", "evm")); if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.getName().toLowerCase().endsWith(".evm")) file = new File(file.getAbsolutePath() + ".evm"); if (file.exists()) { int result = JOptionPane.showConfirmDialog(rootPane, file.getName() + " already exists. Overwrite file?", "Save Backup", JOptionPane.YES_NO_OPTION); if (result != JOptionPane.YES_OPTION) return; } try { File tempDir = Files.createTempDirectory("event-manager").toFile(); FileUtils.copyDirectory(info.localDirectory, tempDir); File lockFile = new File(tempDir, "update.dat.lock"); lockFile.delete(); /* change id */ Properties props = new Properties(); FileReader fr = new FileReader(new File(tempDir, "info.dat")); props.load(fr); fr.close(); props.setProperty("old-UUID", props.getProperty("UUID", "none")); props.setProperty("UUID", UUID.randomUUID().toString()); FileWriter fw = new FileWriter(new File(tempDir, "info.dat")); props.store(fw, ""); fw.close(); ZipUtils.zipFolder(tempDir, file, false); } catch (Exception e) { GUIUtils.displayError(this, "Failed to save file: " + e.getMessage()); } } }
From source file:au.com.jwatmuff.eventmanager.gui.main.LoadCompetitionWindow.java
private void loadBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadBackupButtonActionPerformed File databaseStore = new File(Main.getWorkingDirectory(), "comps"); JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter("Event Manager Files", "evm")); JPanel optionsPanel = new JPanel(); optionsPanel.setBorder(/*from w w w. j av a 2 s . c om*/ new CompoundBorder(new EmptyBorder(0, 10, 0, 10), new TitledBorder("Load backup options"))); JCheckBox preserveIDCheckbox = new JCheckBox("Preserve competition ID"); optionsPanel.add(preserveIDCheckbox); chooser.setAccessory(optionsPanel); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { /* input zip file */ File file = chooser.getSelectedFile(); /* construct output directory */ File dir = new File(databaseStore, file.getName()); int suffix = 0; while (dir.exists()) { suffix++; dir = new File(databaseStore, file.getName() + "_" + suffix); } /* unzip */ try { ZipUtils.unzipFile(dir, file); /* change id */ Properties props = new Properties(); FileReader fr = new FileReader(new File(dir, "info.dat")); props.load(fr); fr.close(); if (!preserveIDCheckbox.isSelected()) { props.setProperty("UUID", UUID.randomUUID().toString()); } props.setProperty("name", props.getProperty("name") + " - " + dateFormat.format(new Date())); FileWriter fw = new FileWriter(new File(dir, "info.dat")); props.store(fw, ""); fw.close(); /* update gui */ checkDatabasesExecutor.schedule(checkDatabasesTask, 0, TimeUnit.MILLISECONDS); } catch (Exception e) { GUIUtils.displayError(null, "Error while opening file: " + e.getMessage()); } } }
From source file:org.apache.hadoop.util.LinuxMemoryCalculatorPlugin.java
private void readProcMemInfoFile() { if (readMemInfoFile) { return;/*from www . jav a 2s . com*/ } // Read "/proc/memInfo" file BufferedReader in = null; FileReader fReader = null; try { fReader = new FileReader(PROCFS_MEMFILE); in = new BufferedReader(fReader); } catch (FileNotFoundException f) { // shouldn't happen.... return; } Matcher mat = null; try { String str = in.readLine(); while (str != null) { mat = PROCFS_MEMFILE_FORMAT.matcher(str); if (mat.find()) { if (mat.group(1).equals(MEMTOTAL_STRING)) { ramSize = Long.parseLong(mat.group(2)); } else if (mat.group(1).equals(SWAPTOTAL_STRING)) { swapSize = Long.parseLong(mat.group(2)); } } str = in.readLine(); } } catch (IOException io) { LOG.warn("Error reading the stream " + io); } finally { // Close the streams try { fReader.close(); try { in.close(); } catch (IOException i) { LOG.warn("Error closing the stream " + in); } } catch (IOException i) { LOG.warn("Error closing the stream " + fReader); } } readMemInfoFile = true; }
From source file:me.oriley.crate.CrateGenerator.java
private boolean isFileValid(@NonNull File crateOutputFile, @NonNull String[] comments) { if (comments.length <= 0) { return false; }//from w w w .j a va 2 s.com boolean isValid = true; try { FileReader reader = new FileReader(crateOutputFile); BufferedReader input = new BufferedReader(reader); for (String comment : comments) { String fileLine = input.readLine(); if (fileLine == null || comment == null || !StringUtils.contains(fileLine, comment)) { log("Aborting, comment: " + comment + ", fileLine: " + fileLine); isValid = false; break; } else { log("Line valid, comment: " + comment + ", fileLine: " + fileLine); } } input.close(); reader.close(); } catch (IOException e) { logError("Error parsing file", e, false); isValid = false; } log("File check result -- isValid ? " + isValid); return isValid; }
From source file:uk.codingbadgers.bootstrap.tasks.TaskInstallerUpdateCheck.java
@Override public void run(Bootstrap bootstrap) { try {//from w w w .ja v a 2 s.c o m HttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(INSTALLER_UPDATE_URL); request.setHeader(new BasicHeader("Accept", GITHUB_MIME_TYPE)); HttpResponse response = client.execute(request); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); String localVersion = null; if (bootstrap.getInstallerFile().exists()) { JarFile jar = new JarFile(bootstrap.getInstallerFile()); Manifest manifest = jar.getManifest(); localVersion = manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION); jar.close(); } JsonArray json = PARSER.parse(new InputStreamReader(entity.getContent())).getAsJsonArray(); JsonObject release = json.get(0).getAsJsonObject(); JsonObject installerAsset = null; JsonObject librariesAsset = null; int i = 0; for (JsonElement element : release.get("assets").getAsJsonArray()) { JsonObject object = element.getAsJsonObject(); if (INSTALLER_LABEL.equals(object.get("name").getAsString())) { installerAsset = object; } else if (INSTALLER_LIBS_LABEL.equals(object.get("name").getAsString())) { librariesAsset = object; } } if (VersionComparator.getInstance().compare(localVersion, release.get("name").getAsString()) < 0) { bootstrap.addDownload(DownloadType.INSTALLER, new EtagDownload( installerAsset.get("url").getAsString(), bootstrap.getInstallerFile())); localVersion = release.get("name").getAsString(); } File libs = new File(bootstrap.getInstallerFile() + ".libs"); boolean update = true; if (libs.exists()) { FileReader reader = null; try { reader = new FileReader(libs); JsonElement parsed = PARSER.parse(reader); if (parsed.isJsonObject()) { JsonObject libsJson = parsed.getAsJsonObject(); if (libsJson.has("installer")) { JsonObject installerJson = libsJson.get("installer").getAsJsonObject(); if (installerJson.get("version").getAsString().equals(localVersion)) { update = false; } } } } catch (JsonParseException ex) { throw new BootstrapException(ex); } finally { reader.close(); } } if (update) { new EtagDownload(librariesAsset.get("url").getAsString(), new File(bootstrap.getInstallerFile() + ".libs")).download(); FileReader reader = null; FileWriter writer = null; try { reader = new FileReader(libs); JsonObject libsJson = PARSER.parse(reader).getAsJsonObject(); JsonObject versionJson = new JsonObject(); versionJson.add("version", new JsonPrimitive(localVersion)); libsJson.add("installer", versionJson); writer = new FileWriter(libs); new Gson().toJson(libsJson, writer); } catch (JsonParseException ex) { throw new BootstrapException(ex); } finally { reader.close(); writer.close(); } } EntityUtils.consume(entity); } else if (statusLine.getStatusCode() == HttpStatus.SC_FORBIDDEN) { System.err.println("Hit rate limit, skipping update check"); } else { throw new BootstrapException("Error sending request to github. Error " + statusLine.getStatusCode() + statusLine.getReasonPhrase()); } } catch (IOException e) { throw new BootstrapException(e); } }
From source file:at.tuwien.minimee.migration.parser.HPROF_Parser.java
public void parse(String fileToRead) { try {//from w ww . j ava2 s . c o m total_virtual = 0; total_allocated = 0; /* * Sets up a file reader to read the file passed on the command line * one character at a time */ FileReader input = new FileReader(fileToRead); /* * Filter FileReader through a Buffered read to read a line at a * time */ try { BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line // Read first line line = bufRead.readLine(); // Read through file one line at time. Print line # and line while (line != null) { if (line.contains(" rank self")) break; line = bufRead.readLine(); } // read next line containing the first info line = bufRead.readLine(); // begin parsing while (line != null && line.compareTo("SITES END") != 0) { interpretline(line); line = bufRead.readLine(); } } finally { input.close(); } } catch (IOException e) { // If another exception is generated, print a stack trace log.error(e); } }