下面列出了java.util.Formatter#format ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
/**
* 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();
}
/**
* Make a space-delineated String from a list of Dimension names.
* Inverse of makeDimensionsList().
*
* @return space-delineated String of Dimension names.
* @deprecated use Dimensions.makeDimensionsString()
*/
@Deprecated
public static String makeDimensionsString(List<Dimension> dimensions) {
if (dimensions == null)
return "";
Formatter buf = new Formatter();
for (int i = 0; i < dimensions.size(); i++) {
Dimension myd = dimensions.get(i);
String dimName = myd.getShortName();
if (i != 0)
buf.format(" ");
if (myd.isVariableLength()) {
buf.format("*");
} else if (myd.isShared()) {
buf.format("%s", dimName);
} else {
// if (dimName != null) // LOOK losing anon dim name
// buf.format("%s=", dimName);
buf.format("%d", myd.getLength());
}
}
return buf.toString();
}
public void styleColor(Formatter out, String attr, Color color) {
if (color == null) {
return;
}
HSSFColor hSSFColor = (HSSFColor) color;
short[] rgb = hSSFColor.getTriplet();
out.format(" %s: #%02x%02x%02x; %n", attr, rgb[0], rgb[1], rgb[2]);
}
private static void emitMeasureTableHeader(PrintWriter out, Formatter formatter) {
out.write("<thead>");
out.write("<tr>");
formatter.format("<th colspan=1>%s</th>", TABLE_HEADER_MEASURE);
formatter.format("<th colspan=1 class=\"borderL\">%s</th>", TABLE_HEADER_DESCRIPTION);
formatter.format("<th colspan=1 class=\"borderL\">%s</th>", TABLE_HEADER_UNIT);
formatter.format("<th colspan=1 class=\"borderL\">%s</th>", TABLE_HEADER_MEASURE_TYPE);
out.write("</tr>");
out.write("</thead>");
}
public void formatTo(Formatter fmt, int f, int width, int precision) {
StringBuilder sb = new StringBuilder();
// decide form of name
String name = companyName;
if (fmt.locale().equals(Locale.FRANCE))
name = frenchCompanyName;
boolean alternate = (f & ALTERNATE) == ALTERNATE;
boolean usesymbol = alternate || (precision != -1 && precision < 10);
String out = (usesymbol ? symbol : name);
// apply precision
if (precision == -1 || out.length() < precision) {
// write it all
sb.append(out);
} else {
sb.append(out.substring(0, precision - 1)).append('*');
}
// apply width and justification
int len = sb.length();
if (len < width)
for (int i = 0; i < width - len; i++)
if ((f & LEFT_JUSTIFY) == LEFT_JUSTIFY)
sb.append(' ');
else
sb.insert(0, ' ');
fmt.format(sb.toString());
}
@Override
public String asText(int indentlen) {
StringBuilder s = new StringBuilder();
Formatter formatter = new Formatter(s, Locale.US);
if (lft < 0) {
formatter.format("%s ", taxon.getId());
} else {
formatter.format("%s ", "+");
}
while (s.length() < 20-indentlen) {
formatter.format("%s", " ");
}
formatter.format("%s ", AlloppMisc.nonnegIn8Chars(height));
return s.toString();
}
private static String byteArray2Hex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
return formatter.toString();
}
public void formatTo(Formatter fmt, int f, int width, int precision) {
StringBuilder sb = new StringBuilder();
// decide form of name
String name = companyName;
if (fmt.locale().equals(Locale.FRANCE))
name = frenchCompanyName;
boolean alternate = (f & ALTERNATE) == ALTERNATE;
boolean usesymbol = alternate || (precision != -1 && precision < 10);
String out = (usesymbol ? symbol : name);
// apply precision
if (precision == -1 || out.length() < precision) {
// write it all
sb.append(out);
} else {
sb.append(out.substring(0, precision - 1)).append('*');
}
// apply width and justification
int len = sb.length();
if (len < width)
for (int i = 0; i < width - len; i++)
if ((f & LEFT_JUSTIFY) == LEFT_JUSTIFY)
sb.append(' ');
else
sb.insert(0, ' ');
fmt.format(sb.toString());
}
/** Initialize the OutputStream to the next file to write to.
*/
private void openNextFile() throws IOException {
StringBuffer sb = new StringBuffer();
Formatter fmt = new Formatter(sb);
fmt.format("%05d", this.fileNum++);
String filename = filePrefix + fmt.toString();
if (codec != null) {
filename = filename + codec.getDefaultExtension();
}
Path destFile = new Path(destDir, filename);
FileSystem fs = destFile.getFileSystem(conf);
LOG.debug("Opening next output file: " + destFile);
if (fs.exists(destFile)) {
Path canonicalDest = destFile.makeQualified(fs);
throw new IOException("Destination file " + canonicalDest
+ " already exists");
}
OutputStream fsOut = fs.create(destFile);
// Count how many actual bytes hit HDFS.
this.countingFilterStream = new CountingOutputStream(fsOut);
if (codec != null) {
// Wrap that in a compressing stream.
this.writeStream = codec.createOutputStream(this.countingFilterStream);
} else {
// Write to the counting stream directly.
this.writeStream = this.countingFilterStream;
}
}
public static String getFourLineHexString(byte[] sha256Hash){
Formatter formatter = new Formatter();
for (int i = 0; i < 32; i++) {
formatter.format("%02X", sha256Hash[i]);
if (i == 7 || i == 15 || i == 23) {
formatter.format("\n");
} else if (i != 31) {
formatter.format(" ");
}
}
return formatter.toString();
}
private static void formatConfiguration(Formatter formatter, QuorumConfigurationMessage message) {
formatter.format("(");
if (message.getTransitional()) {
formatPeerIdList(formatter, message.getPrevPeersList());
formatter.format(" -> ");
formatPeerIdList(formatter, message.getNextPeersList());
} else {
formatPeerIdList(formatter, message.getAllPeersList());
}
formatter.format(")");
}
@Override
public void showInternal(Formatter f, Indent indent) {
super.showInternal(f, indent);
for (StructureMembers.Member m : memberData.keySet()) {
Array data = memberData.get(m);
f.format("%s %s = %s%n", indent, m, data);
}
}
/**
* Check if this is a POINT datatype. If so, a TableAnalyser is used to analyze its structure.
* The TableAnalyser is reused when the dataset is opened.
* <ol>
* <li>Can handle ANY_POINT FeatureType.
* <li>Must have time, lat, lon axis (from CoordSysBuilder)
* <li>Call TableAnalyzer.factory() to create a TableAnalyzer
* <li>TableAnalyzer must agree it can handle the requested FeatureType
* </ol>
*
* @param wantFeatureType desired feature type, null means FeatureType.ANY_POINT
* @param ds analyse this dataset
* @param errlog log error messages here (may not be null)
* @return if successful, return non-null. This object is then passed back into open(), so analysis can be reused.
*/
@Override
public Object isMine(FeatureType wantFeatureType, NetcdfDataset ds, Formatter errlog) {
if (wantFeatureType == null)
wantFeatureType = FeatureType.ANY_POINT;
if (wantFeatureType != FeatureType.ANY_POINT) {
if (!wantFeatureType.isPointFeatureType())
return null;
}
TableConfigurer tc = TableAnalyzer.getTableConfigurer(wantFeatureType, ds);
// if no explicit tc, then check whatever we can before expensive analysis)
if (tc == null) {
boolean hasTime = false;
boolean hasLat = false;
boolean hasLon = false;
for (CoordinateAxis axis : ds.getCoordinateAxes()) {
if (axis.getAxisType() == AxisType.Time) // && (axis.getRank() == 1))
hasTime = true;
if (axis.getAxisType() == AxisType.Lat) // && (axis.getRank() == 1))
hasLat = true;
if (axis.getAxisType() == AxisType.Lon) // && (axis.getRank() == 1))
hasLon = true;
}
// minimum we need
if (!(hasTime && hasLon && hasLat)) {
errlog.format("PointDataset must have lat,lon,time");
return null;
}
} else if (showTables) {
System.out.printf("TableConfigurer = %s%n", tc.getClass().getName());
}
try {
// gotta do some work
TableAnalyzer analyser = TableAnalyzer.factory(tc, wantFeatureType, ds);
if (analyser == null)
return null;
if (!analyser.featureTypeOk(wantFeatureType, errlog)) {
return null;
}
return analyser;
} catch (Throwable t) {
return null;
}
}
private TableConfig makeStationTable(NetcdfDataset ds, FeatureType ftype, EncodingInfo info, Formatter errlog) {
Variable lat = CoordSysEvaluator.findCoordByType(ds, AxisType.Lat);
Variable lon = CoordSysEvaluator.findCoordByType(ds, AxisType.Lon);
if (lat == null || lon == null) {
errlog.format("CFpointObs: must have lat and lon coordinates%n");
return null;
}
// Dimension stationDim = (info.encoding == Encoding.single) ? null : lat.getDimension(0); // assumes outer dim of
// lat is parent dimension, single = scalar
Table.Type stationTableType = Table.Type.Structure;
if (info.encoding == Encoding.single)
stationTableType = Table.Type.Top;
if (info.encoding == Encoding.flat)
stationTableType = Table.Type.Construct;
Dimension stationDim = (info.encoding == Encoding.flat) ? info.childDim : info.parentDim;
String name = (stationDim == null) ? " single" : stationDim.getShortName();
TableConfig stnTable = new TableConfig(stationTableType, name);
stnTable.featureType = ftype;
// stnId
Variable stnIdVar =
Evaluator.findVariableWithAttributeAndDimension(ds, CF.CF_ROLE, CF.TIMESERIES_ID, stationDim, errlog);
if (stnIdVar == null)
stnIdVar =
Evaluator.findVariableWithAttributeAndDimension(ds, CF.STANDARD_NAME, CF.STATION_ID, stationDim, errlog);
if (stnIdVar == null) {
errlog.format("CFpointObs: must have a Station id variable with %s = %s%n", CF.CF_ROLE, CF.TIMESERIES_ID);
return null;
}
stnTable.stnId = stnIdVar.getFullName();
info.instanceId = stnIdVar;
stnTable.stnDesc = Evaluator.findNameVariableWithStandardNameAndDimension(ds, CF.PLATFORM_NAME, stationDim, errlog);
if (stnTable.stnDesc == null)
stnTable.stnDesc =
Evaluator.findNameVariableWithStandardNameAndDimension(ds, CF.STATION_DESC, stationDim, errlog);
stnTable.stnWmoId = Evaluator.findNameVariableWithStandardNameAndDimension(ds, CF.PLATFORM_ID, stationDim, errlog);
if (stnTable.stnWmoId == null)
stnTable.stnWmoId =
Evaluator.findNameVariableWithStandardNameAndDimension(ds, CF.STATION_WMOID, stationDim, errlog);
stnTable.stnAlt =
Evaluator.findNameVariableWithStandardNameAndDimension(ds, CF.SURFACE_ALTITUDE, stationDim, errlog);
if (stnTable.stnAlt == null)
stnTable.stnAlt =
Evaluator.findNameVariableWithStandardNameAndDimension(ds, CF.STATION_ALTITUDE, stationDim, errlog);
stnTable.lat = lat.getFullName();
stnTable.lon = lon.getFullName();
if (info.encoding != Encoding.single && stationDim != null) {
stnTable.dimName = stationDim.getShortName();
makeStructureInfo(stnTable, ds, stnIdVar.getParentStructure(), stationDim);
}
// LOOK probably need a standard name here
// optional alt coord - detect if its a station height or actually associated with the obs, eg for a profile
if (stnTable.stnAlt == null) {
Variable alt = CoordSysEvaluator.findCoordByType(ds, AxisType.Height);
if (alt != null) {
if ((info.encoding == Encoding.single) && alt.getRank() == 0)
stnTable.stnAlt = alt.getFullName();
if ((info.encoding != Encoding.single) && (lat.getRank() == alt.getRank()) && alt.getRank() > 0
&& alt.getDimension(0).equals(stationDim))
stnTable.stnAlt = alt.getFullName();
}
}
return stnTable;
}
@Override
protected void showTableExtraInfo(String indent, Formatter f) {
f.format("%sstart=%s, numRecords=%s%n", indent, startVarName, numRecordsVarName);
}
protected void writeCDL(Formatter f, Indent indent, boolean strict) {
toStringStart(f, indent, strict);
f.format("%s}%n", indent);
}
@Override
public String toString() {
Formatter ff = new Formatter();
ff.format("equatorRadius=%f inverseFlattening=%f", equatorRadius, (1.0 / flattening));
return ff.toString();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(" mean:").append(mean).append(" median:").append(getQuantile(0.5f)).append(" mode:").append(mode).append(" 10tile:").append(getQuantile(0.1f)).append(" 90tile:").append(getQuantile(0.9f));
b.append('\n');
Formatter l1 = new Formatter();
Formatter l2 = new Formatter();
for(int i=0;i<values.length;i++) {
if(values[i] >= 0.001) {
l1.format(" %5d | ", i*BIN_SIZE);
l2.format("%5d%% | ", Math.round(values[i]*100));
}
}
b.append(l1).append('\n');
b.append(l2).append('\n');
return b.toString();
}
static void printf(Formatter formatter, String format, Object... args) throws IOException {
formatter.format(format, args);
IOException ioException = formatter.ioException();
if (ioException != null) throw ioException;
}