下面列出了怎么用java.util.Formatter的API类实例代码及写法,或者点击链接到github查看源代码。
public String[] graph(float... values) {
String[] rows = new String[height + 1];
if (max == -1) {
max = (int) Math.ceil(maxFloat(values));
}
int bucketWidth = (int)Math.ceil((float)(max - min) / height);
int[] counts = count(bucketWidth, values);
int maxCount = max(counts);
StringBuilder out = new StringBuilder();
Formatter formatter = new Formatter(out);
formatter.format("%8d %" + width + "d", 0, maxCount);
rows[0] = out.toString();
for (int i = 0; i < counts.length; i++) {
out.setLength(0);
int bucketId = (int) (min + bucketWidth * i + bucketWidth / 2f);
PieGraph pieGraph = new PieGraph(width, new CharMarker(marker.get(i, bucketId), ' '));
String bar = pieGraph.render(counts[i], maxCount - counts[i]);
formatter.format("%6d |%s:%6d", bucketId, bar, counts[i]);
rows[i + 1] = out.toString();
}
return rows;
}
@ParameterizedTest
@MethodSource("allPools")
void disposeLaterIsLazy(Function<PoolBuilder<Formatter, ?>, AbstractPool<Formatter>> configAdjuster) {
Formatter uniqueElement = new Formatter();
PoolBuilder<Formatter, ?> builder = PoolBuilder
.from(Mono.just(uniqueElement))
.sizeBetween(1, 1)
.evictionPredicate((poolable, metadata) -> true);
AbstractPool<Formatter> pool = configAdjuster.apply(builder);
pool.warmup().block();
Mono<Void> disposeMono = pool.disposeLater();
Mono<Void> disposeMono2 = pool.disposeLater();
assertThat(disposeMono)
.isNotSameAs(disposeMono2);
assertThatCode(uniqueElement::flush)
.doesNotThrowAnyException();
}
public void appendFormattedMessage(StringBuilder sb) {
// Unfortunately, there's no public API to reset a Formatter's
// Appendable. If this proves to be a perf issue, we can do
// runtime introspection to access the private Formatter.init()
// API to replace the Appendable.
try (Formatter f = new Formatter(sb, Locale.US)) {
f.format(getMessage(), getParameters());
} catch (IllegalFormatException e) {
sb.append("Invalid format string: ");
sb.append(displayLevel);
sb.append(" '");
sb.append(getMessage());
sb.append("' ");
Object[] params = getParameters();
if (params == null) {
params = new Object[0];
}
sb.append(Arrays.asList(params));
} catch (ConcurrentModificationException originalException) {
// This way we may be at least able to figure out where offending log was created.
throw new ConcurrentModificationException(
"Concurrent modification when logging for message " + getMessage(), originalException);
}
}
private String encode(String script) {
JPackerWords words = new JPackerWords(script, encoding);
Pattern wordsPattern = Pattern.compile("\\w+");
Matcher wordsMatcher = wordsPattern.matcher(script);
StringBuffer sb = new StringBuffer();
while (wordsMatcher.find()) {
JPackerWord tempWord = new JPackerWord(wordsMatcher.group());
wordsMatcher.appendReplacement(sb, words.find(tempWord).getEncoded());
}
wordsMatcher.appendTail(sb);
int ascii = Math.min(Math.max(words.getWords().size(), 2), encoding.getEncodingBase());
String p = escape(sb.toString());
String a = String.valueOf(ascii);
String c = String.valueOf(words.getWords().size());
String k = words.toString();
String e = getEncode(ascii);
String r = ascii > 10 ? "e(c)" : "c";
return new Formatter().format(UNPACK, p, a, c, k, e, r).toString();
}
/**
* Utility method to dump a byte array in a java syntax.
* @param bytes and array of bytes
* @return a string containing the bytes formatted in java syntax
*/
protected static String dumpSerialStream(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 5);
Formatter fmt = new Formatter(sb);
fmt.format(" byte[] bytes = {" );
final int linelen = 10;
for (int i = 0; i < bytes.length; i++) {
if (i % linelen == 0) {
fmt.format("%n ");
}
fmt.format(" %3d,", bytes[i] & 0xff);
if ((i % linelen) == (linelen-1) || i == bytes.length - 1) {
fmt.format(" /*");
int s = i / linelen * linelen;
int k = i % linelen;
for (int j = 0; j <= k && s + j < bytes.length; j++) {
fmt.format(" %c", bytes[s + j] & 0xff);
}
fmt.format(" */");
}
}
fmt.format("%n };%n");
return sb.toString();
}
public static int showOffsets(StructureMembers members, Indent indent, Formatter f) {
int offset = 0;
for (StructureMembers.Member m : members.getMembers()) {
f.format("%s%s offset=%d (%d %s = %d bytes)%n", indent, m.getName(), m.getDataParam(), m.getSize(),
m.getDataType(), m.getSizeBytes());
if (m.getStructureMembers() != null) {
indent.incr();
StructureMembers nested = m.getStructureMembers();
f.format("%n%s%s == %d bytes%n", indent, nested.getName(), nested.getStructureSize());
showOffsets(nested, indent, f);
indent.decr();
}
}
return offset;
}
private URI readDistroUrlDeprecatedWay() throws URISyntaxException {
String distroUrl = null;
try {
distroUrl = getProperty("urlRoot") + "/"
+ getProperty("distributionName") + "-"
+ getProperty("distributionVersion") + "-"
+ getProperty("distributionClassifier") + ".zip";
Formatter formatter = new Formatter();
formatter.format("Wrapper properties file '%s' contains deprecated entries 'urlRoot', 'distributionName', 'distributionVersion' and 'distributionClassifier'. These will be removed soon. Please use '%s' instead.%n", propertiesFile, DISTRIBUTION_URL_PROPERTY);
warningOutput.append(formatter.toString());
} catch (Exception e) {
//even the deprecated properties are not provided, report error:
reportMissingProperty(DISTRIBUTION_URL_PROPERTY);
}
return new URI(distroUrl);
}
/**
* EL式を評価する。
* @param expression EL式
* @param values EL式中の変数。
* @return 評価した式。
* @throws ExpressionEvaluationException
*/
protected String evaluateExpression(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
final Map<String, Object> context = new LinkedHashMap<String, Object>();
context.putAll(values);
// フォーマッターの追加
context.computeIfAbsent("formatter", key -> new Formatter());
final String value = expressionLanguage.evaluate(expression, context).toString();
if(logger.isTraceEnabled()) {
logger.trace("evaluate expression language: expression='{}' ===> value='{}'", expression, value);
}
return value;
}
/**
* Gets a capability provided by the {@link GraalRuntime} instance available to the application.
*
* @throws UnsupportedOperationException if the capability is not available
*/
public static <T> T getRequiredCapability(Class<T> clazz) {
T t = getRuntime().getCapability(clazz);
if (t == null) {
String javaHome = System.getProperty("java.home");
String vmName = System.getProperty("java.vm.name");
Formatter errorMessage = new Formatter();
if (getRuntime().getClass() == InvalidGraalRuntime.class) {
errorMessage.format("The VM does not support the Graal API.%n");
} else {
errorMessage.format("The VM does not expose required Graal capability %s.%n", clazz.getName());
}
errorMessage.format("Currently used Java home directory is %s.%n", javaHome);
errorMessage.format("Currently used VM configuration is: %s", vmName);
throw new UnsupportedOperationException(errorMessage.toString());
}
return t;
}
public void testHorizCoordSys(Formatter f) {
GdsHorizCoordSys cs = makeHorizCoordSys();
f.format("%s testProjection %s%n", getClass().getName(), cs.proj.getClass().getName());
double endx = cs.startx + (getNx() - 1) * cs.dx;
double endy = cs.starty + (getNy() - 1) * cs.dy;
ProjectionPoint endPP = ProjectionPoint.create(endx, endy);
f.format(" start at proj coord= %s%n", ProjectionPoint.create(cs.startx, cs.starty));
f.format(" end at proj coord= %s%n", endPP);
LatLonPoint startLL = LatLonPoint.create(la1, lo1);
LatLonPoint endLL = cs.proj.projToLatLon(endPP);
f.format(" start at latlon= %s%n", startLL);
f.format(" end at latlon= %s%n", endLL);
}
private String prettyPrintCM (Evaluation.Matrix matrix, String[] classes ) {
double[][] values = matrix.values;
String[] classAbb = new String[classes.length];
StringBuilder res = new StringBuilder();
Formatter formatter = new Formatter(res,Locale.US);
int max = 0;
for (int i = 0; i < classes.length; i++) {
classAbb[i] = classes[i].replaceAll("\\B(.{1,2}).*?(.)\\b","$1$2");
if (classAbb[i].length() > max) max = classAbb[i].length();
}
max++;
String formatStr = "%-"+max+"s";
formatter.format(formatStr,"");
for (int i = 0; i < classes.length; i++) {
formatter.format(formatStr,classAbb[i]);
}
res.append("\n\n");
for (int i = 0; i < classes.length; i++ ) {
formatter.format(formatStr,classAbb[i]);
for (int j = 0; j < classes.length; j++) {
formatter.format(formatStr,Double.toString(values[i][j]));
}
res.append("\n\n");
}
return res.toString();
}
private boolean doCompare(String location, boolean showCompare, boolean showEach, boolean compareData)
throws IOException {
try (NetcdfFile ncfile = NetcdfFiles.open(location); NetcdfFile jni = openJni(location)) {
jni.setLocation(location + " (jni)");
// System.out.printf("Compare %s to %s%n", ncfile.getIosp().getClass().getName(),
// jni.getIosp().getClass().getName());
Formatter f = new Formatter();
CompareNetcdf2 tc = new CompareNetcdf2(f, showCompare, showEach, compareData);
boolean ok = tc.compare(ncfile, jni, new CompareNetcdf2.Netcdf4ObjectFilter());
System.out.printf(" %s compare %s ok = %s%n", ok ? "" : "***", location, ok);
if (!ok || (showCompare && showCompareResults))
System.out.printf("%s%n=====================================%n", f);
return ok;
}
}
@Override
protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated() || subject.isRemembered()) {
chain.doFilter(request, response);
} else {
WebUtils.saveRequest(request);
String path = WebUtils.getContextPath((HttpServletRequest) request);
String url = loginUrl;
if (StringUtils.isNotBlank(path) && path.length() > 1) {
url = path + url;
}
if (isAjaxRequest((HttpServletRequest) request)) {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print(JSON.toJSONString(Result.failure("您还没有登录!")));
} else {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(new Formatter().format(JS, url).toString());
}
}
}
@Test
public void testUselessWidthAndPrecision() {
final Formattable f = new Formattable() {
@Override
public void formatTo(final Formatter formatter, final int flags, final int width, final int precision) {
final StringBuilder sb = new StringBuilder();
sb.append(flags);
sb.append(":");
sb.append(width);
sb.append(":");
sb.append(precision);
formatter.format("%s", sb);
}
};
final String result = String.format("%10.3s", f);
System.out.println(result);
Assert.assertEquals("0:10:3", result);
}
private void compareWithBuilder(String filename) throws Exception {
logger.info("TestBuilders on {}%n", filename);
SPFactory.setServiceProvider("ucar.nc2.iosp.netcdf3.N3raf");
try (NetcdfFile org = NetcdfFile.open(filename)) {
SPFactory.setServiceProvider("ucar.nc2.internal.iosp.netcdf3.N3iospNew");
try (NetcdfFile withBuilder = NetcdfFile.open(filename)) {
Formatter f = new Formatter();
CompareNetcdf2 compare = new CompareNetcdf2(f, false, false, true);
if (!compare.compare(org, withBuilder)) {
System.out.printf("Compare %s%n%s%n", filename, f);
fail();
}
}
} finally {
SPFactory.setServiceProvider("ucar.nc2.iosp.netcdf3.N3raf");
}
}
private void readData(Formatter f) {
List<MessageBean> beans = messageTable.getBeans();
int count = 0;
try {
for (MessageBean bean : beans) {
bean.read();
count++;
}
f.format("Read %d messages", count);
} catch (Exception e) {
StringWriter sw = new StringWriter(10000);
e.printStackTrace(new PrintWriter(sw));
f.format("%s", sw.toString());
}
}
public static String getNumberTime2(long time_second) {
Formatter formatter = new Formatter(null, Locale.getDefault());
if (time_second < 0) {
time_second = 0;
}
try {
String formatter2;
long seconds = time_second % 60;
if (time_second / 60 > 99) {
formatter2 = formatter.format("%03d:%02d", new Object[]{Long.valueOf(time_second / 60), Long.valueOf(seconds)}).toString();
} else {
formatter2 = formatter.format("%02d:%02d", new Object[]{Long.valueOf(time_second / 60), Long.valueOf(seconds)}).toString();
formatter.close();
}
return formatter2;
} finally {
formatter.close();
}
}
public synchronized void logAndClear() {
if (payloadIdMissingMessagesMap.isEmpty()) {
return;
}
final StringBuilder stringBuilder = new StringBuilder();
final Formatter formatter = new Formatter(stringBuilder);
formatter.format("%n%1$31s%n%n", "MISSING PAYLOADS");
formatter.format("%1$19s | %2$8s | %3$47s %n", "payloadId", "retained", "topic");
formatter.format("%1$s%n", bigLine);
for (final Map.Entry<Long, MissingMessageInformation> entry : payloadIdMissingMessagesMap.entrySet()) {
final MissingMessageInformation missingMessage = entry.getValue();
formatter.format("%1$19d | %2$8b | %3$47s %n", missingMessage.getPayloadId(), missingMessage.isRetained(), missingMessage.getTopic());
formatter.format("%n%1$s%n", smallLine);
}
formatter.flush();
migrationLog.warn(stringBuilder.toString());
payloadIdMissingMessagesMap.clear();
}
@Override
public void writeTo(final Formatter f, final Object aValueToWrite, final Appendable aOut) throws IOException {
if (aValueToWrite == null) {
if ((flags & FormattableFlags.UPPERCASE) > 0) {
aOut.append("NULL");
} else {
aOut.append("null");
}
} else if (aValueToWrite instanceof Boolean) {
if ((flags & FormattableFlags.UPPERCASE) > 0) {
aOut.append(String.valueOf(((Boolean) aValueToWrite).booleanValue()).toUpperCase());
} else {
aOut.append(String.valueOf(((Boolean) aValueToWrite).booleanValue()));
}
} else {
if ((flags & FormattableFlags.UPPERCASE) > 0) {
aOut.append("true");
} else {
aOut.append("true");
}
}
}
/**
* Write the columns as fixed width text to the output.
*
* @param out Output stream.
* @param columns Columns
* @throws IOException Signals that an I/O exception has occurred.
*/
private static void writeColumns(OutputStream out,
List<List<String>> columns) throws IOException {
// Create format using the column widths
final String format = createTextFormatFromColumnWidths(columns);
// Output
try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
Formatter formatter = new Formatter(output)) {
final int rows = columns.get(0).size();
final Object[] args = new Object[columns.size()];
for (int row = 0; row < rows; row++) {
for (int i = 0; i < args.length; i++) {
args[i] = columns.get(i).get(row);
}
formatter.format(format, args);
}
}
}
/**
* Generates the label for one series in a category chart.
*
* @param dataset the dataset ({@code null} not permitted).
* @param seriesKey the key ({@code null} not permitted).
*
* @return The label (never {@code null} for this implementation).
*/
@Override
public String generateSeriesLabel(CategoryDataset3D<S, R, C> dataset,
S seriesKey) {
Args.nullNotPermitted(dataset, "dataset");
Args.nullNotPermitted(seriesKey, "seriesKey");
Formatter formatter = new Formatter(new StringBuilder());
int count = DataUtils.count(dataset, seriesKey);
double total = DataUtils.total(dataset, seriesKey);
formatter.format(this.template, seriesKey, count, total);
String result = formatter.toString();
formatter.close();
return result;
}
public static String wordProbToString(double[] prob, List<LdLocale> langlist) {
Formatter formatter = new Formatter();
for(int j=0;j<prob.length;++j) {
double p = prob[j];
if (p>=0.00001) {
formatter.format(" %s:%.5f", langlist.get(j), p);
}
}
return formatter.toString();
}
@Override
public void toString(final StringBuilder builder) {
if (this.name != null) {
builder.append(this.name).append(':');
}
try (final Formatter formatter = new Formatter(builder)) {
formatter.format("%.2f", this.size / BYTES_PER_MB);
builder.append("MB used, ");
builder.append(getPercentFree()).append("% free, ");
builder.append(this.evictions).append(" evictions");
}
}
@Override
public void showIndex(Formatter f) {
super.showIndex(f);
f.format("%nPartition isPartitionOfPartitions = %s%n", isPartitionOfPartitions);
for (Partition p : partitions) {
f.format(" %s%n", p);
}
}
/**
* Dump this variable
*
* @return the variable
*/
public String dump() {
DateFormatter formatter = new DateFormatter();
Formatter sbuff = new Formatter();
sbuff.format("%s %d %n", name, records.size());
for (GridRecord record : records) {
sbuff.format(" level = %d %f", record.getLevelType1(), record.getLevel1());
if (null != record.getValidTime())
sbuff.format(" time = %s", formatter.toDateTimeString(record.getValidTime()));
sbuff.format("%n");
}
return sbuff.toString();
}
/**
* Make a long name for the variable
*
* @return long variable name
*/
protected String makeLongName() {
Formatter f = new Formatter();
GridParameter param = lookup.getParameter(firstRecord);
if (param == null)
return null;
f.format("%s", param.getDescription());
String levelName = makeLevelName(firstRecord, lookup);
if (!levelName.isEmpty())
f.format(" @ %s", levelName);
return f.toString();
}
private void emitHtmlBody(PrintWriter out) {
Formatter formatter = new Formatter(out, Locale.US);
out.write(
"<p class=\"header\">"
+ "<img class=\"oc\" src=\"https://opencensus.io/img/logo-sm.svg\" />"
+ "Open<span>Census</span></p>");
out.write("<h1>RPC Stats</h1>");
out.write("<p></p>");
emitSummaryTable(out, formatter, /* isReceived= */ false);
emitSummaryTable(out, formatter, /* isReceived= */ true);
}
private void doOne(String filename) throws Exception {
try (NetcdfFile ncfile = NetcdfDatasets.acquireFile(DatasetUrl.create(null, filename), null);
NetcdfDataset ncWrap = new NetcdfDataset(ncfile, true);
NetcdfDataset ncd = NetcdfDataset.acquireDataset(DatasetUrl.create(null, filename), true, null)) {
System.out.println(" dataset wraps= " + filename);
Assert.assertTrue(CompareNetcdf2.compareFiles(ncd, ncWrap, new Formatter()));
}
}
private void testException(final Class<? extends ODataLibraryException> clazz,
final ODataLibraryException.MessageKey[] messageKeys) throws Exception {
for (ODataLibraryException.MessageKey messageKey : messageKeys) {
String propKey = clazz.getSimpleName() + "." + messageKey.toString();
String value = properties.getProperty(propKey);
Assert.assertNotNull("No value found for message key '" + propKey + "'", value);
//
int paraCount = countParameters(value);
Constructor<? extends ODataLibraryException> ctor =
clazz.getConstructor(String.class, ODataLibraryException.MessageKey.class, String[].class);
String[] paras = new String[paraCount];
for (int i = 0; i < paras.length; i++) {
paras[i] = "470" + i;
}
String developerMessage = UUID.randomUUID().toString();
ODataLibraryException e = ctor.newInstance(developerMessage, messageKey, paras);
try {
throw e;
} catch (ODataLibraryException translatedException) {
Formatter formatter = new Formatter();
String formattedValue = formatter.format(value, (Object[]) paras).toString();
formatter.close();
Assert.assertEquals(formattedValue, translatedException.getTranslatedMessage(null).getMessage());
Assert.assertEquals(formattedValue, translatedException.getLocalizedMessage());
Assert.assertEquals(developerMessage, translatedException.getMessage());
}
}
}
/**
* Wrap a NetcdfDataset as a FeatureDataset.
*
* @param wantFeatureType open this kind of FeatureDataset; may be null, which means search all factories.
* If datatype is not null, only return FeatureDataset with objects of that type
* @param ncd the NetcdfDataset to wrap as a FeatureDataset
* @param task user may cancel
* @param errlog place errors here, may not be null
* @return a subclass of FeatureDataset, or null if no suitable factory was found
* @throws java.io.IOException on io error
*/
public static FeatureDataset wrap(FeatureType wantFeatureType, NetcdfDataset ncd, ucar.nc2.util.CancelTask task,
Formatter errlog) throws IOException {
if (debug)
System.out.println("wrap " + ncd.getLocation() + " want = " + wantFeatureType);
// the case where we dont know what type it is
if ((wantFeatureType == null) || (wantFeatureType == FeatureType.ANY)) {
return wrapUnknown(ncd, task, errlog);
}
// find a Factory that claims this dataset by passing back an "analysis result" object
Object analysis = null;
FeatureDatasetFactory useFactory = null;
for (Factory fac : factoryList) {
if (!featureTypeOk(wantFeatureType, fac.featureType))
continue;
if (debug)
System.out.println(" wrap try factory " + fac.factory.getClass().getName());
analysis = fac.factory.isMine(wantFeatureType, ncd, errlog);
if (analysis != null) {
useFactory = fac.factory;
break;
}
}
if (null == useFactory) {
errlog.format("**Failed to find FeatureDatasetFactory for= %s datatype=%s%n", ncd.getLocation(), wantFeatureType);
return null;
}
// this call must be thread safe - done by implementation
return useFactory.open(wantFeatureType, ncd, analysis, task, errlog);
}