Java Code Examples for java.io.PrintWriter#printf()

The following examples show how to use java.io.PrintWriter#printf() . 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: CommandSpecYamlPrinter.java    From picocli with Apache License 2.0 7 votes vote down vote up
private void printUsageMessage(UsageMessageSpec usageMessage, PrintWriter pw, String indent) {
    pw.printf("%sUsageMessageSpec:%n", indent);
    indent += "  ";
    pw.printf("%swidth: %s%n", indent, usageMessage.width());
    pw.printf("%sabbreviateSynopsis: %s%n", indent, usageMessage.abbreviateSynopsis());
    pw.printf("%shidden: %s%n", indent, usageMessage.hidden());
    pw.printf("%sshowDefaultValues: %s%n", indent, usageMessage.showDefaultValues());
    pw.printf("%ssortOptions: %s%n", indent, usageMessage.sortOptions());
    pw.printf("%srequiredOptionMarker: '%s'%n", indent, usageMessage.requiredOptionMarker());
    pw.printf("%sheaderHeading: '%s'%n", indent, usageMessage.headerHeading());
    pw.printf("%sheader: %s%n", indent, Arrays.toString(usageMessage.header()));
    pw.printf("%ssynopsisHeading: '%s'%n", indent, usageMessage.synopsisHeading());
    pw.printf("%scustomSynopsis: %s%n", indent, Arrays.toString(usageMessage.customSynopsis()));
    pw.printf("%sdescriptionHeading: '%s'%n", indent, usageMessage.descriptionHeading());
    pw.printf("%sdescription: %s%n", indent, Arrays.toString(usageMessage.description()));
    pw.printf("%sparameterListHeading: '%s'%n", indent, usageMessage.parameterListHeading());
    pw.printf("%soptionListHeading: '%s'%n", indent, usageMessage.optionListHeading());
    pw.printf("%scommandListHeading: '%s'%n", indent, usageMessage.commandListHeading());
    pw.printf("%sfooterHeading: '%s'%n", indent, usageMessage.footerHeading());
    pw.printf("%sfooter: %s%n", indent, Arrays.toString(usageMessage.footer()));
}
 
Example 2
Source File: FairSchedulerServlet.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Print the administration form for the MemBasedLoadManager
 */
private void showAdminFormMemBasedLoadMgr(PrintWriter out,
                                          boolean advancedView) {
  if (!(loadMgr instanceof MemBasedLoadManager)) {
    return;
  }
  out.print("<h2>Memory Based Scheduling</h2>\n");
  MemBasedLoadManager memLoadMgr = (MemBasedLoadManager)loadMgr;
  Collection<String> possibleThresholds =
    Arrays.asList(("0,1,2,3,4,5,6,7,8,9,10,1000").split(","));
  long reservedMemGB =
          (long)(memLoadMgr.getReservedPhysicalMemoryOnTT() / 1024D + 0.5);
  out.printf("<p>Reserve %s GB memory on one node.",
             generateSelect(possibleThresholds, "" + reservedMemGB,
                            "/fairscheduler?setTtThreshold=<CHOICE>" +
                            (advancedView ? "&advanced" : "")));
}
 
Example 3
Source File: ZMsg.java    From aion with MIT License 6 votes vote down vote up
/**
 * Dump the message in human readable format. This should only be used for
 * debugging and tracing, inefficient in handling large messages.
 **/
public void dump(Appendable out)
{
    try {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.printf("--------------------------------------\n");
        for (ZFrame frame : frames) {
            pw.printf("[%03d] %s\n", frame.getData().length, frame.toString());
        }
        out.append(sw.getBuffer());
        sw.close();
    }
    catch (IOException e) {
        throw new RuntimeException("Message dump exception " + super.toString(), e);
    }
}
 
Example 4
Source File: ListJrpipRequest.java    From jrpip with Apache License 2.0 6 votes vote down vote up
private static void printUsage()
{
    PrintWriter pw = new PrintWriter(System.out, true);
    String usageStr =
            "Usage:\n"
                    + "   ListJrpipRequest -f inputFileName [OPTIONS]\n\n"
                    + "   Options:\n"
                    + "       -id number [,number]\n"
                    + "       -method name\n"
                    + "       -between start, end [dates formatted as yyyy-MM-dd HH:mm:ss]\n"
                    + "       -argument value\n\n"
                    + "   Example:\n"
                    + "       ListJrpipRequest -f inputFile.log\n"
                    + "       ListJrpipRequest -f inputFile.log -id 11,23 -method myMethod -between 2011-05-30 13:00:00, 2011-05-30 13:05:00 -argument GSCO\n"
                    + "\n\n\n";

    pw.printf(usageStr);
}
 
Example 5
Source File: MoveTableTask.java    From emodb with Apache License 2.0 6 votes vote down vote up
private void moveFacades(Collection<String> facades, String srcPlacement, String destPlacement,
                         Optional<Integer> numShards, PrintWriter out, MoveType moveType) {
    if (!facades.isEmpty() && (srcPlacement == null || destPlacement == null)) {
        out.println("The 'src' and 'dest' placement query parameters are required when moving facades.");
        return;
    }
    for (String facade : facades) {
        out.printf("Moving facade %s to placement %s...%n", facade, destPlacement);
        try {
            _tableDao.moveFacade(facade, srcPlacement, destPlacement, numShards, new AuditBuilder().build(), moveType);
        } catch (Exception e) {
            out.printf("ERROR moving facade %s to placement %s: ", facade, destPlacement);
            e.printStackTrace(out);
        }
    }
}
 
Example 6
Source File: ClusteringPartition.java    From ade with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Write the clustering details into a file.
 * 
 * @param file
 *            the file to where the clustering details are to be written.
 */
public final void printClusteringDetails(File file) throws AdeException {
	final PrintWriter out = FileUtils.openPrintWriterToFile(file, true);

	out.printf("%s%n", m_clusteringDetails);

	out.close();
}
 
Example 7
Source File: DataDefender.java    From DataDefender with Apache License 2.0 5 votes vote down vote up
public int handleParseException(ParameterException ex, String[] args) {
    CommandLine cmd = ex.getCommandLine();
    PrintWriter writer = cmd.getErr();

    writer.println(ex.getMessage());
    UnmatchedArgumentException.printSuggestions(ex, writer);
    writer.print(cmd.getHelp().fullSynopsis()); // since 4.1

    CommandSpec spec = cmd.getCommandSpec();
    writer.printf("Try '%s --help' for more information.%n", spec.qualifiedName());

    return cmd.getExitCodeExceptionMapper() != null
                ? cmd.getExitCodeExceptionMapper().getExitCode(ex)
                : spec.exitCodeOnInvalidInput();
}
 
Example 8
Source File: IndexesServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  Query q =
      new Query("Widget")
          .setFilter(
              CompositeFilterOperator.and(
                  new FilterPredicate("x", FilterOperator.EQUAL, 1),
                  new FilterPredicate("y", FilterOperator.EQUAL, "red")))
          .addSort("date", Query.SortDirection.ASCENDING);
  List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());

  PrintWriter out = resp.getWriter();
  out.printf("Got %d widgets.\n", results.size());
}
 
Example 9
Source File: MBeanInfoInteropTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void generate(String className) throws Exception {
    System.out.println("Generating " + className + ".java");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    for (Serializable s : objects)
        oos.writeObject(s);
    oos.close();
    byte[] bytes = bos.toByteArray();
    PrintWriter pw = new PrintWriter(className + ".java");
    pw.printf(
        "// Generated by: MBeanInfoInteropTest generate %s\n" +
        "import java.io.*;\n" +
        "public class %s {\n" +
        "public static final byte[] BYTES = {\n", className, className);
    for (int i = 0; i < bytes.length; i++) {
        byte b = bytes[i];
        pw.printf("%d,", b);
        if (i % 16 == 15)
            pw.printf("\n");
    }
    pw.printf("\n");
    pw.printf(
        "};\n" +
        "}\n");
    pw.close();
    System.out.println("...done");
}
 
Example 10
Source File: DatasetUtil.java    From BPR with Apache License 2.0 5 votes vote down vote up
/**
 * Only retain top occurrence words of a review. 
 * @param inputfileDir
 * @param dataset
 * @param maxWords The number of (top occurrence) words in the word dictionary.
 * @throws IOException
 * @throws LangDetectException 
 */
public void FilterVotesReviewsByWords(String inputfileDir, String dataset, int maxWords) 
		throws IOException {
	String inputfile = inputfileDir + dataset + ".votes";
	String outputfile = inputfileDir + dataset + "_w" + maxWords/1000 + "k.votes";
	reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputfile)));
	
	System.out.print("\nFiltering reviews by words: " + dataset);
	// Step 1: Build word dictionary.
	HashMap<String, Integer> map_word_id = new HashMap<String, Integer>();
	this.buildWordsDictionary(inputfile, map_word_id, maxWords);
	
	// Step 2: Write the filtered file.
	PrintWriter writer = new PrintWriter (new FileOutputStream(outputfile));
	String line;
	while ((line = reader.readLine()) != null) {
		String[] arr = line.split(" ");
		String filtered_review_text = "";
		int wordcount = 0;
		for (int i = 5; i < arr.length; i++) {
			String word = arr[i];
			if (map_word_id.containsKey(word)) {
				wordcount ++;
				filtered_review_text = filtered_review_text + word + " ";
			}
		}
		writer.printf("%s %s %s %s %d %s\n", 
				arr[0], arr[1], arr[2], arr[3], wordcount, filtered_review_text);
	}
	
	System.out.println("\nWrite the filtered file in: " + outputfile);
	writer.close();
	reader.close();
}
 
Example 11
Source File: SourceModel.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected void generateDecl(PrintWriter pw) {
    generateWarningSuppression(pw);
    pw.print(toJoinedString(this.accessFlags, " ", "", " "));
    pw.printf("%s %s(", returnType, name);
    pw.print(toJoinedString(parameters, ","));
    pw.print(")");
}
 
Example 12
Source File: ManPageGenerator.java    From picocli with Apache License 2.0 5 votes vote down vote up
private static void writePositional(PrintWriter pw, PositionalParamSpec positional, IParameterRenderer parameterRenderer, IParamLabelRenderer paramLabelRenderer) {
    pw.println();
    Text[][] rows = parameterRenderer.render(positional, paramLabelRenderer, COLOR_SCHEME);
    pw.printf("%s::%n", join(", ", rows[0][1], rows[0][3]));
    pw.printf("  %s%n", rows[0][4]);
    for (int i = 1; i < rows.length; i++) {
        pw.printf("+%n%s%n", rows[i][4]);
    }
}
 
Example 13
Source File: BoostedRTrees.java    From mltk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void write(PrintWriter out) throws Exception {
	out.printf("[Predictor: %s]\n", this.getClass().getCanonicalName());
	out.println("Length: " + trees.size());
	for (RTree rt : trees) {
		rt.write(out);
		out.println();
	}
}
 
Example 14
Source File: SorCqlSettingsTask.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
    String fetchValue = Iterables.getFirst(parameters.get("fetchSize"), "-1");
    String batchFetchValue = Iterables.getFirst(parameters.get("batchFetchSize"), "-1");
    String prefetchLimitValue = Iterables.getFirst(parameters.get("prefetchLimit"), "-1");
    String batchPrefetchLimitValue = Iterables.getFirst(parameters.get("batchPrefetchLimit"), "-1");
    Integer fetchSize = parseInt(fetchValue, "fetch size", out);
    Integer batchFetchSize = parseInt(batchFetchValue, "batch fetch size", out);
    Integer prefetchLimit = parseInt(prefetchLimitValue, "prefetch limit", out);
    Integer batchPrefetchLimit = parseInt(batchPrefetchLimitValue, "batch prefetch limit", out);

    if (fetchSize == null || batchFetchSize == null || prefetchLimit == null || batchPrefetchLimit == null) {
        return;
    }

    // Update fetch sizes and prefetch limits if needed
    if (fetchSize > 0 || prefetchLimit >= 0) {
        if (fetchSize > 0) {
            _cqlDriverConfiguration.setSingleRowFetchSize(fetchSize);
        }
        if (prefetchLimit >= 0) {
            _cqlDriverConfiguration.setSingleRowPrefetchLimit(prefetchLimit);
        }
    }
    if (batchFetchSize > 0 || batchPrefetchLimit >= 0) {
        if (batchFetchSize > 0) {
            _cqlDriverConfiguration.setMultiRowFetchSize(batchFetchSize);
        }
        if (batchPrefetchLimit >= 0) {
            _cqlDriverConfiguration.setMultiRowPrefetchLimit(batchPrefetchLimit);
        }
    }

    out.printf("Use CQL for multi-gets/scans = %s/%s.  To change these values use the \"sor-cql-driver\" task.%n%n",
            _useCqlForMultiGets.get(), _useCqlForScans.get());

    out.printf("FETCH_SIZE : %d | BATCH_FETCH_SIZE: %d | PREFETCH_LIMIT=%d | BATCH_PREFETCH_LIMIT=%d%n",
            _cqlDriverConfiguration.getSingleRowFetchSize(), _cqlDriverConfiguration.getMultiRowFetchSize(),
            _cqlDriverConfiguration.getSingleRowPrefetchLimit(), _cqlDriverConfiguration.getMultiRowPrefetchLimit());
}
 
Example 15
Source File: Tsv3XSerializer.java    From webanno with Apache License 2.0 5 votes vote down vote up
private static void writeDisambiguationId(PrintWriter aOut, TsvDocument aDoc, AnnotationFS aFS)
{
    Integer disambiguationId = aDoc.getDisambiguationId(aFS);
    if (disambiguationId != null) {
        aOut.printf("[%d]", disambiguationId);
    }
}
 
Example 16
Source File: ThreadDump.java    From metrics with Apache License 2.0 4 votes vote down vote up
/**
 * Dumps all of the threads' current information to an output stream.
 *
 * @param out an output stream
 */
public void dump(OutputStream out) {
    final ThreadInfo[] threads = this.threadMXBean.dumpAllThreads(true, true);
    final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, UTF_8));

    for (int ti = threads.length - 1; ti >= 0; ti--) {
        final ThreadInfo t = threads[ti];
        writer.printf("%s id=%d state=%s",
                      t.getThreadName(),
                      t.getThreadId(),
                      t.getThreadState());
        final LockInfo lock = t.getLockInfo();
        if (lock != null && t.getThreadState() != Thread.State.BLOCKED) {
            writer.printf("%n    - waiting on <0x%08x> (a %s)",
                          lock.getIdentityHashCode(),
                          lock.getClassName());
            writer.printf("%n    - locked <0x%08x> (a %s)",
                          lock.getIdentityHashCode(),
                          lock.getClassName());
        } else if (lock != null && t.getThreadState() == Thread.State.BLOCKED) {
            writer.printf("%n    - waiting to lock <0x%08x> (a %s)",
                          lock.getIdentityHashCode(),
                          lock.getClassName());
        }

        if (t.isSuspended()) {
            writer.print(" (suspended)");
        }

        if (t.isInNative()) {
            writer.print(" (running in native)");
        }

        writer.println();
        if (t.getLockOwnerName() != null) {
            writer.printf("     owned by %s id=%d%n", t.getLockOwnerName(), t.getLockOwnerId());
        }

        final StackTraceElement[] elements = t.getStackTrace();
        final MonitorInfo[] monitors = t.getLockedMonitors();

        for (int i = 0; i < elements.length; i++) {
            final StackTraceElement element = elements[i];
            writer.printf("    at %s%n", element);
            for (int j = 1; j < monitors.length; j++) {
                final MonitorInfo monitor = monitors[j];
                if (monitor.getLockedStackDepth() == i) {
                    writer.printf("      - locked %s%n", monitor);
                }
            }
        }
        writer.println();

        final LockInfo[] locks = t.getLockedSynchronizers();
        if (locks.length > 0) {
            writer.printf("    Locked synchronizers: count = %d%n", locks.length);
            for (LockInfo l : locks) {
                writer.printf("      - %s%n", l);
            }
            writer.println();
        }
    }

    writer.println();
    writer.flush();
}
 
Example 17
Source File: SourceModel.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public void generateWarningSuppression(PrintWriter pw) {
    if (this.emitSuppressWarnings) {
        pw.printf("@SuppressWarnings(\"unchecked\")\n    ");
    }
}
 
Example 18
Source File: SourceModel.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void generateWarningSuppression(PrintWriter pw) {
    if (this.emitSuppressWarnings) {
        pw.printf("@SuppressWarnings(\"unchecked\")\n    ");
    }
}
 
Example 19
Source File: SimpleSerialization.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static PrintWriter printObject(final PrintWriter pw, final Object o) {
    pw.printf("%s@%08x", o.getClass().getName(), System.identityHashCode(o));
    return pw;
}
 
Example 20
Source File: SourceModel.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public void generate(PrintWriter pw) {
    generateDecl(pw);
    pw.printf(" { %s }", this.body);
}