Java Code Examples for java.io.PrintStream

The following are top voted examples for showing how to use java.io.PrintStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OpenJSharp   File: PSPrinterJob.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Project: dremio-oss   File: TestNewTextReader.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 3
Project: ditb   File: TestImportExport.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 4
Project: alvisnlp   File: CCGBase.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 5
Project: omero-ms-queue   File: Create.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 6
Project: vogar   File: TestRunner.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 7
Project: incubator-netbeans   File: MIMESupportTest.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 8
Project: ramus   File: Manager.java   Source Code and License 6 votes vote down vote up
protected void stop() {
    PrintStream printStream = new PrintStream(out);
    printStream.println("stop");
    printStream.flush();
    printStream.close();
    restartItem.setEnabled(false);
    stopItem.setEnabled(false);
    startItem.setEnabled(true);
}
 
Example 9
Project: MaxSim   File: CommandProcessor.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 10
Project: vscrawler   File: AVM.java   Source Code and License 6 votes vote down vote up
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();
	}
}
 
Example 11
Project: cactoos   File: BytesOf.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
            }
        }
    );
}
 
Example 12
Project: alvisnlp   File: AbstractWapiti.java   Source Code and License 6 votes vote down vote up
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();
			}
		}
	}
}
 
Example 13
Project: hadoop-oss   File: TestCount.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 14
Project: alvisnlp   File: EnjuExternal.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 15
Project: migration-tooling   File: WorkspaceWriter.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 16
Project: hadoop   File: TestContainerLaunch.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 17
Project: OpenJSharp   File: ServerTool.java   Source Code and License 5 votes vote down vote up
public void printCommandHelp(PrintStream out, boolean helpType)
{
    if (helpType == longHelp) {
        out.println(CorbaResourceUtil.getText("servertool.register"));
    } else {
        out.println(CorbaResourceUtil.getText("servertool.register1"));
    }
}
 
Example 18
Project: RefDiff   File: RefactoringSet.java   Source Code and License 5 votes vote down vote up
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(";");
}
 
Example 19
Project: loom   File: WordIndex.java   Source Code and License 5 votes vote down vote up
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));
    }
}
 
Example 20
Project: dice   File: RndTool.java   Source Code and License 5 votes vote down vote up
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();
        }
    }
}
 
Example 21
Project: openjdk-jdk10   File: Scan.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 22
Project: deployment-recorder-extension   File: PomReadIT.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 23
Project: V8LogScanner   File: TestCmdAppl.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 24
Project: xcc   File: InstrInfoEmitter.java   Source Code and License 5 votes vote down vote up
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");
}
 
Example 25
Project: OpenJSharp   File: BandStructure.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 26
Project: hadoop   File: GetGroupsTestBase.java   Source Code and License 5 votes vote down vote up
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();
  }
}
 
Example 27
Project: ZooKeeper   File: IOUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 28
Project: BiglyBT   File: Pairing.java   Source Code and License 5 votes vote down vote up
@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("> -----");
}
 
Example 29
Project: migration-tooling   File: WorkspaceWriterTest.java   Source Code and License 5 votes vote down vote up
@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");
}
 
Example 30
Project: Jar2Java   File: JavaSourceTextPrinter.java   Source Code and License 5 votes vote down vote up
public JavaSourceTextPrinter(CommonPreferences preferences, PrintStream printStream) {
    this.preferences = preferences;
    this.printStream = printStream;
    this.maxLineNumber = 0;
    this.majorVersion = 0;
    this.minorVersion = 0;
    this.indentationCount = 0;
}
 
Example 31
Project: openNaEF   File: DumpCommand.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 32
Project: jdk8u-jdk   File: CategoryClassFile.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 33
Project: xcc   File: Init.java   Source Code and License 5 votes vote down vote up
@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("]");
}
 
Example 34
Project: elasticsearch_my   File: PainlessDocGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * 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");
}
 
Example 35
Project: openjdk-jdk10   File: IdGeneratorTest.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 36
Project: openjdk-jdk10   File: Debug.java   Source Code and License 5 votes vote down vote up
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(" }");
}
 
Example 37
Project: openjdk-jdk10   File: J2DAnalyzer.java   Source Code and License 5 votes vote down vote up
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");
}
 
Example 38
Project: hashsdn-controller   File: TracingBrokerTest.java   Source Code and License 5 votes vote down vote up
@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).
}
 
Example 39
Project: openjdk-jdk10   File: ComponentOperator.java   Source Code and License 5 votes vote down vote up
/**
 * Maps {@code Component.list(PrintStream)} through queue
 */
public void list(final PrintStream printStream) {
    runMapping(new MapVoidAction("list") {
        @Override
        public void map() {
            getSource().list(printStream);
        }
    });
}
 
Example 40
Project: ats-framework   File: SwingElementFinder.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 41
Project: Panako   File: FileDrop.java   Source Code and License 5 votes vote down vote up
/** Determine if the dragged data is a file list. */
private boolean isDragOk( final java.io.PrintStream out, final java.awt.dnd.DropTargetDragEvent evt )
{   boolean ok = false;
    
    // Get data flavors being dragged
    java.awt.datatransfer.DataFlavor[] flavors = evt.getCurrentDataFlavors();
    
    // See if any of the flavors are a file list
    int i = 0;
    while( !ok && i < flavors.length )
    {   
        // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
        // Is the flavor a file list?
        final DataFlavor curFlavor = flavors[i];
        if( curFlavor.equals( java.awt.datatransfer.DataFlavor.javaFileListFlavor ) ||
            curFlavor.isRepresentationClassReader()){
            ok = true;
        }
        // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
        i++;
    }   // end while: through flavors
    
    // If logging is enabled, show data flavors
    if( out != null )
    {   if( flavors.length == 0 )
            log( out, "FileDrop: no data flavors." );
        for( i = 0; i < flavors.length; i++ )
            log( out, flavors[i].toString() );
    }   // end if: logging enabled
    
    return ok;
}
 
Example 42
Project: Rubus   File: FileDrop.java   Source Code and License 5 votes vote down vote up
/** Determine if the dragged data is a file list. */
private boolean isDragOk(final java.io.PrintStream out,
		final java.awt.dnd.DropTargetDragEvent evt) {
	boolean ok = false;

	// Get data flavors being dragged
	java.awt.datatransfer.DataFlavor[] flavors = evt
			.getCurrentDataFlavors();

	// See if any of the flavors are a file list
	int i = 0;
	while (!ok && i < flavors.length) {
		// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support
		// added.
		// Is the flavor a file list?
		final DataFlavor curFlavor = flavors[i];
		if (curFlavor
				.equals(java.awt.datatransfer.DataFlavor.javaFileListFlavor)
				|| curFlavor.isRepresentationClassReader()) {
			ok = true;
		}
		// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support
		// added.
		i++;
	} // end while: through flavors

	// If logging is enabled, show data flavors
	if (out != null) {
		if (flavors.length == 0)
			log(out, "FileDrop: no data flavors.");
		for (i = 0; i < flavors.length; i++)
			log(out, flavors[i].toString());
	} // end if: logging enabled

	return ok;
}
 
Example 43
Project: OpenJSharp   File: XMLSignatureException.java   Source Code and License 5 votes vote down vote up
/**
 * Prints this <code>XMLSignatureException</code>, its backtrace and
 * the cause's backtrace to the specified print stream.
 *
 * @param s <code>PrintStream</code> to use for output
 */
public void printStackTrace(PrintStream s) {
    super.printStackTrace(s);
    if (cause != null) {
        cause.printStackTrace(s);
    }
}
 
Example 44
Project: openjdk-jdk10   File: SysPropsDumper.java   Source Code and License 5 votes vote down vote up
public void run() {
   Properties sysProps = VM.getVM().getSystemProperties();
   PrintStream out = System.out;
   if (sysProps != null) {
      Enumeration keys = sysProps.keys();
      while (keys.hasMoreElements()) {
         Object key = keys.nextElement();
         out.print(key);
         out.print(" = ");
         out.println(sysProps.get(key));
      }
   } else {
      out.println("System Properties info not available!");
   }
}
 
Example 45
Project: Xndroid   File: LogUtils.java   Source Code and License 5 votes vote down vote up
private static String formatException(Throwable e) {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(output);
    e.printStackTrace(ps);
    ps.close();
    return output.toString();
}
 
Example 46
Project: RefDiff   File: LSdiffHierarchialDeltaKB.java   Source Code and License 5 votes vote down vote up
private void printInheritedMethods (PrintStream p,TreeSet<LSDFact> ontheflyDeltaKB,  LSDFact typeF) { 
	for (LSDFact fact:originalDeltaKB) {
		if (fact.getPredicate().getName().indexOf("_inheritedmethod")>0 && fact.getBindings().get(2).getGroundConst().equals(typeF.getBindings().get(0).getGroundConst())){ 
			if (filter.methodLevel) ontheflyDeltaKB.add(fact);
			if (filter.methodLevel&& p!=null) p.println("\t\t\t"+ fact); 
		}
	}
}
 
Example 47
Project: xcc   File: RecordVal.java   Source Code and License 5 votes vote down vote up
public void print(PrintStream os, boolean printSem)
{
    if (getPrefix() != 0) os.print("field ");
    getType().print(os);
    os.printf(" %s", getName());
    if (getValue() != null)
    {
        os.print(" = ");
        getValue().print(os);
    }
    if (printSem) os.println(";");
}
 
Example 48
Project: openjdk-jdk10   File: TestHumongousMovement.java   Source Code and License 5 votes vote down vote up
public void printDetails(PrintStream out) {
    BigInteger objectAddressAfterGC =
            new BigInteger(Long.toUnsignedString((WB.getObjectAddress(allocation))));

    out.println(String.format("Object stored address = %d\nObject address after GC = %d\n"
                    + "They are %sequals", objectAddress,
            objectAddressAfterGC, !objectAddress.equals(objectAddressAfterGC) ? "not " : ""));
}
 
Example 49
Project: OpenJSharp   File: Assembler.java   Source Code and License 5 votes vote down vote up
/**
 * Print the byte codes
 */
public void listing(PrintStream out) {
    out.println("-- listing --");
    for (Instruction inst = first ; inst != null ; inst = inst.next) {
        out.println(inst.toString());
    }
}
 
Example 50
Project: hadoop   File: DFSck.java   Source Code and License 5 votes vote down vote up
public DFSck(Configuration conf, PrintStream out) throws IOException {
  super(conf);
  this.ugi = UserGroupInformation.getCurrentUser();
  this.out = out;
  this.connectionFactory = URLConnectionFactory
      .newDefaultURLConnectionFactory(conf);
  this.isSpnegoEnabled = UserGroupInformation.isSecurityEnabled();
}
 
Example 51
Project: incubator-sdap-mudrod   File: LocalOntology.java   Source Code and License 5 votes vote down vote up
protected static void renderRestriction(PrintStream out, Restriction r) {
  if (!r.isAnon()) {
    out.print("Restriction ");
    renderURI(out, r.getModel(), r.getURI());
  } else {
    renderAnonymous(out, r, "restriction");
  }

  out.print(" on property ");
  renderURI(out, r.getModel(), r.getOnProperty().getURI());
}
 
Example 52
Project: incubator-netbeans   File: BlacklistedClassesHandlerSingleton.java   Source Code and License 5 votes vote down vote up
public String listViolations(boolean listExceptions, boolean printCaptions) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    listViolations(ps, listExceptions, printCaptions);
    ps.flush();
    return baos.toString();
}
 
Example 53
Project: docx4j-template   File: JspWriter.java   Source Code and License 5 votes vote down vote up
public static JspWriter create(OutputStream os, Charset charset, boolean trimLeadingWhitespaces, boolean skipErrors) {
    if (skipErrors || os instanceof PrintStream) {
        if (trimLeadingWhitespaces) {
            os = new TrimLeadingWhitespacesOutputStream(os);
        }
        return new JspOutputStreamPrinter(os, charset);
    } else {
        if (trimLeadingWhitespaces) {
            os = new TrimLeadingWhitespacesOutputStream(os);
        }
        return new JspOutputStreamPrinterEx(os, charset);
    }
}
 
Example 54
Project: picocli   File: CommandLineHelpTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCommandLine_printVersionInfo_printsArrayOfPlainTextStrings() throws Exception {
    @Command(version = {"Versioned Command 1.0", "512-bit superdeluxe", "(c) 2017"}) class Versioned {}
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true, "UTF8"), Help.Ansi.OFF);
    String result = baos.toString("UTF8");
    assertEquals(String.format("Versioned Command 1.0%n512-bit superdeluxe%n(c) 2017%n"), result);
}
 
Example 55
Project: openjdk-jdk10   File: CDSTestUtils.java   Source Code and License 5 votes vote down vote up
private static void writeFile(File file, String content) throws Exception {
    FileOutputStream fos = new FileOutputStream(file);
    PrintStream ps = new PrintStream(fos);
    ps.print(content);
    ps.close();
    fos.close();
}
 
Example 56
Project: xcc   File: InstrInfoEmitter.java   Source Code and License 5 votes vote down vote up
private static void printDefList(ArrayList<Record> uses, int num, PrintStream os)
{
    os.printf("\tpublic static final int[] implicitList%d = { ", num);
    int e = uses.size();
    if (e > 0)
    {
        os.printf("%s", uses.get(0).getName());
        for (int i = 1 ; i != e; ++i)
        {
            os.printf(", %s", uses.get(i).getName());
        }
    }
    os.printf("};\n");
}
 
Example 57
Project: OpenJSharp   File: SynchronizedStatement.java   Source Code and License 5 votes vote down vote up
/**
 * Print
 */
public void print(PrintStream out, int indent) {
    super.print(out, indent);
    out.print("synchronized ");
    expr.print(out);
    out.print(" ");
    if (body != null) {
        body.print(out, indent);
    } else {
        out.print("{}");
    }
}
 
Example 58
Project: incubator-netbeans   File: JShellTool.java   Source Code and License 4 votes vote down vote up
protected IOContext createIOContext(JShellTool tool, InputStream cmdIn, PrintStream console) {
    return null;
}
 
Example 59
Project: RefDiff   File: ModedRuleBaseCollection.java   Source Code and License 4 votes vote down vote up
public void dumpFacts(PrintStream out) {
	out.print(facts);
}
 
Example 60
Project: MaxSim   File: Compilation.java   Source Code and License 4 votes vote down vote up
public void print(PrintStream stream, boolean printInlining) {
    print(stream, 0, printInlining);
}