Java Code Examples for java.io.PrintStream#flush()

The following examples show how to use java.io.PrintStream#flush() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NoTalkbackSlimExceptionTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public final void testNoTalkbackSlimExceptionString() {
  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final PrintStream perr = new PrintStream(bos);
  Diagnostic.setLogStream(perr);
  try {
    final NoTalkbackSlimException e = new NoTalkbackSlimException(new RuntimeException(), ErrorType.INFO_ERROR, "really really long message");
    e.logException();
    perr.flush();
    //System.err.println(bos.toString());
    TestUtils.containsAll(bos.toString(), "really really long message");
  } finally {
    Diagnostic.setLogStream();
    perr.close();
  }

}
 
Example 2
Source File: SamUtilsTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void testReadGroupFailure() throws IOException {
  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final PrintStream logStream = new PrintStream(bos);
  Diagnostic.setLogStream(logStream);
  final File alignmentsDir = FileUtils.createTempDir("samheaderchecktest", "check");
  final File file1 = new File(alignmentsDir, OUT_SAM + 1);
  final File file2 = new File(alignmentsDir, OUT_SAM + 2);
  FileUtils.stringToFile("@HD" + TAB + "VN:1.0" + TAB + "SO:coordinate\n" + "@SQ" + TAB + "SN:gi" + TAB + "LN:30\n" + "@RG\tID:blah\tSM:sam1\tPL:IONTORRENT", file1);
  FileUtils.stringToFile("@HD" + TAB + "VN:1.0" + TAB + "SO:coordinate\n" + "@SQ" + TAB + "SN:gi" + TAB + "LN:30\n" + "@RG\tID:blah\tSM:sam2\tPL:IONTORRENT", file2);
  final ArrayList<File> files = new ArrayList<>();
  files.add(file1);
  files.add(file2);
  try {
    SamUtils.getUberHeader(files);
    fail();
  } catch (final NoTalkbackSlimException ntse) {
    assertEquals("1", ntse.getMessage());
  }

  logStream.flush();
  final String[] exp = {file2.getPath() + " contained read group with ID \"blah\" and sample \"sam2\" but"
  };
  TestUtils.containsAll(bos.toString(), exp);
  assertTrue(FileHelper.deleteAll(alignmentsDir));
}
 
Example 3
Source File: JarBackSlash.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void testJarList(String jarFile) throws IOException {
    List<String> argList = new ArrayList<String>();
    argList.add("-tvf");
    argList.add(jarFile);
    argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);

    String jarArgs[] = new String[argList.size()];
    jarArgs = argList.toArray(jarArgs);

    PipedOutputStream pipedOutput = new PipedOutputStream();
    PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
    PrintStream out = new PrintStream(pipedOutput);

    Main jarTool = new Main(out, System.err, "jar");
    if (!jarTool.run(jarArgs)) {
        fail("Could not list jar file.");
    }

    out.flush();
    check(pipedInput.available() > 0);
}
 
Example 4
Source File: FreeMarkerTemplateManagerSpec.java    From javalite with Apache License 2.0 6 votes vote down vote up
@Test
public void yieldShouldFailGracefullyIfNoContentProvided() {

    manager.setDefaultLayout("/layouts/default_layout_with_yeld");
    Map<String, Object> values = new HashMap<>();
    values.put("name", "Jim");

    StringWriter sw = new StringWriter();

    ByteArrayOutputStream bin = new ByteArrayOutputStream();
    PrintStream err = new PrintStream(bin);
    System.setErr(err);
    manager.merge(values, "/abc_controller/does_not_contain_content_for", sw);
    String generated = sw.toString();

    err.flush();

    a(XPathHelper.selectText("//title", generated)).shouldEqual("");
}
 
Example 5
Source File: JarBackSlash.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void testJarList(String jarFile) throws IOException {
    List<String> argList = new ArrayList<String>();
    argList.add("-tvf");
    argList.add(jarFile);
    argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);

    String jarArgs[] = new String[argList.size()];
    jarArgs = argList.toArray(jarArgs);

    PipedOutputStream pipedOutput = new PipedOutputStream();
    PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
    PrintStream out = new PrintStream(pipedOutput);

    Main jarTool = new Main(out, System.err, "jar");
    if (!jarTool.run(jarArgs)) {
        fail("Could not list jar file.");
    }

    out.flush();
    check(pipedInput.available() > 0);
}
 
Example 6
Source File: KeyUtil.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
/**
 * Produce a string that is a decomposition of the given x.509 or ASN1 encoded
 * object.  For learning and debugging purposes.
 */
public static String decomposeASN1Encoded(ByteString input)
  throws Exception
{
  ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(byte_out);

  ASN1StreamParser parser = new ASN1StreamParser(input.toByteArray());
  out.println("ASN1StreamParser");

  while(true)
  {
    ASN1Encodable encodable = parser.readObject();
    if (encodable == null) break;

    decomposeEncodable(encodable, 2, out);
  }

  out.flush();
  return new String(byte_out.toByteArray());

}
 
Example 7
Source File: VersionCommand.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Main function, entry-point for version command.
 * @param out regular output stream, only for passing to delegate help printers
 * @return shell return code 0 for success, anything else for failure
 */
public static int mainInit(final PrintStream out) {
  try {
    out.print(getVersion());
  } finally {
    out.flush();
  }
  return 0;
}
 
Example 8
Source File: CommandLine.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Print command line usage information to given stream.
 *
 * @param os
 *            the output stream
 */
public void printUsage(OutputStream os) {
    int count = 0;
    PrintStream out = UTF8.printStream(os);
    for (String option : optionList) {

        if (optionGroups.containsKey(count)) {
            out.println("  " + optionGroups.get(count));
        }
        count++;

        if (unlistedOptions.contains(option)) {
            continue;
        }
        out.print("    ");

        StringBuilder buf = new StringBuilder();
        buf.append(option);
        if (optionExtraPartSynopsisMap.get(option) != null) {
            String optionExtraPartSynopsis = optionExtraPartSynopsisMap.get(option);
            buf.append("[:");
            buf.append(optionExtraPartSynopsis);
            buf.append("]");
        }
        if (requiresArgumentSet.contains(option)) {
            buf.append(" <");
            buf.append(argumentDescriptionMap.get(option));
            buf.append(">");
        }
        printField(out, buf.toString(), maxWidth + 1);

        out.println(optionDescriptionMap.get(option));
    }
    out.flush();
}
 
Example 9
Source File: ThrowableTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testStackTraceWithPrintStream() throws Exception {
  Exception testException = new Exception("test exception");
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(baos);
  testException.printStackTrace(out);
  out.flush();
  String trace = baos.toString("UTF-8");
  assertTrue(trace.contains("com.google.j2objc.ThrowableTest.testStackTraceWithPrintStream("));
}
 
Example 10
Source File: SanityManager.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void printPagedOutput(final PrintStream out,
    final InputStream in, final String output, final int maxLines,
    final String continuePrompt, final boolean noecho) {
  int lineStart = 0;
  int numLines = 0;
  char c;
  for (int index = 0; index < output.length(); index++) {
    c = output.charAt(index);
    if (c == '\n') {
      // got end of line
      out.println(output.substring(lineStart, index));
      out.flush();
      lineStart = index + 1;
      if (++numLines >= maxLines && lineStart < output.length()) {
        // wait for user input before further output
        out.print(continuePrompt);
        out.flush();
        String chars = ClientSharedUtils.getJdkHelper()
            .readChars(in, noecho);
        out.println();
        if (chars != null && chars.length() > 0
            && (chars.charAt(0) == 'q' || chars.charAt(0) == 'Q')) {
          out.flush();
          return;
        }
        numLines = 0;
      }
    }
  }
  // print any remaining string
  if (lineStart < output.length()) {
    out.println(output.substring(lineStart));
  }
  out.flush();
}
 
Example 11
Source File: SimpleMemoryAllocatorImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  ByteArrayOutputStream baos = new ByteArrayOutputStream(64*1024);
  PrintStream ps = new PrintStream(baos);
  ps.print(this.getMessage());
  ps.print(" rc=");
  ps.print(this.rc);
  if (this.dupCount > 0) {
    ps.print(" dupCount=");
    ps.print(this.dupCount);
  }
  ps.print(" by ");
  ps.print(this.threadName);
  if (this.owner != null) {
    ps.print(" owner=");
    ps.print(this.owner.getClass().getName());
    ps.print("@");
    ps.print(System.identityHashCode(this.owner));
  }
  ps.println(": ");
  StackTraceElement[] trace = getStackTrace();
  // skip the initial elements from SimpleMemoryAllocatorImpl
  int skip=0;
  for (int i=0; i < trace.length; i++) {
    if (!trace[i].getClassName().contains("SimpleMemoryAllocatorImpl")) {
      skip = i;
      break;
    }
  }
  for (int i=skip; i < trace.length; i++) {
    ps.println("\tat " + trace[i]);
  }
  ps.flush();
  return baos.toString();
}
 
Example 12
Source File: PrettyPrinterTest.java    From plunger with Apache License 2.0 5 votes vote down vote up
@Test
public void printToDefaultHeader() throws Exception {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  PrintStream printStream = new PrintStream(bytes);
  new PrettyPrinter(data).printTo(printStream);

  printStream.flush();
  printStream.close();

  assertThat(bytes.toString("UTF-8"), is("A\tB\n1\t100\n2\t200\n"));
}
 
Example 13
Source File: RouteReloaderUnitTest.java    From xio with Apache License 2.0 5 votes vote down vote up
private String rawCreateConf(String value, String filename) throws FileNotFoundException {
  File output = new File(temporaryFolder.getRoot(), filename);
  PrintStream out = new PrintStream(output);
  out.append(value);
  out.flush();
  out.close();
  return output.getAbsolutePath();
}
 
Example 14
Source File: ApexCli.java    From Bats with Apache License 2.0 5 votes vote down vote up
private void printJson(String json) throws IOException
{
  PrintStream os = getOutputPrintStream();

  if (jsonp != null) {
    os.println(jsonp + "(" + json + ");");
  } else {
    os.println(json);
  }
  os.flush();
  closeOutputPrintStream(os);
}
 
Example 15
Source File: ControlCommand.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public int run(final Namespace options, final List<Target> targets, final PrintStream out,
               final PrintStream err, final String username, final boolean json,
               final BufferedReader stdin)
    throws Exception {
  boolean allSuccessful = true;

  boolean isFirst = true;

  // TODO (dxia) The json = true branches below are a hack to get valid JSON for multiple domains.
  // Refactor concrete command implementations later to return an Object that can then be put into
  // a {"$DOMAIN": $VALUE} dict before json serializing and returning it.

  // Execute the control command over each target cluster
  final Iterator<Target> targetIterator = targets.iterator();
  while (targetIterator.hasNext()) {
    final Target target = targetIterator.next();

    if (targets.size() > 1) {
      if (!json) {
        final List<URI> endpoints = target.getEndpointSupplier().get();
        final String header = format("%s (%s)", target.getName(), endpoints);
        out.println(header);
        out.println(repeat("-", header.length()));
        out.flush();
      } else {
        if (isFirst) {
          out.println("{");
          isFirst = false;
        }
        out.println("\"" + target.getName() + "\": ");
      }
    }

    final boolean successful = run(options, target, out, err, username, json, stdin);
    if (shortCircuit && !successful) {
      return 1;
    }
    allSuccessful &= successful;

    if (targets.size() > 1) {
      if (!json) {
        out.println();
      } else {
        if (targetIterator.hasNext()) {
          out.println(",\n");
        } else {
          out.println("}");
        }
      }
    }
  }

  return allSuccessful ? 0 : 1;
}
 
Example 16
Source File: Log.java    From pluotsorbet with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Print the specified message to the enabled streams. A <code>null</code>
 * message will be replaced with an empty string.
 * 
 * @param printObj if <code>true</code> then then the <code>obj</code> Object will be included in the message.
 * @param message the message to print.
 * @param obj the optional object to include in the message.
 * @param loggerName the optional logger name, if <code>null</code> then this will not be included.
 * @param levelName name of the logging level, must not be <code>null</code>.
 */
public static synchronized void print(boolean printObj, String message, Object obj,
        String loggerName, String levelName) 
{
    
    if (delegate != null) {
        delegate.print(printObj, message, obj, loggerName, levelName);
        return;
    }
    
    String objStr = (obj == null ? "NULL" : obj.toString());
    
    if (message == null) {
        message = "";
    }
    
    for (int i = 0; i < streams.length; i++) {
        PrintStream ps = streams[i];
        
        if (ps != null) {
            printTimeStamp(ps, false);
            ps.print(' ');
            
            if (loggerName != null) {
                ps.print('[');
                ps.print(loggerName);
                ps.print("] ");
            }
            
            ps.print(levelName);
            ps.print(' ');
            
            ps.print(message);
          
            if (printObj) {
                ps.print(": ");
                ps.print(objStr);
            }
            
            ps.println();
            ps.flush();
        }
    }
}
 
Example 17
Source File: FingramsKEEL.java    From KEEL with GNU General Public License v3.0 4 votes vote down vote up
private int runProcess(String command, String tempOutFile) {
	int exitVal = -1;
	Process p = null;
	try {
		// System.out.println("runProcess: 1 -> "+command);
		Runtime rt = Runtime.getRuntime();

		// System.out.println("runProcess: 2 -> "+command);
		// Date d= new Date(System.currentTimeMillis());
		// System.out.println("runProcess: T1 -> "+DateFormat.getDateTimeInstance().format(d));
		p = rt.exec(command);
		// d= new Date(System.currentTimeMillis());
		// System.out.println("runProcess: T2 -> "+DateFormat.getDateTimeInstance().format(d));
		// cleaning output buffer
		InputStream is = p.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);

		FileOutputStream fos = new FileOutputStream(new File("."
				+ System.getProperty("file.separator") + tempOutFile));
		PrintStream pOutFile = new PrintStream(fos);
		String line;
		// d= new Date(System.currentTimeMillis());
		// System.out.println("runProcess: T3 -> "+DateFormat.getDateTimeInstance().format(d));
		while ((line = br.readLine()) != null)
			pOutFile.println(line);

		br.close();
		pOutFile.flush();
		pOutFile.close();
		fos.close();
		exitVal = p.waitFor();

		// System.out.println("runProcess: 3");
		is.close();
		isr.close();
		// p.waitFor();
		// System.out.println("runProcess: waiting.......");
		// d= new Date(System.currentTimeMillis());
		// System.out.println("runProcess: T4 -> "+DateFormat.getDateTimeInstance().format(d));
		// System.out.println("runProcess: 4");
	} catch (Throwable e) {
		e.printStackTrace();
		p.destroy();
	}
	// System.out.println("runProcess: 5");
	return exitVal;
}
 
Example 18
Source File: JarReorder.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private void run(String args[]) {

        int arglen = args.length;
        int argpos = 0;

        // Look for "-o outputfilename" option
        if (arglen > 0) {
            if (arglen >= 2 && args[0].equals("-o")) {
                try {
                    out = new PrintStream(new FileOutputStream(args[1]));
                } catch (FileNotFoundException e) {
                    System.err.println("Error: " + e.getMessage());
                    e.printStackTrace(System.err);
                    System.exit(1);
                }
                argpos += 2;
                arglen -= 2;
            } else {
                System.err.println("Error: Illegal arg count");
                System.exit(1);
            }
        } else {
            out = System.out;
        }

        // Should be 2 or more args left
        if (arglen <= 2) {
            usage();
            System.exit(1);
        }

        // Read the ordered set of files to be included in rt.jar.
        // Read the set of files/directories to be excluded from rt.jar.
        String classListFile = args[argpos];
        String excludeListFile = args[argpos + 1];
        argpos += 2;
        arglen -= 2;

        // Create 2 lists and a set of processed files
        List<String> orderList = readListFromFile(classListFile, true);
        List<String> excludeList = readListFromFile(excludeListFile, false);
        Set<String> processed = new HashSet<String>();

        // Create set of all files and directories excluded, then expand
        //   that list completely
        Set<String> excludeSet = new HashSet<String>(excludeList);
        Set<String> allFilesExcluded = expand(null, excludeSet, processed);

        // Indicate all these have been processed, orderList too, kept to end.
        processed.addAll(orderList);

        // The remaining arguments are names of files/directories to be included
        // in the jar file.
        Set<String> inputSet = new HashSet<String>();
        for (int i = 0; i < arglen; ++i) {
            String name = args[argpos + i];
            name = cleanPath(new File(name));
            if ( name != null && name.length() > 0 && !inputSet.contains(name) ) {
                inputSet.add(name);
            }
        }

        // Expand file/directory input so we get a complete set (except ordered)
        //   Should be everything not excluded and not in order list.
        Set<String> allFilesIncluded = expand(null, inputSet, processed);

        // Create simple sorted list so we can add ordered items at end.
        List<String> allFiles = new ArrayList<String>(allFilesIncluded);
        Collections.sort(allFiles);

        // Now add the ordered set to the end of the list.
        // Add in REVERSE ORDER, so that the first element is closest to
        // the end (and the index).
        for (int i = orderList.size() - 1; i >= 0; --i) {
            String s = orderList.get(i);
            if (allFilesExcluded.contains(s)) {
                // Disable this warning until 8005688 is fixed
                // System.err.println("Included order file " + s
                //    + " is also excluded, skipping.");
            } else if (new File(s).exists()) {
                allFiles.add(s);
            } else {
                System.err.println("Included order file " + s
                    + " missing, skipping.");
            }
        }

        // Print final results.
        for (String str : allFiles) {
            out.println(str);
        }
        out.flush();
        out.close();
    }
 
Example 19
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/** Writes a .SF file with a digest to the manifest. */
private void writeSignatureFile(SignatureOutputStream out)
        throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");

    BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    PrintStream print = new PrintStream(
            new DigestOutputStream(new ByteArrayOutputStream(), md),
            true, SdkConstants.UTF_8);

    // Digest of the entire manifest
    mManifest.write(print);
    print.flush();
    main.putValue(DIGEST_MANIFEST_ATTR, base64.encode(md.digest()));

    Map<String, Attributes> entries = mManifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue(DIGEST_ATTR, base64.encode(md.digest()));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }

    sf.write(out);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((out.size() % 1024) == 0) {
        out.write('\r');
        out.write('\n');
    }
}
 
Example 20
Source File: ExceptionUtils.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>Prints a compact stack trace for the root cause of a throwable.</p>
 *
 * <p>The compact stack trace starts with the root cause and prints
 * stack frames up to the place where it was caught and wrapped.
 * Then it prints the wrapped exception and continues with stack frames
 * until the wrapper exception is caught and wrapped again, etc.</p>
 *
 * <p>The output of this method is consistent across JDK versions.
 * Note that this is the opposite order to the JDK1.4 display.</p>
 *
 * <p>The method is equivalent to <code>printStackTrace</code> for throwables
 * that don't have nested causes.</p>
 *
 * @param throwable  the throwable to output, may be null
 * @param stream  the stream to output to, may not be null
 * @throws IllegalArgumentException if the stream is <code>null</code>
 * @since 2.0
 */
public static void printRootCauseStackTrace(Throwable throwable, PrintStream stream) {
    if (throwable == null) {
        return;
    }
    if (stream == null) {
        throw new IllegalArgumentException("The PrintStream must not be null");
    }
    String trace[] = getRootCauseStackTrace(throwable);
    for (String element : trace) {
        stream.println(element);
    }
    stream.flush();
}