List of usage examples for java.io BufferedReader ready
public boolean ready() throws IOException
From source file:org.apache.flink.client.FlinkYarnSessionCli.java
public static void runInteractiveCli(AbstractFlinkYarnCluster yarnCluster) { final String HELP = "Available commands:\n" + "help - show these commands\n" + "stop - stop the YARN session"; int numTaskmanagers = 0; try {//from w ww. j a va 2s . c o m BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); label: while (true) { // ------------------ check if there are updates by the cluster ----------- FlinkYarnClusterStatus status = yarnCluster.getClusterStatus(); if (status != null && numTaskmanagers != status.getNumberOfTaskManagers()) { System.err.println("Number of connected TaskManagers changed to " + status.getNumberOfTaskManagers() + ". Slots available: " + status.getNumberOfSlots()); numTaskmanagers = status.getNumberOfTaskManagers(); } List<String> messages = yarnCluster.getNewMessages(); if (messages != null && messages.size() > 0) { System.err.println("New messages from the YARN cluster: "); for (String msg : messages) { System.err.println(msg); } } if (yarnCluster.hasFailed()) { System.err.println("The YARN cluster has failed"); yarnCluster.shutdown(true); } // wait until CLIENT_POLLING_INTERVALL is over or the user entered something. long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < CLIENT_POLLING_INTERVALL * 1000 && !in.ready()) { Thread.sleep(200); } //------------- handle interactive command by user. ---------------------- if (in.ready()) { String command = in.readLine(); switch (command) { case "quit": case "stop": break label; case "help": System.err.println(HELP); break; default: System.err.println("Unknown command '" + command + "'. Showing help: \n" + HELP); break; } } if (yarnCluster.hasBeenStopped()) { LOG.info("Stopping interactive command line interface, YARN cluster has been stopped."); break; } } } catch (Exception e) { LOG.warn("Exception while running the interactive command line interface", e); } }
From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java
/** * Reads a certificate in PEM-format from an InputStream. * * The stream may contain other things, the first certificate in the * stream is read./* w ww.j a v a 2s .c o m*/ * * @param certstream the input stream containing the certificate in * PEM-format * @return Ordered List of X509Certificate, first certificate first, * or empty List * @exception IOException if the stream cannot be read. * @exception CertificateException if the stream does not contain a * correct certificate. */ private List<X509Certificate> getCertsFromPEM(final InputStream certstream) throws IOException, CertificateException { final ArrayList<X509Certificate> ret = new ArrayList<X509Certificate>(); final BufferedReader bufRdr = new BufferedReader(new InputStreamReader(certstream)); while (bufRdr.ready()) { final ByteArrayOutputStream ostr = new ByteArrayOutputStream(); final PrintStream opstr = new PrintStream(ostr); String temp; while ((temp = bufRdr.readLine()) != null && !temp.equals(PEM_BEGIN)) { } if (temp == null) { throw new IOException("Error in " + certstream.toString() + ", missing " + PEM_BEGIN + " boundary"); } while ((temp = bufRdr.readLine()) != null && !temp.equals(PEM_END)) { opstr.print(temp); } if (temp == null) { throw new IOException("Error in " + certstream.toString() + ", missing " + PEM_END + " boundary"); } opstr.close(); final byte[] certbuf = Base64.decode(ostr.toByteArray()); ostr.close(); // Phweeew, were done, now decode the cert from file back to // X509Certificate object final CertificateFactory cf = getCertificateFactory(); final X509Certificate x509cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(certbuf)); ret.add(x509cert); } return ret; }
From source file:org.owasp.dependencycheck.analyzer.RubyBundleAuditAnalyzer.java
/** * Processes the bundler audit output.// www . j ava 2 s . co m * * @param original the dependency * @param engine the dependency-check engine * @param rdr the reader of the report * @throws IOException thrown if the report cannot be read. */ private void processBundlerAuditOutput(Dependency original, Engine engine, BufferedReader rdr) throws IOException { final String parentName = original.getActualFile().getParentFile().getName(); final String fileName = original.getFileName(); final String filePath = original.getFilePath(); Dependency dependency = null; Vulnerability vulnerability = null; String gem = null; final Map<String, Dependency> map = new HashMap<String, Dependency>(); boolean appendToDescription = false; while (rdr.ready()) { final String nextLine = rdr.readLine(); if (null == nextLine) { break; } else if (nextLine.startsWith(NAME)) { appendToDescription = false; gem = nextLine.substring(NAME.length()); if (!map.containsKey(gem)) { map.put(gem, createDependencyForGem(engine, parentName, fileName, filePath, gem)); } dependency = map.get(gem); LOGGER.debug(String.format("bundle-audit (%s): %s", parentName, nextLine)); } else if (nextLine.startsWith(VERSION)) { vulnerability = createVulnerability(parentName, dependency, gem, nextLine); } else if (nextLine.startsWith(ADVISORY)) { setVulnerabilityName(parentName, dependency, vulnerability, nextLine); } else if (nextLine.startsWith(CRITICALITY)) { addCriticalityToVulnerability(parentName, vulnerability, nextLine); } else if (nextLine.startsWith("URL: ")) { addReferenceToVulnerability(parentName, vulnerability, nextLine); } else if (nextLine.startsWith("Description:")) { appendToDescription = true; if (null != vulnerability) { vulnerability.setDescription("*** Vulnerability obtained from bundle-audit verbose report. " + "Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 " + " indicates unknown). See link below for full details. *** "); } } else if (appendToDescription) { if (null != vulnerability) { vulnerability.setDescription(vulnerability.getDescription() + nextLine + "\n"); } } } }
From source file:edu.ucdenver.ccp.nlp.ae.dict_util.GeneInfoToDictionary.java
public GeneInfoToDictionary(File geneFile) throws IOException { filterSingleLetterTerms = true;//w w w .j av a 2s .c o m namespacesToInclude = null; BufferedReader reader = null; try { // Create synonyms hash from 5th and 14th columns. They have duplicates, so create // a back hash so you can see how many id's share a particular other designation. // 5th col. is synonyms. 14th is Other Designations //reader = FileReaderUtil.initBufferedReader(geneFile, CharacterEncoding.UTF_8); CharsetDecoder csd = Charset.forName("UTF-8").newDecoder().onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); InputStream ins = new FileInputStream(geneFile); reader = new BufferedReader(new InputStreamReader(ins, csd)); reader.readLine(); while (reader.ready()) { String line = reader.readLine(); String[] parts = line.split("\t"); String id = parts[1]; String[] synonyms = parts[4].split("\\|"); String[] other = parts[13].split("\\|"); ArrayList<String> allSynonyms = new ArrayList<String>(); if (!parts[4].equals("-")) { allSynonyms.addAll(Arrays.asList(synonyms)); } if (!parts[13].equals("-")) { allSynonyms.addAll(Arrays.asList(other)); } for (String syn : allSynonyms) { if (idToSynonymMap.get(id) == null) { idToSynonymMap.put(id, new ArrayList<String>()); } idToSynonymMap.get(id).add(syn); if (synonymToIdMap.get(syn) == null) { synonymToIdMap.put(syn, new ArrayList<String>()); } synonymToIdMap.get(syn).add(id); } } } finally { try { reader.close(); } catch (Exception x) { } } }
From source file:com.irccloud.android.GingerbreadImageProxy.java
private HttpRequest readRequest(Socket client) { HttpRequest request = null;/*from w ww . j a va 2 s .c o m*/ InputStream is; String firstLine; String range = null; String ua = null; try { is = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192); firstLine = reader.readLine(); String line = null; do { line = reader.readLine(); if (line != null && line.toLowerCase().startsWith("range: ")) { range = line.substring(7); } if (line != null && line.toLowerCase().startsWith("user-agent: ")) { ua = line.substring(12); } } while (line != null && reader.ready()); } catch (IOException e) { Log.e(LOG_TAG, "Error parsing request", e); return request; } if (firstLine == null) { Log.i(LOG_TAG, "Proxy client closed connection without a request."); return request; } StringTokenizer st = new StringTokenizer(firstLine); String method = st.nextToken(); String uri = st.nextToken(); String realUri = uri.substring(1); request = new BasicHttpRequest(method, realUri, new ProtocolVersion("HTTP", 1, 1)); if (range != null) request.addHeader("Range", range); if (ua != null) request.addHeader("User-Agent", ua); return request; }
From source file:org.sonatype.nexus.integrationtests.nexus3860.AbstractCargoIT.java
/** * Verify the logging output does not contain any nasty errors and such *///from ww w .j a v a 2s .co m private void downloadAndConfirmLog(String logURI, String name) throws Exception { Response response = null; InputStreamReader reader = null; BufferedReader bReader = null; try { response = RequestFacade.sendMessage(new URL(logURI), Method.GET, null); assertThat(response, ResponseMatchers.isSuccessful()); InputStream stream = response.getEntity().getStream(); if (stream == null) { Assert.fail("Stream was null: " + response.getEntity().getText()); } // get the first 10000 chars from the downloaded log reader = new InputStreamReader(stream); bReader = new BufferedReader(reader); StringBuilder downloadedLog = new StringBuilder(); int lineCount = 10000; while (bReader.ready() && lineCount-- > 0) { downloadedLog.append((char) bReader.read()); } String downloadedLogStr = downloadedLog.toString(); assertThat("Should have been DEBUG level logging so there should have been DEBUG in log", downloadedLogStr, containsString("DEBUG")); List<String> falsePositives = Lists.newArrayList(); falsePositives.add("org/sonatype/nexus/rest/error/reporting/ErrorReportingPlexusResource"); falsePositives.add("org.sonatype.nexus.rest.error.reporting.ErrorReportingPlexusResource"); falsePositives.add("org.sonatype.nexus.error.reporting.DefaultErrorReportingManager"); for (String fp : falsePositives) { downloadedLogStr = downloadedLogStr.replace(fp, ""); } assertThat(downloadedLogStr, not(containsString("error"))); assertThat(downloadedLogStr, not(containsString("exception"))); } finally { RequestFacade.releaseResponse(response); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(bReader); } }
From source file:org.ejbca.core.model.ca.publisher.GeneralPurposeCustomPublisher.java
/** * Writes a byte-array to a temporary file and executes the given command * with the file as argument. The function will, depending on its * parameters, fail if output to standard error from the command was * detected or the command returns with an non-zero exit code. * // w w w . j a v a2 s . com * @param externalCommand * The command to run. * @param bytes * The buffer with content to write to the file. * @param failOnCode * Determines if the method should fail on a non-zero exit code. * @param failOnOutput * Determines if the method should fail on output to standard * error. * @param additionalArguments * Added to the command after the tempfiles name * @throws PublisherException */ private void runWithTempFile(String externalCommand, byte[] bytes, boolean failOnCode, boolean failOnOutput, List<String> additionalArguments) throws PublisherException { // Create temporary file File tempFile = null; FileOutputStream fos = null; try { tempFile = File.createTempFile("GeneralPurposeCustomPublisher", ".tmp"); fos = new FileOutputStream(tempFile); fos.write(bytes); // fos.close(); } catch (FileNotFoundException e) { String msg = intres.getLocalizedMessage("publisher.errortempfile"); log.error(msg, e); throw new PublisherException(msg); } catch (IOException e) { try { fos.close(); } catch (IOException e1) { } tempFile.delete(); String msg = intres.getLocalizedMessage("publisher.errortempfile"); log.error(msg, e); throw new PublisherException(msg); } // Exec file from properties with the file as an argument String tempFileName = null; try { tempFileName = tempFile.getCanonicalPath(); String[] cmdcommand = (externalCommand).split("\\s"); additionalArguments.add(0, tempFileName); if (SystemUtils.IS_OS_WINDOWS) { /* * Hack needed for Windows, where Runtime.exec won't consistently encapsulate arguments, leading to arguments * containing spaces (such as Subject DNs) sometimes being parsed as multiple arguments. Bash, on the other hand, * won't parse quote surrounded arguments. */ for (int i = 0; i < additionalArguments.size(); i++) { String argument = additionalArguments.get(i); //Add quotes to encapsulate argument. if (!argument.startsWith("\"") && !argument.endsWith("\"")) { additionalArguments.set(i, "\"" + argument + "\""); } } } String[] cmdargs = additionalArguments.toArray(new String[additionalArguments.size()]); String[] cmdarray = new String[cmdcommand.length + cmdargs.length]; System.arraycopy(cmdcommand, 0, cmdarray, 0, cmdcommand.length); System.arraycopy(cmdargs, 0, cmdarray, cmdcommand.length, cmdargs.length); Process externalProcess = Runtime.getRuntime().exec(cmdarray, null, null); BufferedReader stdError = new BufferedReader(new InputStreamReader(externalProcess.getErrorStream())); BufferedReader stdInput = new BufferedReader(new InputStreamReader(externalProcess.getInputStream())); while (stdInput.readLine() != null) { } // NOPMD: Required under win32 to avoid lock String stdErrorOutput = null; // Check errorcode and the external applications output to stderr if (((externalProcess.waitFor() != 0) && failOnCode) || (stdError.ready() && failOnOutput)) { tempFile.delete(); String errTemp = null; while (stdError.ready() && (errTemp = stdError.readLine()) != null) { if (stdErrorOutput == null) { stdErrorOutput = errTemp; } else { stdErrorOutput += "\n" + errTemp; } } String msg = intres.getLocalizedMessage("publisher.errorexternalapp", externalCommand); if (stdErrorOutput != null) { msg += " - " + stdErrorOutput + " - " + tempFileName; } log.error(msg); throw new PublisherException(msg); } } catch (IOException e) { String msg = intres.getLocalizedMessage("publisher.errorexternalapp", externalCommand); throw new PublisherException(msg); } catch (InterruptedException e) { String msg = intres.getLocalizedMessage("publisher.errorexternalapp", externalCommand); Thread.currentThread().interrupt(); throw new PublisherException(msg); } finally { try { fos.close(); } catch (IOException e1) { } // Remove temporary file or schedule for delete if delete fails. if (!tempFile.delete()) { tempFile.deleteOnExit(); log.info(intres.getLocalizedMessage("publisher.errordeletetempfile", tempFileName)); } } }
From source file:openaf.AFCmdOS.java
/** * //w w w .j av a 2s.c o m * @param in * @param out * @param op * @throws Exception */ protected void execute(InputStream in, OutputStream out, String op) throws Exception { boolean processScript = false; StringBuilder input = new StringBuilder(); // Check repack if (this.getClass().getResourceAsStream("/js.jar") != null && !silenceRepack) System.err.println("Warning: Please consider repacking OpenAF (use --repack)."); // 1. Read the input from stdin and option -e and from a file // StringBuilder theInput = new StringBuilder(); pmIn = new JsonObject(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); if (pipe) { String lineO = ""; while ((lineO = br.readLine()) != null) { input.append(lineO); input.append("\n"); } } else { while (br.ready()) { input.append(br.readLine()); input.append("\n"); } } //br.close(); if (INPUT_TYPE != inputtype.INPUT_EXPR) { if (!exprInput.equals("")) { theInput.append(exprInput); } else { theInput.append(input); } } else { theInput.append(input); INPUT_TYPE = inputtype.INPUT_SCRIPT; } // 2. Recognize input // pmOut = new JsonObject(); // 2.1 Auto detect the input if (INPUT_TYPE == inputtype.INPUT_AUTO) { if (theInput.toString().startsWith(PREFIX_SCRIPT) || theInput.toString().startsWith("#!")) INPUT_TYPE = inputtype.INPUT_SCRIPT; } if (theInput.length() > 0) { switch (INPUT_TYPE) { case INPUT_JSON: pmIn = (new com.google.gson.Gson()).fromJson(theInput.toString(), JsonObject.class); break; case INPUT_SCRIPT: processScript = true; break; default: break; } } JsonObject pmOut = execute(pmIn, op, processScript, theInput, false); // 4. Generate output // if (!silentMode) { String outS = ""; outS = pmOut.toString(); out.write(outS.getBytes()); out.write('\n'); out.flush(); out.close(); } }
From source file:org.nuxeo.connect.packages.dependencies.CUDFHelper.java
/** * Parse a CUDF universe string//from w w w . j av a2s . c om * * @param reader * @return The CUDF universe as a map of {@link NuxeoCUDFPackageDescription} per CUDF unique ID * (pkgName-pkgCUDFVersion). The map uses the natural ordering of its keys. * @throws IOException * @throws DependencyException * @since 1.4.20 * @see #getCUDFFile() * @see #formatCUDF(NuxeoCUDFPackage) */ public Map<String, NuxeoCUDFPackageDescription> parseCUDFFile(BufferedReader reader) throws IOException, DependencyException { Map<String, NuxeoCUDFPackageDescription> map = new TreeMap<>(); NuxeoCUDFPackageDescription nuxeoCUDFPkgDesc = null; Pattern linePattern = Pattern.compile(CUDFPackage.LINE_PATTERN); while (reader.ready()) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); log.debug("Parsing line >> " + line); if (line.trim().isEmpty()) { if (nuxeoCUDFPkgDesc == null) { throw new DependencyException("Invalid CUDF file starting with an empty line"); } map.put(nuxeoCUDFPkgDesc.getCUDFName() + "-" + nuxeoCUDFPkgDesc.getCUDFVersion(), nuxeoCUDFPkgDesc); nuxeoCUDFPkgDesc = null; } else { Matcher m = linePattern.matcher(line); if (!m.matches()) { throw new DependencyException("Invalid CUDF line: " + line); } String tag = m.group(1); if (tag.endsWith(":")) { tag += " "; } String value = m.group(2); if (nuxeoCUDFPkgDesc == null) { if (!CUDFPackage.TAG_PACKAGE.equals(tag)) { throw new DependencyException( "Invalid CUDF file not starting with " + CUDFPackage.TAG_PACKAGE); } nuxeoCUDFPkgDesc = new NuxeoCUDFPackageDescription(); nuxeoCUDFPkgDesc.setCUDFName(value); continue; } switch (tag) { case CUDFPackage.TAG_VERSION: nuxeoCUDFPkgDesc.setCUDFVersion(Integer.parseInt(value)); break; case CUDFPackage.TAG_INSTALLED: nuxeoCUDFPkgDesc.setInstalled(Boolean.parseBoolean(value)); break; case CUDFPackage.TAG_DEPENDS: nuxeoCUDFPkgDesc.setDependencies(parseCUDFDeps(value)); break; case CUDFPackage.TAG_CONFLICTS: nuxeoCUDFPkgDesc.setConflicts(parseCUDFDeps(value)); break; case CUDFPackage.TAG_PROVIDES: nuxeoCUDFPkgDesc.setProvides(parseCUDFDeps(value)); break; case CUDFPackage.TAG_REQUEST: case CUDFPackage.TAG_INSTALL: case CUDFPackage.TAG_REMOVE: case CUDFPackage.TAG_UPGRADE: log.debug("Ignore request stanza " + line); break; case CUDFPackage.TAG_PACKAGE: default: throw new DependencyException("Invalid CUDF line: " + line); } } } if (nuxeoCUDFPkgDesc != null) { // CUDF file without newline at end of file map.put(nuxeoCUDFPkgDesc.getCUDFName() + "-" + nuxeoCUDFPkgDesc.getCUDFVersion(), nuxeoCUDFPkgDesc); } return map; }
From source file:ffx.autoparm.ForceFieldFilter_2.java
private void parse(InputStream stream) { try {/*from ww w .j a va 2 s. c om*/ BufferedReader br = new BufferedReader(new InputStreamReader(stream)); while (br.ready()) { String input = br.readLine(); String tokens[] = input.trim().split(" +"); if (tokens != null) { String keyword = tokens[0].toUpperCase().replaceAll("-", "_"); boolean parsed = true; try { // Parse Keywords with a String value. ForceFieldString ffString = ForceFieldString.valueOf(keyword); forceField.addForceFieldString(ffString, tokens[1]); } catch (Exception e) { try { // Parse Keywords with a Double value. ForceFieldDouble ffDouble = ForceFieldDouble.valueOf(keyword); double value = Double.parseDouble(tokens[1]); forceField.addForceFieldDouble(ffDouble, value); } catch (Exception e2) { try { // Parse Keywords with an Integer value. ForceFieldInteger ffInteger = ForceFieldInteger.valueOf(keyword); int value = Integer.parseInt(tokens[1]); forceField.addForceFieldInteger(ffInteger, value); } catch (Exception e3) { try { // Parse Keywords with an Integer value. ForceFieldBoolean ffBoolean = ForceFieldBoolean.valueOf(keyword); boolean value = true; if (tokens.length > 1 && tokens[0].toUpperCase().endsWith("TERM")) { /** * Handle the token "ONLY" specially to * shut off all other terms. */ if (tokens[1].equalsIgnoreCase("ONLY")) { for (ForceFieldBoolean term : ForceFieldBoolean.values()) { if (term.toString().toUpperCase().endsWith("TERM")) { forceField.addForceFieldBoolean(term, false); } } } else if (tokens[1].equalsIgnoreCase("NONE")) { /** * Legacy support for the "NONE" * token. */ value = false; } else { value = Boolean.parseBoolean(tokens[1]); } } forceField.addForceFieldBoolean(ffBoolean, value); forceField.log(keyword); } catch (Exception e4) { parsed = false; } } } } if (!parsed) { try { ForceFieldType type = ForceFieldType.valueOf(tokens[0].toUpperCase()); switch (type) { case ATOM: parseAtom(input, tokens); break; case ANGLE: parseAngle(input, tokens); break; case BIOTYPE: parseBioType(input, tokens); break; case BOND: parseBond(input, tokens); break; case CHARGE: parseCharge(input, tokens); break; case MULTIPOLE: parseMultipole(input, tokens, br); break; case OPBEND: parseOPBend(input, tokens); break; case STRBND: parseStrBnd(input, tokens); break; case PITORS: parsePiTorsion(input, tokens); break; case TORSION: parseTorsion(input, tokens); break; case TORTORS: parseTorsionTorsion(input, tokens, br); break; case UREYBRAD: parseUreyBradley(input, tokens); break; case VDW: parseVDW(input, tokens); break; case POLARIZE: parsePolarize(input, tokens); break; default: logger.warning("ForceField type recognized, but not stored:" + type); } continue; } catch (Exception e) { //String message = "Exception parsing force field parametesr.\n"; //logger.log(Level.WARNING, message, e); } } } } br.close(); } catch (Exception e) { String message = "Error parsing force field parameters.\n"; logger.log(Level.SEVERE, message, e); } }