Java 类java.io.PrintStream 实例源码
项目:OpenJSharp
文件:PSPrinterJob.java
/**
* This is called from the Java Plug-in to print an Applet's
* contents as EPS to a postscript stream provided by the browser.
* @param applet the applet component to print.
* @param stream the print stream provided by the plug-in
* @param x the x location of the applet panel in the browser window
* @param y the y location of the applet panel in the browser window
* @param w the width of the applet panel in the browser window
* @param h the width of the applet panel in the browser window
*/
public PluginPrinter(Component applet,
PrintStream stream,
int x, int y, int w, int h) {
this.applet = applet;
this.epsTitle = "Java Plugin Applet";
this.stream = stream;
bx = x;
by = y;
bw = w;
bh = h;
width = applet.size().width;
height = applet.size().height;
epsPrinter = new EPSPrinter(this, epsTitle, stream,
0, 0, width, height);
}
项目:dremio-oss
文件:TestNewTextReader.java
@Test
public void testShortFile() throws Exception {
// short file: 2 characters worth (shorter than the UTF-8 BOM), without BOMs
File testFolder = tempDir.newFolder("testShortFilesFolder");
File testFile2 = new File(testFolder, "twobyte.csv");
PrintStream p2 = new PrintStream(testFile2);
p2.print("y\n");
p2.close();
testBuilder()
.sqlQuery(String.format("select * from table(dfs.`%s` (type => 'text', " +
"fieldDelimiter => ',', lineDelimiter => '\n', extractHeader => true)) ",
testFile2.getAbsolutePath()))
.unOrdered()
.baselineColumns("y")
.expectsEmptyResultSet()
.go();
}
项目:ditb
文件:TestImportExport.java
/**
* test main method. Import should print help and call System.exit
*/
@Test
public void testImportMain() throws Exception {
PrintStream oldPrintStream = System.err;
SecurityManager SECURITY_MANAGER = System.getSecurityManager();
LauncherSecurityManager newSecurityManager= new LauncherSecurityManager();
System.setSecurityManager(newSecurityManager);
ByteArrayOutputStream data = new ByteArrayOutputStream();
String[] args = {};
System.setErr(new PrintStream(data));
try {
System.setErr(new PrintStream(data));
Import.main(args);
fail("should be SecurityException");
} catch (SecurityException e) {
assertEquals(-1, newSecurityManager.getExitCode());
assertTrue(data.toString().contains("Wrong number of arguments:"));
assertTrue(data.toString().contains("-Dimport.bulk.output=/path/for/output"));
assertTrue(data.toString().contains("-Dimport.filter.class=<name of filter class>"));
assertTrue(data.toString().contains("-Dimport.bulk.output=/path/for/output"));
assertTrue(data.toString().contains("-Dmapreduce.reduce.speculative=false"));
} finally {
System.setErr(oldPrintStream);
System.setSecurityManager(SECURITY_MANAGER);
}
}
项目:alvisnlp
文件:CCGBase.java
protected void printSentence(PrintStream out, StringBuilder sb, Layer sentence, boolean withPos) {
boolean notFirst = false;
for (Annotation word : sentence) {
String form = word.getLastFeature(formFeatureName);
if (form.isEmpty())
continue;
sb.setLength(0);
if (notFirst)
sb.append(' ');
else
notFirst = true;
Strings.escapeWhitespaces(sb, form, '|', '.');
if (withPos) {
sb.append('|');
sb.append(word.getLastFeature(posFeatureName));
}
out.print(sb);
}
out.println();
}
项目:omero-ms-queue
文件:Create.java
@Override
public ExitCode exec(PrintStream out) throws CannotCreateSessionException,
PermissionDeniedException, ServerError {
client c = newClient();
ServiceFactoryPrx serviceFactory = c.createSession();
serviceFactory.setSecurityPassword(password);
Session initialSession = serviceFactory.getSessionService()
.getSession(c.getSessionId());
Session newSession = serviceFactory.getSessionService()
.createUserSession(0,
timeToIdle(initialSession),
group(initialSession));
c.killSession(); // close initial session.
out.print(newSession.getUuid().getValue());
return ExitCode.Ok;
}
项目:vogar
文件:TestRunner.java
public void run() throws IOException {
final TargetMonitor monitor = useSocketMonitor
? TargetMonitor.await(monitorPort)
: TargetMonitor.forPrintStream(System.out);
PrintStream monitorPrintStream = new PrintStreamDecorator(System.out) {
@Override public void print(String str) {
monitor.output(str != null ? str : "null");
}
};
System.setOut(monitorPrintStream);
System.setErr(monitorPrintStream);
try {
run(monitor);
} catch (Throwable internalError) {
internalError.printStackTrace(monitorPrintStream);
} finally {
monitor.close();
}
}
项目:incubator-netbeans
文件:MIMESupportTest.java
public void testFAttrs() throws Exception {
FileObject resolver = FileUtil.createData(FileUtil.getConfigRoot(), "Services/MIMEResolver/r.xml");
resolver.setAttribute("position", 2);
OutputStream os = resolver.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println("<!DOCTYPE MIME-resolver PUBLIC '-//NetBeans//DTD MIME Resolver 1.0//EN' 'http://www.netbeans.org/dtds/mime-resolver-1_0.dtd'>");
ps.println("<MIME-resolver>");
ps.println(" <file>");
ps.println(" <fattr name='foo' text='yes'/>");
ps.println(" <resolver mime='text/x-boo'/>");
ps.println(" </file>");
ps.println("</MIME-resolver>");
os.close();
FileObject foo = FileUtil.createMemoryFileSystem().getRoot().createData("somefile");
assertEquals("content/unknown", foo.getMIMEType());
foo.setAttribute("foo", Boolean.FALSE);
assertEquals("content/unknown", foo.getMIMEType());
foo.setAttribute("foo", "no");
assertEquals("content/unknown", foo.getMIMEType());
foo.setAttribute("foo", "yes");
assertEquals("text/x-boo", foo.getMIMEType());
}
项目:ramus
文件:Manager.java
protected void stop() {
PrintStream printStream = new PrintStream(out);
printStream.println("stop");
printStream.flush();
printStream.close();
restartItem.setEnabled(false);
stopItem.setEnabled(false);
startItem.setEnabled(true);
}
项目:MaxSim
文件:CommandProcessor.java
public CommandProcessor(DebuggerInterface debugger, BufferedReader in, PrintStream out, PrintStream err) {
this.debugger = debugger;
this.agent = debugger.getAgent();
this.in = in;
this.out = out;
this.err = err;
for (int i = 0; i < commandList.length; i++) {
Command c = commandList[i];
if (commands.get(c.name) != null) {
throw new InternalError(c.name + " has multiple definitions");
}
commands.put(c.name, c);
}
if (debugger.isAttached()) {
postAttach();
}
}
项目:vscrawler
文件:AVM.java
private void printTo(PrintStream ps, int num_args) {
// print items from the top of the stack
// # of items
if (num_args == 0) {
// display $0
ps.println(jrt.jrtGetInputField(0));
} else {
// cache $OFS to separate fields below
// (no need to execute getOFS for each field)
String ofs_string = getOFS().toString();
for (int i = 0; i < num_args; i++) {
String s = JRT.toAwkStringForOutput(pop(), getOFMT().toString());
ps.print(s);
// if more elements, display $FS
if (i < num_args - 1) {
// use $OFS to separate fields
ps.print(ofs_string);
}
}
ps.println();
}
// for now, since we are not using Process.waitFor()
if (IS_WINDOWS) {
ps.flush();
}
}
项目:cactoos
文件:BytesOf.java
/**
* Ctor.
* @param error The exception to serialize
* @param charset Charset
*/
public BytesOf(final Throwable error, final CharSequence charset) {
this(
() -> {
try (
final ByteArrayOutputStream baos =
new ByteArrayOutputStream()
) {
error.printStackTrace(
new PrintStream(baos, true, charset.toString())
);
return baos.toByteArray();
}
}
);
}
项目:alvisnlp
文件:AbstractWapiti.java
private void writeInput(Corpus corpus) throws IOException {
EvaluationContext evalCtx = new EvaluationContext(logger);
WapitiResolvedObjects resObj = getResolvedObjects();
try (PrintStream ps = new PrintStream(inputFile)) {
for (Section sec : Iterators.loop(sectionIterator(evalCtx, corpus))) {
for (Layer sentence : sec.getSentences(tokenLayerName, sentenceLayerName)) {
for (Annotation a : sentence) {
boolean notFirst = false;
for (Evaluator feat : resObj.features) {
if (notFirst) {
ps.print('\t');
}
else {
notFirst = true;
}
String value = feat.evaluateString(evalCtx, a);
ps.print(value);
}
ps.println();
}
ps.println();
}
}
}
}
项目:hadoop-oss
文件:TestCount.java
private void processMultipleStorageTypesContent(boolean quotaUsageOnly)
throws Exception {
Path path = new Path("mockfs:/test");
when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat);
PathData pathData = new PathData(path.toString(), conf);
PrintStream out = mock(PrintStream.class);
Count count = new Count();
count.out = out;
LinkedList<String> options = new LinkedList<String>();
options.add(quotaUsageOnly ? "-u" : "-q");
options.add("-t");
options.add("SSD,DISK");
options.add("dummy");
count.processOptions(options);
count.processPath(pathData);
String withStorageType = BYTES + StorageType.SSD.toString()
+ " " + StorageType.DISK.toString() + " " + pathData.toString();
verify(out).println(withStorageType);
verifyNoMoreInteractions(out);
}
项目:alvisnlp
文件:EnjuExternal.java
private void writeSentence(PrintStream ps, Layer sent) {
boolean notFirst = false;
for (Annotation word : sent) {
if (notFirst) {
ps.print(' ');
}
else {
notFirst = true;
}
writeToken(ps, word.getLastFeature(enjuParser.getWordFormFeatureName()));
if (word.hasFeature(enjuParser.getPosFeatureName())) {
ps.print('/');
writeToken(ps, word.getLastFeature(enjuParser.getPosFeatureName()));
}
}
ps.println();
}
项目:migration-tooling
文件:WorkspaceWriter.java
@Override
public void write(Collection<Rule> rules) {
try (PrintStream workspaceStream = new PrintStream(workspaceFile);
PrintStream buildStream = new PrintStream(buildFile)) {
writeWorkspace(workspaceStream, rules);
writeBuild(buildStream, rules);
} catch (IOException e) {
logger.severe(
"Could not write WORKSPACE and BUILD files to " + buildFile.getParent() + ": "
+ e.getMessage());
return;
}
System.err.println("Wrote:\n" + workspaceFile + "\n" + buildFile);
}
项目:hadoop
文件:TestContainerLaunch.java
/**
* Test that script exists with non-zero exit code when command fails.
* @throws IOException
*/
@Test (timeout = 10000)
public void testShellScriptBuilderNonZeroExitCode() throws IOException {
ShellScriptBuilder builder = ShellScriptBuilder.create();
builder.command(Arrays.asList(new String[] {"unknownCommand"}));
File shellFile = Shell.appendScriptExtension(tmpDir, "testShellScriptBuilderError");
PrintStream writer = new PrintStream(new FileOutputStream(shellFile));
builder.write(writer);
writer.close();
try {
FileUtil.setExecutable(shellFile, true);
Shell.ShellCommandExecutor shexc = new Shell.ShellCommandExecutor(
new String[]{shellFile.getAbsolutePath()}, tmpDir);
try {
shexc.execute();
fail("builder shell command was expected to throw");
}
catch(IOException e) {
// expected
System.out.println("Received an expected exception: " + e.getMessage());
}
}
finally {
FileUtil.fullyDelete(shellFile);
}
}
项目:OpenJSharp
文件:ServerTool.java
public void printCommandHelp(PrintStream out, boolean helpType)
{
if (helpType == longHelp) {
out.println(CorbaResourceUtil.getText("servertool.register"));
} else {
out.println(CorbaResourceUtil.getText("servertool.register1"));
}
}
项目:RefDiff
文件:RefactoringSet.java
public void printSourceCode(PrintStream pw) {
pw.printf("new RefactoringSet(\"%s\", \"%s\")", project, revision);
for (RefactoringRelationship r : refactorings) {
pw.printf("\n .add(RefactoringType.%s, \"%s\", \"%s\")", r.getRefactoringType().toString(), r.getEntityBefore(), r.getEntityAfter());
}
pw.println(";");
}
项目:loom
文件:WordIndex.java
void printWordIndexInOrder(OutputStream stream) {
PrintStream printer = new PrintStream(stream);
for (String key : new TreeSet<String>(indexTable.keySet())) {
printer.printf("%s=%s\n", key, indexTable.get(key));
}
}
项目:dice
文件:RndTool.java
private static void printRandoms(Arg arguments, Encoder encoder, DeterministicRandomBitGenerator drbg, long startTime) throws IOException {
boolean useAutoColumn = false;
if (arguments.count() == null) {
arguments = arguments.toBuilder().count(Arg.DEFAULT_COUNT).build();
useAutoColumn = true;
}
PrintStream printStream = getStream(arguments);
try {
long startRndGen = System.currentTimeMillis();
long actualCount;
if (arguments.robot()) {
actualCount = new ColumnRenderer(encoder.getEncoderFormat(), genFromArg(arguments, encoder, drbg)).renderSingleColumn(arguments.count(), printStream);
} else if (useAutoColumn) {
actualCount = new ColumnRenderer(encoder.getEncoderFormat(), genFromArg(arguments, encoder, drbg)).renderAutoColumn(arguments.count(), printStream, arguments.outFile() != null);
} else {
actualCount = new ColumnRenderer(encoder.getEncoderFormat(), genFromArg(arguments, encoder, drbg)).render(arguments.count(), printStream, arguments.outFile() != null);
}
println(getSummary(System.currentTimeMillis() - startTime, System.currentTimeMillis() - startRndGen, actualCount * arguments.length()), arguments);
} finally {
if (printStream != System.out) {
printStream.close();
}
}
}
项目:openjdk-jdk10
文件:Scan.java
public Scan(PrintStream out,
PrintStream err,
List<String> classPath,
DeprDB db,
boolean verbose) {
this.out = out;
this.err = err;
this.classPath = classPath;
this.db = db;
this.verbose = verbose;
ClassFinder f = new ClassFinder(verbose);
// TODO: this isn't quite right. If we've specified a release other than the current
// one, we should instead add a reference to the symbol file for that release instead
// of the current image. The problems are a) it's unclear how to get from a release
// to paths that reference the symbol files, as this might be internal to the file
// manager; and b) the symbol file includes .sig files, not class files, which ClassFile
// might not be able to handle.
f.addJrt();
for (String name : classPath) {
if (name.endsWith(".jar")) {
f.addJar(name);
} else {
f.addDir(name);
}
}
finder = f;
}
项目:deployment-recorder-extension
文件:PomReadIT.java
@BeforeMethod
public void beforeMethod() {
consoleOutputStdErr = new StringBuilder();
consoleOutputStdOut = new StringBuilder();
originalStdErr = System.err;
originalStdOut = System.out;
PrintStream interceptorStdOut = new InterceptorStdOut(originalStdOut);
PrintStream interceptorStdErr = new InterceptorStdErr(originalStdErr);
System.setOut(interceptorStdOut);
System.setErr(interceptorStdErr);
}
项目:V8LogScanner
文件:TestCmdAppl.java
@Test
public void testStartCursorOp() throws LogScannerClientNotFoundServer, LanServerNotStarted {
//out
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(outStream);
//in
StringBuilder sb = new StringBuilder();
sb.append("1"); //1. Cursor log scanning(recommends)
sb.append("\n1"); //1. SELECT TOP[100] FROM location[0]
sb.append("\n3"); //3. Add own log location
sb.append(String.format("\n%s", logFileName)); // Here we print log location
sb.append("\nq"); //9. Start
sb.append("\n");
ByteBuffer bytes = Charset.forName("UTF-8").encode(sb.toString());
ByteArrayInputStream in = new ByteArrayInputStream(bytes.array());
ApplConsole appl = new ApplConsole(in, out);
V8LogScannerAppl scannerAppl = V8LogScannerAppl.instance();
// cancel reset client so that it did not clear ScanProfile
ClientsManager manager = new ClientsManager();
ClientsManager mockedManager = Mockito.spy(manager);
Mockito.doNothing().when(mockedManager).resetRemoteClients();
scannerAppl.setApplConsole(appl, mockedManager);
scannerAppl.runAppl();
V8LogFileConstructor.deleteLogFile(logFileName);
}
项目:xcc
文件:InstrInfoEmitter.java
private static void printBarriers(ArrayList<Record> barriers, int num, PrintStream os)
{
os.printf("\tpublic static final TargetRegisterClass[] barriers%d = { ", num);
int e = barriers.size();
if (e > 0)
{
os.printf("%sRegisterClass", barriers.get(0).getName());
for(int i = 1; i != e; ++i)
{
os.printf(", %sRegisterClass", barriers.get(i).getName());
}
}
os.printf("};\n");
}
项目:OpenJSharp
文件:BandStructure.java
static void printArrayTo(PrintStream ps, Entry[] cpMap, int start, int end, boolean showTags) {
StringBuffer buf = new StringBuffer();
int len = end-start;
for (int i = 0; i < len; i++) {
Entry e = cpMap[start+i];
ps.print(start+i); ps.print("=");
if (showTags) { ps.print(e.tag); ps.print(":"); }
String s = e.stringValue();
buf.setLength(0);
for (int j = 0; j < s.length(); j++) {
char ch = s.charAt(j);
if (!(ch < ' ' || ch > '~' || ch == '\\')) {
buf.append(ch);
} else if (ch == '\\') {
buf.append("\\\\");
} else if (ch == '\n') {
buf.append("\\n");
} else if (ch == '\t') {
buf.append("\\t");
} else if (ch == '\r') {
buf.append("\\r");
} else {
String str = "000"+Integer.toHexString(ch);
buf.append("\\u").append(str.substring(str.length()-4));
}
}
ps.println(buf);
}
}
项目:hadoop
文件:GetGroupsTestBase.java
private String runTool(Configuration conf, String[] args, boolean success)
throws Exception {
ByteArrayOutputStream o = new ByteArrayOutputStream();
PrintStream out = new PrintStream(o, true);
try {
int ret = ToolRunner.run(getTool(out), args);
assertEquals(success, ret == 0);
return o.toString();
} finally {
o.close();
out.close();
}
}
项目:ZooKeeper
文件:IOUtils.java
/**
* Copies from one stream to another.
*
* @param in
* InputStrem to read from
* @param out
* OutputStream to write to
* @param buffSize
* the size of the buffer
*/
public static void copyBytes(InputStream in, OutputStream out, int buffSize)
throws IOException {
PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
byte buf[] = new byte[buffSize];
int bytesRead = in.read(buf);
while (bytesRead >= 0) {
out.write(buf, 0, bytesRead);
if ((ps != null) && ps.checkError()) {
throw new IOException("Unable to write to output stream.");
}
bytesRead = in.read(buf);
}
}
项目:BiglyBT
文件:Pairing.java
@Override
public void printHelpExtra(PrintStream out, List args) {
out.println("> -----");
out.println("Subcommands:");
out.println("enable\tEnable remote pairing");
out.println("disable\tDisable remote pairing");
out.println("> -----");
}
项目:migration-tooling
文件:WorkspaceWriterTest.java
@Test
public void testHeaders() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
WorkspaceWriter writer = new WorkspaceWriter(
new String[]{"--artifact=x:y:1.2.3", "--artifact=a:b:3.2.1"},
System.getenv("TEST_TMPDIR"));
writer.writeWorkspace(ps, Sets.newHashSet());
assertThat(baos.toString(String.valueOf(Charset.defaultCharset()))).contains(
"# generate_workspace --artifact=x:y:1.2.3 --artifact=a:b:3.2.1");
}
项目:Jar2Java
文件:JavaSourceTextPrinter.java
public JavaSourceTextPrinter(CommonPreferences preferences, PrintStream printStream) {
this.preferences = preferences;
this.printStream = printStream;
this.maxLineNumber = 0;
this.majorVersion = 0;
this.minorVersion = 0;
this.indentationCount = 0;
}
项目:openNaEF
文件:DumpCommand.java
private void dump(PrintStream out, EntityDto dto) {
out.println(render(dto));
for (String attrName : dto.getAttributeNames()) {
Object attrValue = dto.getValue(attrName);
print(out, " ", attrName, attrValue);
}
}
项目:jdk8u-jdk
文件:CategoryClassFile.java
@Override public void writeBeginning(final PrintStream out) {
String targetCls = category.category.superClass.getFullPath();
out.format("\tpublic %1$s(final %2$s obj, final %3$s runtime) {\n" +
"\t\tsuper(obj, runtime);\n" +
"\t}\n",
className, targetCls, JObjCRuntime.class.getCanonicalName());
super.writeBeginning(out);
}
项目:xcc
文件:Init.java
@Override
public void print(PrintStream os)
{
os.print("[");
for (int i = 0, e = values.size(); i < e; i++)
{
if (i != 0) os.print(", ");
os.print(values.get(i));
}
os.print("]");
}
项目:elasticsearch_my
文件:PainlessDocGenerator.java
/**
* Emit an external link to Javadoc for a {@link Method}.
*
* @param root name of the root uri variable
*/
private static void emitJavadocLink(PrintStream stream, String root, Method method) {
stream.print("link:{");
stream.print(root);
stream.print("-javadoc}/");
stream.print((method.augmentation ? Augmentation.class : method.owner.clazz).getName().replace('.', '/'));
stream.print(".html#");
stream.print(methodName(method));
stream.print("%2D");
boolean first = true;
if (method.augmentation) {
first = false;
stream.print(method.owner.clazz.getName());
}
for (Type arg: method.arguments) {
if (first) {
first = false;
} else {
stream.print("%2D");
}
stream.print(arg.struct.clazz.getName());
if (arg.dimensions > 0) {
stream.print(":A");
}
}
stream.print("%2D");
}
项目:openjdk-jdk10
文件:IdGeneratorTest.java
public JShell.Builder getBuilder() {
TestingInputStream inStream = new TestingInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
return JShell.builder()
.in(inStream)
.out(new PrintStream(outStream))
.err(new PrintStream(errStream));
}
项目:openjdk-jdk10
文件:Debug.java
public static void println(PrintStream s, String name, byte[] data) {
s.print(name + ": { ");
if (data == null) {
s.print("null");
} else {
for (int i = 0; i < data.length; i++) {
if (i != 0) s.print(", ");
s.print(data[i] & 0x0ff);
}
}
s.println(" }");
}
项目:openjdk-jdk10
文件:J2DAnalyzer.java
public static void usage(PrintStream out) {
out.println("usage:");
out.println(" java -jar J2DAnalyzer.jar [Option]*");
out.println();
out.println("where options are any of the following in any order:");
out.println(" -Help|-Usage "+
"print out this usage statement");
out.println(" -Group:<groupname> "+
"the following result sets are combined into a group");
out.println(" -NoGroup "+
"the following result sets stand on their own");
out.println(" -ShowUncontested "+
"show results even when only result set has a result");
out.println(" -Graph "+
"graph the results visually (using lines of *'s)");
out.println(" -Best "+
"use best time within a resultset");
out.println(" -Worst "+
"use worst time within a resultset");
out.println(" -Average|-Avg "+
"use average of all times within a resultset");
out.println(" -MidAverage|-MidAvg "+
"like -Average but ignore best and worst times");
out.println(" <resultfilename> "+
"load in results from named file");
out.println();
out.println("results within a result set "+
"use Best/Worst/Average mode");
out.println("results within a group "+
"are best of all result sets in that group");
}
项目:hashsdn-controller
文件:TracingBrokerTest.java
@Test
@SuppressWarnings({ "resource", "unused" }) // Finding resource leaks is the point of this test
public void testPrintOpenTransactions() {
DOMDataBroker domDataBroker = mock(DOMDataBroker.class, RETURNS_DEEP_STUBS);
Config config = new ConfigBuilder().setTransactionDebugContextEnabled(true).build();
BindingNormalizedNodeSerializer codec = mock(BindingNormalizedNodeSerializer.class);
TracingBroker tracingBroker = new TracingBroker(domDataBroker, config, codec);
DOMDataReadWriteTransaction tx = tracingBroker.newReadWriteTransaction();
DOMTransactionChain txChain = tracingBroker.createTransactionChain(null);
DOMDataReadWriteTransaction txFromChain = txChain.newReadWriteTransaction();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
boolean printReturnValue = tracingBroker.printOpenTransactions(ps);
String output = new String(baos.toByteArray(), UTF_8);
assertThat(printReturnValue).isTrue();
// Assert expections about stack trace
assertThat(output).contains("testPrintOpenTransactions(TracingBrokerTest.java");
assertThat(output).doesNotContain(TracingBroker.class.getName());
String previousLine = "";
for (String line : output.split("\n")) {
if (line.contains("(...")) {
assertThat(previousLine.contains("(...)")).isFalse();
}
previousLine = line;
}
// We don't do any verify/times on the mocks,
// because the main point of the test is just to verify that
// printOpenTransactions runs through without any exceptions
// (e.g. it used to have a ClassCastException).
}
项目:openjdk-jdk10
文件:ComponentOperator.java
/**
* Maps {@code Component.list(PrintStream)} through queue
*/
public void list(final PrintStream printStream) {
runMapping(new MapVoidAction("list") {
@Override
public void map() {
getSource().list(printStream);
}
});
}
项目:ats-framework
文件:SwingElementFinder.java
private static String formattedHierarchy(
ComponentPrinter printer,
Container root ) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(out, true);
printer.printComponents(printStream, root);
printStream.flush();
return new String(out.toByteArray());
}