java.io.PrintStream Java Examples

The following examples show how to use java.io.PrintStream. 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: FixedStepPopulationVariantGeneratorCli.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected int mainExec(OutputStream out, PrintStream err) throws IOException {
  final CFlags flags = mFlags;
  final PortableRandom random;
  if (flags.isSet(SEED)) {
    random = new PortableRandom((Integer) flags.getValue(SEED));
  } else {
    random = new PortableRandom();
  }
  final long seed = random.getSeed();
  final int distance = (Integer) flags.getValue(DISTANCE);
  final File input = (File) flags.getValue(REFERENCE_SDF);
  final Mutator mutator = new Mutator((String) flags.getValue(SNP_SPECIFICATION));
  final File outputVcf = VcfUtils.getZippedVcfFileName(true, (File) flags.getValue(OUTPUT_VCF));
  final double af = (Double) flags.getValue(FREQUENCY);
  try (SequencesReader dsr = SequencesReaderFactory.createMemorySequencesReader(input, true, LongRange.NONE)) {
    final FixedStepPopulationVariantGenerator fs = new FixedStepPopulationVariantGenerator(dsr, distance, mutator, random, af);
    PopulationVariantGenerator.writeAsVcf(outputVcf, fs.generatePopulation(), dsr, seed);
    return 0;
  }
}
 
Example #2
Source File: Method.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public void dumpReplayData(PrintStream out) {
    NMethod nm = getNativeMethod();
    int code_size = 0;
    if (nm != null) {
      code_size = (int)nm.codeEnd().minus(nm.getVerifiedEntryPoint());
    }
    Klass holder = getMethodHolder();
    out.println("ciMethod " +
                holder.getName().asString() + " " +
                OopUtilities.escapeString(getName().asString()) + " " +
                getSignature().asString() + " " +
                getInvocationCount() + " " +
                getBackedgeCount() + " " +
                interpreterInvocationCount() + " " +
                interpreterThrowoutCount() + " " +
                code_size);
}
 
Example #3
Source File: ConsoleLogListenerTestCase.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void requireThatLogEntryWithLevelAboveThresholdIsNotOutput() {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    LogListener listener = new ConsoleLogListener(new PrintStream(out), null, "5");
    for (int i = 0; i < 10; ++i) {
        listener.logged(new MyEntry(0, i, "message"));
    }
    // TODO: Should use ConsoleLogFormatter.ABSENCE_REPLACEMENT instead of literal '-'. See ticket 7128315.
    assertEquals("0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n" +
                 "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\terror\tmessage\n" +
                 "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\twarning\tmessage\n" +
                 "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tinfo\tmessage\n" +
                 "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tdebug\tmessage\n" +
                 "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n",
                 out.toString());
}
 
Example #4
Source File: TestCount.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void processOptionsHeaderNoQuotas() {
  LinkedList<String> options = new LinkedList<String>();
  options.add("-v");
  options.add("dummy");

  PrintStream out = mock(PrintStream.class);

  Count count = new Count();
  count.out = out;

  count.processOptions(options);

  String noQuotasHeader =
  // <----12----> <----12----> <-------18------->
    "   DIR_COUNT   FILE_COUNT       CONTENT_SIZE PATHNAME";
  verify(out).println(noQuotasHeader);
  verifyNoMoreInteractions(out);
}
 
Example #5
Source File: MergeProperties.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the merged properties to a single file while preserving any
 * comments.
 *
 * @param fileContents list of file contents
 * @throws Exception if the destination file can't be created
 */
private void writeFile(List fileContents) throws Exception {
    Iterator iterate = fileContents.iterator();
    try {
        FileOutputStream out = new FileOutputStream(destFile);
        PrintStream p = new PrintStream(out);
        try {
            // write original file with updated values
            while (iterate.hasNext()) {
                FileContents fc = (FileContents) iterate.next();
                if (fc.comment != null && !fc.comment.equals("")) {
                    p.println();
                    p.print(fc.comment);
                }
                p.println(fc.value);
            }
        } catch (Exception e) {
            throw new Exception("Could not write file: " + destFile, e);
        } finally {
            out.close();
        }
    } catch (IOException IOe) {
        throw new Exception("Could not write file: " + destFile, IOe);
    }
}
 
Example #6
Source File: Main.java    From ironjacamar with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * hasValidatingMcfInterface
 * 
 * @param out output stream
 * @param classname classname
 * @param cl classloader
 */
private static void hasValidatingMcfInterface(PrintStream out, PrintStream error, String classname,
      URLClassLoader cl)
{
   try
   {
      out.print("  Validating: ");
      Class<?> clazz = Class.forName(classname, true, cl);

      if (hasInterface(clazz, "javax.resource.spi.ValidatingManagedConnectionFactory"))
      {
         out.println("Yes");
      }
      else
      {
         out.println("No");
      }
   }
   catch (Throwable t)
   {
      // Nothing we can do
      t.printStackTrace(error);
      out.println("Unknown");
   }
}
 
Example #7
Source File: SplitBamByCellTest.java    From Drop-seq with MIT License 6 votes vote down vote up
@Test
public void testReadBamList() throws IOException {
    // Create a bam_list with one relative path and one absolute, and confirm that reader
    // resolves them correctly.
    final File bamList = TestUtils.getTempReportFile("testReadBamList.", ".bam_list");
    final PrintStream out = new ErrorCheckingPrintStream(IOUtil.openFileForWriting(bamList));
    final String relative = "foo.bam";
    out.println(relative);
    final String absolute = "/an/absolute/path.bam";
    out.println(absolute);
    out.close();
    final List<File> expected = Arrays.asList(
      new File(bamList.getCanonicalFile().getParent(), relative),
      new File(absolute)
    );
    Assert.assertEquals(expected, FileListParsingUtils.readFileList(bamList));
    // Confirm that when reading a symlink to a bam_list, relative paths are resolved relative to the directory
    // of the actually bam_list file, not the directory containing the symlink.
    final File otherDir = Files.createTempDirectory("testReadBamList").toFile();
    otherDir.deleteOnExit();
    final File symlink = new File(otherDir, "testReadBamList.bam_list");
    symlink.deleteOnExit();
    Files.createSymbolicLink(symlink.toPath(), bamList.toPath());
    Assert.assertEquals(expected, FileListParsingUtils.readFileList(symlink));
}
 
Example #8
Source File: PostgresqlDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void backup(File f) throws IOException {

	if (getString(URL_PGDUMP).length() <= 0) {
		throw new NullPointerException("Please fill URL_PGDUMP var");
	}

	String dumpCommand = getString(URL_PGDUMP) + "/pg_dump" + " -d" + getString(DB_NAME)
			+ " -h" + getString(SERVERNAME) + " -U" + getString(LOGIN) + " -p"
			+ getString(SERVERPORT);

	Runtime rt = Runtime.getRuntime();
	logger.info("begin Backup :" + dumpCommand);

	Process child = rt.exec(dumpCommand);
	try (PrintStream ps = new PrintStream(f)) {
		InputStream in = child.getInputStream();
		int ch;
		while ((ch = in.read()) != -1) {
			ps.write(ch);
		}
		logger.info("Backup " + getString(DB_NAME) + " done");
	}

}
 
Example #9
Source File: Compiler.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new YAIL compiler.
 *
 * @param project  project to build
 * @param compTypes component types used in the project
 * @param compBlocks component types mapped to blocks used in project
 * @param out  stdout stream for compiler messages
 * @param err  stderr stream for compiler messages
 * @param userErrors stream to write user-visible error messages
 * @param childProcessMaxRam  maximum RAM for child processes, in MBs.
 */
@VisibleForTesting
Compiler(Project project, Set<String> compTypes, Map<String, Set<String>> compBlocks, PrintStream out, PrintStream err,
         PrintStream userErrors, boolean isForCompanion, boolean isForEmulator, boolean includeDangerousPermissions,
         int childProcessMaxRam, String dexCacheDir, BuildServer.ProgressReporter reporter) {
  this.project = project;
  this.compBlocks = compBlocks;

  prepareCompTypes(compTypes);
  readBuildInfo();

  this.out = out;
  this.err = err;
  this.userErrors = userErrors;
  this.isForCompanion = isForCompanion;
  this.isForEmulator = isForEmulator;
  this.includeDangerousPermissions = includeDangerousPermissions;
  this.childProcessRamMb = childProcessMaxRam;
  this.dexCacheDir = dexCacheDir;
  this.reporter = reporter;

}
 
Example #10
Source File: GenericOptionsParser.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
/**
 * Print the usage message for generic command-line options supported.
 * 
 * @param out stream to print the usage message to.
 */
public static void printGenericCommandUsage(PrintStream out) {
  
  out.println("Generic options supported are");
  out.println("-conf <configuration file>     specify an application configuration file");
  out.println("-D <property=value>            use value for given property");
  out.println("-fs <local|namenode:port>      specify a namenode");
  out.println("-jt <local|jobtracker:port>    specify a job tracker");
  out.println("-files <comma separated list of files>    " + 
    "specify comma separated files to be copied to the map reduce cluster");
  out.println("-libjars <comma separated list of jars>    " +
    "specify comma separated jar files to include in the classpath.");
  out.println("-archives <comma separated list of archives>    " +
              "specify comma separated archives to be unarchived" +
              " on the compute machines.\n");
  out.println("The general command line syntax is");
  out.println("bin/hadoop command [genericOptions] [commandOptions]\n");
}
 
Example #11
Source File: ExtractResourceWithChangesSCM.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
public void saveToChangeLog(File changeLogFile, ExtractChangeLogParser.ExtractChangeLogEntry changeLog) throws IOException {
    FileOutputStream outputStream = new FileOutputStream(changeLogFile);

    PrintStream stream = new PrintStream(outputStream, false, "UTF-8");

    stream.println("<?xml version='1.0' encoding='UTF-8'?>");
    stream.println("<extractChanges>");
    stream.println("<entry>");
    stream.println("<zipFile>" + escapeForXml(changeLog.getZipFile()) + "</zipFile>");

    for (String fileName : changeLog.getAffectedPaths()) {
        stream.println("<file>");
        stream.println("<fileName>" + escapeForXml(fileName) + "</fileName>");
        stream.println("</file>");
    }

    stream.println("</entry>");
    stream.println("</extractChanges>");

    stream.close();
}
 
Example #12
Source File: LoggingPrintStream.java    From MCPELauncher with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized PrintStream append(
        CharSequence csq, int start, int end) {
    builder.append(csq, start, end);
    flush(false);
    return this;
}
 
Example #13
Source File: XMLSerializer.java    From vxquery with Apache License 2.0 5 votes vote down vote up
private void printInteger(PrintStream ps, TaggedValuePointable tvp) {
    LongPointable lp = pp.takeOne(LongPointable.class);
    try {
        tvp.getValue(lp);
        ps.print(lp.longValue());
    } finally {
        pp.giveBack(lp);
    }
}
 
Example #14
Source File: BuildServer.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private void buildAndCreateZip(String userName, File inputZipFile, ProgressReporter reporter)
  throws IOException, JSONException {
  Result buildResult = build(userName, inputZipFile, reporter);
  boolean buildSucceeded = buildResult.succeeded();
  outputZip = File.createTempFile(inputZipFile.getName(), ".zip");
  outputZip.deleteOnExit();  // In case build server is killed before cleanUp executes.
  ZipOutputStream zipOutputStream =
    new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputZip)));
  if (buildSucceeded) {
    if (outputKeystore != null) {
      zipOutputStream.putNextEntry(new ZipEntry(outputKeystore.getName()));
      Files.copy(outputKeystore, zipOutputStream);
    }
    zipOutputStream.putNextEntry(new ZipEntry(outputApk.getName()));
    Files.copy(outputApk, zipOutputStream);
    successfulBuildRequests.getAndIncrement();
  } else {
    LOG.severe("Build " + buildCount.get() + " Failed: " + buildResult.getResult() + " " + buildResult.getError());
    failedBuildRequests.getAndIncrement();
  }
  zipOutputStream.putNextEntry(new ZipEntry("build.out"));
  String buildOutputJson = genBuildOutput(buildResult);
  PrintStream zipPrintStream = new PrintStream(zipOutputStream);
  zipPrintStream.print(buildOutputJson);
  zipPrintStream.flush();
  zipOutputStream.flush();
  zipOutputStream.close();
}
 
Example #15
Source File: LinePerThreadBufferingOutputStream.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected PrintStream initialValue() {
    return AccessController.doPrivileged(new PrivilegedAction<PrintStream>() {
        public PrintStream run() {
            return new PrintStream(new LineBufferingOutputStream(handler));
        }
    });
}
 
Example #16
Source File: ServerTool.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void printCommandHelp(PrintStream out, boolean helpType)
{
    if (helpType == longHelp) {
        out.println(CorbaResourceUtil.getText("servertool.listappnames"));
    } else {
        out.println(CorbaResourceUtil.getText("servertool.listappnames1"));
    }
}
 
Example #17
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 #18
Source File: HttpServer.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  if (!HttpServer.isInstrumentationAccessAllowed(getServletContext(),
                                                 request, response)) {
    return;
  }
  response.setContentType("text/plain; charset=UTF-8");
  try (PrintStream out = new PrintStream(
      response.getOutputStream(), false, "UTF-8")) {
    ReflectionUtils.printThreadInfo(out, "");
  }
  ReflectionUtils.logThreadInfo(LOG, "jsp requested", 1);      
}
 
Example #19
Source File: RocSlopeTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void test1() throws IOException {
  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try (PrintStream ps = new PrintStream(baos)) {
    RocSlope.writeSlope(new ByteArrayInputStream(ROC1.getBytes()), ps);
  }
  mNano.check("roc-slope-1.txt", TestUtils.sanitizeTsvHeader(baos.toString()));
}
 
Example #20
Source File: VerifyCachesCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
private boolean verifyRuleKeyCache(
    CellProvider cellProvider,
    PrintStream stdOut,
    RuleKeyConfiguration ruleKeyConfiguration,
    FileHashLoader fileHashLoader,
    RuleKeyCacheRecycler<RuleKey> recycler) {
  ImmutableList<Map.Entry<BuildRule, RuleKey>> contents = recycler.getCachedBuildRules();
  RuleKeyFieldLoader fieldLoader = new RuleKeyFieldLoader(ruleKeyConfiguration);
  ActionGraphBuilder graphBuilder =
      new MultiThreadedActionGraphBuilder(
          MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()),
          TargetGraph.EMPTY,
          ConfigurationRuleRegistryFactory.createRegistry(TargetGraph.EMPTY),
          new DefaultTargetNodeToBuildRuleTransformer(),
          cellProvider);
  contents.forEach(e -> graphBuilder.addToIndex(e.getKey()));
  DefaultRuleKeyFactory defaultRuleKeyFactory =
      new DefaultRuleKeyFactory(fieldLoader, fileHashLoader, graphBuilder);
  stdOut.println(String.format("Examining %d build rule keys.", contents.size()));
  ImmutableList<BuildRule> mismatches =
      RichStream.from(contents)
          .filter(entry -> !defaultRuleKeyFactory.build(entry.getKey()).equals(entry.getValue()))
          .map(Map.Entry::getKey)
          .toImmutableList();
  if (mismatches.isEmpty()) {
    stdOut.println("No rule key cache errors found.");
  } else {
    stdOut.println("Found rule key cache errors:");
    for (BuildRule rule : mismatches) {
      stdOut.println(String.format("  %s", rule));
    }
  }
  return true;
}
 
Example #21
Source File: HtmlExporter.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@Override
protected void handleLabels(PrintStream out, List<String> labels) {
    out.println("\t\t<tr>");
    for (String label : labels) {
        out.printf("\t\t\t<td>%s</td>%n", label);
    }
    out.println("\t\t</tr>");
}
 
Example #22
Source File: JDBCDisplayUtil.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
static public void ShowException(PrintStream out, Throwable e) {
	if (e == null) return;

	if (e instanceof SQLException)
		ShowSQLException(out, (SQLException)e);
	else
		e.printStackTrace(out);
}
 
Example #23
Source File: Compilation.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void printShort(PrintStream stream) {
    if (getMethod() == null) {
        stream.println(getSpecial());
    } else {
        int bc = isOsr() ? getOsr_bci() : -1;
        stream.print(getId() + getMethod().decodeFlags(bc) + getMethod().format(bc));
    }
}
 
Example #24
Source File: TestMapReduce.java    From spork with Apache License 2.0 5 votes vote down vote up
@Test
public void testQualifiedFunctionsWithNulls() throws Throwable {

    //create file
    File tmpFile = File.createTempFile("test", ".txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for(int i = 0; i < 1; i++) {
    if ( i % 10 == 0 ){
           ps.println("");
    } else {
           ps.println(i);
    }
    }
    ps.close();

    // execute query
    String query = "foreach (group (load '"
            + Util.generateURI(tmpFile.toString(), pig.getPigContext())
            + "' using " + MyStorage.class.getName() + "()) by "
            + MyGroup.class.getName() + "('all')) generate flatten("
            + MyApply.class.getName() + "($1)) ;";
    System.out.println(query);
    pig.registerQuery("asdf_id = " + query);

    //Verfiy query
    Iterator<Tuple> it = pig.openIterator("asdf_id");
    Tuple t;
    int count = 0;
    while(it.hasNext()) {
        t = it.next();
        assertEquals(t.get(0).toString(), "Got");
        Integer.parseInt(t.get(1).toString());
        count++;
    }

    assertEquals( MyStorage.COUNT, count );
    tmpFile.delete();
}
 
Example #25
Source File: ProcessResults.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**  Throws new RuntimeException if the child JVM returns not 0 value.
 *
 * @param err PrintStraem where output have to be redirected
 */
public synchronized void verifyProcessExitValue(PrintStream err) {
    if (exitValue != 0) {
        throw new RuntimeException("Child process returns not 0 value!" +
                "Returned value is " + exitValue);
    }
}
 
Example #26
Source File: Block.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void dump(PrintStream out) {
  out.print("B" + preOrder());
  out.print(" Freq: " + freq());
  out.println();
  Node_List nl = nodes();
  int cnt = nl.size();
  for( int i=0; i<cnt; i++ )
    nl.at(i).dump(out);
  out.print("\n");
}
 
Example #27
Source File: ClusterTool.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void pid(final PrintStream out, final File clusterDir)
{
    if (markFileExists(clusterDir) || TIMEOUT_MS > 0)
    {
        try (ClusterMarkFile markFile = openMarkFile(clusterDir, null))
        {
            out.println(markFile.decoder().pid());
        }
    }
    else
    {
        System.exit(-1);
    }
}
 
Example #28
Source File: Main.java    From FancyBing with GNU General Public License v3.0 5 votes vote down vote up
private static void printUsage(PrintStream out)
{
    String text =
        "Usage: gogui-client [options] hostname port\n" +
        "\n" +
        "-config  config file\n" +
        "-help    display this help and exit\n" +
        "-timeout stop trying to connect after n seconds (default 10)\n" +
        "-version print version and exit\n";
    out.print(text);
}
 
Example #29
Source File: Histogram.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/** Print a report of this histogram.
 */
public
void print(String name, String[] histTitles, PrintStream out) {
    int totalUnique = getTotalLength();
    int ltotalWeight = getTotalWeight();
    double tlen = getBitLength();
    double avgLen = tlen / ltotalWeight;
    double avg = (double) ltotalWeight / totalUnique;
    String title = (name
                    +" len="+round(tlen,10)
                    +" avgLen="+round(avgLen,10)
                    +" weight("+ltotalWeight+")"
                    +" unique["+totalUnique+"]"
                    +" avgWeight("+round(avg,100)+")");
    if (histTitles == null) {
        out.println(title);
    } else {
        out.println(title+" {");
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < matrix.length; i++) {
            buf.setLength(0);
            buf.append("  ").append(histTitles[i]).append(" {");
            for (int j = 1; j < matrix[i].length; j++) {
                buf.append(" ").append(matrix[i][j]);
            }
            buf.append(" }");
            out.println(buf);
        }
        out.println("}");
    }
}
 
Example #30
Source File: OpaqueClassFile.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override public void writeBeginning(PrintStream out){
    out.println("\t// " + opaque.type);
    out.println("\t// " + opaque.type.getJType());
    out.println("");
    out.println("\tpublic " + className + "(" + Pointer.class.getName() + "<?> ptr){");
    out.println("\t\tsuper(ptr);");
    out.println("\t}");
    out.println("");
    out.println("\tpublic " + className + "(long ptr){");
    out.println("\t\tsuper(ptr);");
    out.println("\t}");
}