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

The following examples show how to use java.io.PrintWriter#printf() . These examples are extracted from open source projects. 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 Project: picocli   File: CommandSpecYamlPrinter.java    License: 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 Project: emodb   File: MoveTableTask.java    License: 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 3
Source Project: RDFS   File: FairSchedulerServlet.java    License: 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 4
Source Project: jrpip   File: ListJrpipRequest.java    License: 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 Project: aion   File: ZMsg.java    License: 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 6
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 7
Source Project: webanno   File: Tsv3XSerializer.java    License: 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 8
@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 Project: DataDefender   File: DataDefender.java    License: 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 10
/**
 * 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 11
Source Project: BPR   File: DatasetUtil.java    License: 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 12
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 13
Source Project: picocli   File: ManPageGenerator.java    License: 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 14
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 15
Source Project: emodb   File: SorCqlSettingsTask.java    License: 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 16
public void generate(PrintWriter pw) {
    generateDecl(pw);
    pw.printf(" { %s }", this.body);
}
 
Example 17
Source Project: metrics   File: ThreadDump.java    License: 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 18
Source Project: hottub   File: SourceModel.java    License: 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
public void generateWarningSuppression(PrintWriter pw) {
    if (this.emitSuppressWarnings) {
        pw.printf("@SuppressWarnings(\"unchecked\")\n    ");
    }
}
 
Example 20
private static PrintWriter printObject(final PrintWriter pw, final Object o) {
    pw.printf("%[email protected]%08x", o.getClass().getName(), System.identityHashCode(o));
    return pw;
}