下面列出了怎么用java.text.Format的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testToDateWithFormatOnDate() throws Exception {
long ts = nextTimestamp();
initPtsdbTableValues(ts);
String format = "yyyy-MM-dd HH:mm:ss.S";
Format dateFormatter = DateUtil.getDateFormatter(format);
String query = "SELECT HOST,TO_CHAR(DATE,'" + format + "') FROM PTSDB WHERE INST='x' AND HOST='y' and DATE=TO_DATE(?,'" + format + "')";
String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
try {
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, dateFormatter.format(D1));
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(dateFormatter.format(D1), rs.getString(2));
} finally {
conn.close();
}
}
public RampartProcessArgs(RampartStage stage) {
super(new Params());
this.outputDir = new File("");
this.samples = new ArrayList<>();
this.threads = DEFAULT_THREADS;
this.memoryMb = DEFAULT_MEMORY;
this.runParallel = DEFAULT_RUN_PARALLEL;
this.stage = stage;
this.organism = null;
Format formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
String dateTime = formatter.format(new Date());
this.jobPrefix = "rampart-" + stage.getOutputDirName() + "-" + dateTime;
}
/**
*
*/
protected Format getFormat(Object value, TimeZone ownTimeZone)//FIXMEFORMAT optimize this with an interface
{
Format format = null;
if (value instanceof java.util.Date)
{
format = filler.getDateFormat(getDatePattern(value), ownTimeZone);
}
else if (value instanceof java.lang.Number)
{
format = filler.getNumberFormat(getNumberPattern(value));
}
return format;
}
/**
* We use this method to get the data, since we are using
* ObjectTableModel, so the calling getDataVector doesn't
* work as expected.
*
* @param model {@link ObjectTableModel}
* @param formats Array of {@link Format} array can contain null formatters in this case value is added as is
* @return the data from the model
*/
public static List<List<Object>> getAllTableData(ObjectTableModel model, Format[] formats) {
List<List<Object>> data = new ArrayList<>();
if (model.getRowCount() > 0) {
for (int rw = 0; rw < model.getRowCount(); rw++) {
int cols = model.getColumnCount();
List<Object> column = new ArrayList<>();
data.add(column);
for (int idx = 0; idx < cols; idx++) {
Object val = model.getValueAt(rw, idx);
if (formats[idx] != null) {
column.add(formats[idx].format(val));
} else {
column.add(val);
}
}
}
}
return data;
}
@Override
public String toStringLiteral(Object o, Format formatter) {
StringBuilder buf = new StringBuilder(PArrayDataType.ARRAY_TYPE_SUFFIX + "[");
PhoenixArray array = (PhoenixArray)o;
PDataType baseType = PDataType.arrayBaseType(this);
int len = array.getDimensions();
if (len != 0) {
for (int i = 0; i < len; i++) {
buf.append(baseType.toStringLiteral(array.getElement(i), null));
buf.append(',');
}
buf.setLength(buf.length()-1);
}
buf.append(']');
return buf.toString();
}
/**
* Get a custom format from a format description.
*
* @param desc String
* @return Format
*/
private Format getFormat(String desc) {
if (registry != null) {
String name = desc;
String args = null;
int i = desc.indexOf(START_FMT);
if (i > 0) {
name = desc.substring(0, i).trim();
args = desc.substring(i + 1).trim();
}
FormatFactory factory = registry.get(name);
if (factory != null) {
return factory.getFormat(name, args, getLocale());
}
}
return null;
}
/**
* @param encodedCert
* @return
* @throws CertificateException
*/
public static CertData getCertData(String encodedCert) throws CertificateException {
if (encodedCert != null) {
byte[] bytes = Base64.decode(encodedCert);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) factory
.generateCertificate(new ByteArrayInputStream(bytes));
Format formatter = new SimpleDateFormat("dd/MM/yyyy");
return fillCertData(cert, formatter);
} else {
String errorMsg = "Invalid encoded certificate: \'NULL\'";
log.debug(errorMsg);
throw new IllegalArgumentException(errorMsg);
}
}
/**
* Get a custom format from a format description.
*
* @param desc String
* @return Format
*/
private Format getFormat(String desc) {
if (registry != null) {
String name = desc;
String args = null;
int i = desc.indexOf(START_FMT);
if (i > 0) {
name = desc.substring(0, i).trim();
args = desc.substring(i + 1).trim();
}
FormatFactory factory = (FormatFactory) registry.get(name);
if (factory != null) {
return factory.getFormat(name, args, getLocale());
}
}
return null;
}
/**
* Adds an array of exceptions relative to the base timeline.
*
* @param timeline The timeline where the exceptions will be stored
* @param exceptionString The exceptions to load
* @param fmt The date formatter to use to parse each exceptions[i] value
* @throws ParseException If there is any exception parsing each
* exceptions[i] value.
*/
private void fillInBaseTimelineExceptions(SegmentedTimeline timeline,
String[] exceptionString,
Format fmt) throws ParseException {
SegmentedTimeline baseTimeline = timeline.getBaseTimeline();
for (int i = 0; i < exceptionString.length; i++) {
long e;
if (fmt instanceof NumberFormat) {
e = ((NumberFormat) fmt).parse(exceptionString[i]).longValue();
}
else {
e = timeline.getTime(((SimpleDateFormat) fmt)
.parse(exceptionString[i]));
}
timeline.addBaseTimelineException(e);
// verify all timeline segments included in the
// baseTimeline.segment are now exceptions
SegmentedTimeline.Segment segment1 = baseTimeline.getSegment(e);
for (SegmentedTimeline.Segment segment2
= timeline.getSegment(segment1.getSegmentStart());
segment2.getSegmentStart() <= segment1.getSegmentEnd();
segment2.inc()) {
if (!segment2.inExcludeSegments()) {
assertTrue(segment2.inExceptionSegments());
}
}
}
}
@Test
public void test_toFormat_parseObject_StringParsePosition() throws Exception {
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
ParsePosition pos = new ParsePosition(0);
TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30XXX", pos);
assertEquals(pos.getIndex(), 5);
assertEquals(pos.getErrorIndex(), -1);
assertEquals(result.isSupported(DAY_OF_MONTH), true);
assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
@SuppressWarnings("unchecked")
public PhoenixConnection(ConnectionQueryServices services, String url, Properties info, PMetaData metaData) throws SQLException {
this.url = url;
// Copy so client cannot change
this.info = info == null ? new Properties() : new Properties(info);
if (this.info.isEmpty()) {
this.services = services;
} else {
Map<String, String> existingProps = services.getProps().asMap();
Map<String, String> tmpAugmentedProps = Maps.newHashMapWithExpectedSize(existingProps.size() + info.size());
tmpAugmentedProps.putAll(existingProps);
tmpAugmentedProps.putAll((Map)this.info);
final ReadOnlyProps augmentedProps = new ReadOnlyProps(tmpAugmentedProps);
this.services = new DelegateConnectionQueryServices(services) {
@Override
public ReadOnlyProps getProps() {
return augmentedProps;
}
};
}
this.scn = JDBCUtil.getCurrentSCN(url, this.info);
this.tenantId = JDBCUtil.getTenantId(url, this.info);
this.mutateBatchSize = JDBCUtil.getMutateBatchSize(url, this.info, services.getProps());
datePattern = services.getProps().get(QueryServices.DATE_FORMAT_ATTRIB, DateUtil.DEFAULT_DATE_FORMAT);
int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
Format dateTimeFormat = DateUtil.getDateFormatter(datePattern);
formatters[PDataType.DATE.ordinal()] = dateTimeFormat;
formatters[PDataType.TIME.ordinal()] = dateTimeFormat;
this.metaData = PMetaDataImpl.pruneMultiTenant(metaData);
this.mutationState = new MutationState(maxSize, this);
services.addConnection(this);
}
@Test
public void test_toFormat_parseObject_StringParsePosition() throws Exception {
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
ParsePosition pos = new ParsePosition(0);
TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30XXX", pos);
assertEquals(pos.getIndex(), 5);
assertEquals(pos.getErrorIndex(), -1);
assertEquals(result.isSupported(DAY_OF_MONTH), true);
assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
private static String getPattern() {
final Date date = new Date();
final Format fileDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
final String pathLogFileFolder = Configuration.getPathLogFileFolder();
final Path logFileFolder = Paths.get(pathLogFileFolder);
if (Files.notExists(logFileFolder)) {
try {
Files.createDirectories(logFileFolder);
} catch (IOException e) {
Logger.getLogger(LogFileHandler.class.getName()).log(Level.SEVERE, "Could not create log file folder",
e);
}
}
return pathLogFileFolder + "mp_" + fileDateFormat.format(date) + ".log";
}
private static void checkSubformat(Format[] subformats, int index, Format expected) {
Format subformat = subformats[index];
if (subformat == expected) {
return;
}
if ((subformat != null) && subformat.equals(expected)) {
return;
}
throw new RuntimeException("found unexpected subformat for argument " + index + ":\n expected: " + expected + "\n actual: " + subformat);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_toFormat_parseObject_StringParsePosition_nullString() throws Exception {
// SimpleDateFormat has this behavior
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
ParsePosition pos = new ParsePosition(0);
format.parseObject((String) null, pos);
}
@Test
public void test_toFormat_parseObject_String() throws Exception {
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30");
assertEquals(result.isSupported(DAY_OF_MONTH), true);
assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
/**
* DOCUMENT ME!
*
* @param value DOCUMENT ME!
* @param columnClass DOCUMENT ME!
*/
private void configureValue(Object value, Class columnClass) {
if (columnClass == Object.class || columnClass == null) {
setHorizontalAlignment(JLabel.LEADING);
} else if (columnClass == Float.class || columnClass == Double.class) {
if (numberFormat == null) {
numberFormat = NumberFormat.getInstance();
}
setHorizontalAlignment(JLabel.TRAILING);
setText((value == null) ? "" : ((NumberFormat) numberFormat).format(value));
} else if (columnClass == Number.class) {
setHorizontalAlignment(JLabel.TRAILING);
// Super will have set value.
} else if (columnClass == Icon.class || columnClass == ImageIcon.class) {
setHorizontalAlignment(JLabel.CENTER);
setIcon((value instanceof Icon) ? (Icon) value : null);
setText("");
} else if (columnClass == Date.class) {
if (dateFormat == null) {
dateFormat = DateFormat.getDateInstance();
}
setHorizontalAlignment(JLabel.LEADING);
setText((value == null) ? "" : ((Format) dateFormat).format(value));
} else {
configureValue(value, columnClass.getSuperclass());
}
}
@Test
public void test_toFormat_parseObject_StringParsePosition_parseError() throws Exception {
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
ParsePosition pos = new ParsePosition(0);
TemporalAccessor result = (TemporalAccessor) format.parseObject("ONEXXX", pos);
assertEquals(pos.getIndex(), 0); // TODO: is this right?
assertEquals(pos.getErrorIndex(), 3);
assertEquals(result, null);
}
public static Object getFiscalDate( Context actualContext, Scriptable actualObject, Object[] ArgList,
Function FunctionContext ) {
if ( ArgList.length == 2 ) {
try {
if ( isNull( ArgList ) ) {
return null;
} else if ( isUndefined( ArgList ) ) {
return Context.getUndefinedValue();
}
Date dIn = (Date) Context.jsToJava( ArgList[ 0 ], Date.class );
Calendar startDate = Calendar.getInstance();
Calendar fisStartDate = Calendar.getInstance();
Calendar fisOffsetDate = Calendar.getInstance();
startDate.setTime( dIn );
Format dfFormatter = new SimpleDateFormat( "dd.MM.yyyy" );
String strOffsetDate = Context.toString( ArgList[ 1 ] ) + String.valueOf( startDate.get( Calendar.YEAR ) );
Date dOffset = (Date) dfFormatter.parseObject( strOffsetDate );
fisOffsetDate.setTime( dOffset );
String strFisStartDate = "01.01." + String.valueOf( startDate.get( Calendar.YEAR ) + 1 );
fisStartDate.setTime( (Date) dfFormatter.parseObject( strFisStartDate ) );
int iDaysToAdd = (int) ( ( startDate.getTimeInMillis() - fisOffsetDate.getTimeInMillis() ) / 86400000 );
fisStartDate.add( Calendar.DATE, iDaysToAdd );
return fisStartDate.getTime();
} catch ( Exception e ) {
throw Context.reportRuntimeError( e.toString() );
}
} else {
throw Context.reportRuntimeError( "The function call getFiscalDate requires 2 arguments." );
}
}
@Test
public void test_toFormat_parseObject_StringParsePosition_parseError() throws Exception {
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
ParsePosition pos = new ParsePosition(0);
TemporalAccessor result = (TemporalAccessor) format.parseObject("ONEXXX", pos);
assertEquals(pos.getIndex(), 0); // TODO: is this right?
assertEquals(pos.getErrorIndex(), 3);
assertEquals(result, null);
}
public FormattedContentToken( final Object original,
final Format format,
final String text ) {
this.format = format;
this.original = original;
this.text = text;
}
public String toStringLiteral(Object o, Format formatter) {
if (o == null) {
return String.valueOf(o);
}
if (formatter != null) {
return formatter.format(o);
}
return o.toString();
}
@Test
public void test_toFormat_parseObject_StringParsePosition_invalidPosition_tooSmall() throws Exception {
// SimpleDateFormat throws StringIndexOutOfBoundException
DateTimeFormatter dtf = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
ParsePosition pos = new ParsePosition(-1);
Format test = dtf.toFormat();
assertNull(test.parseObject("ONE30", pos));
assertTrue(pos.getErrorIndex() >= 0);
}
@Override
public void bindView(TextView view, Integer value, Format format) {
if (format != null) {
view.setText(format.format(value));
} else {
view.setText(value);
}
}
/**
* Tests methods related to adding exceptions.
*
* @param timeline the timeline to verify
* @param exceptionString array of Strings that represent the exceptions
* @param fmt Format object that can parse the exceptionString strings
*
* @throws ParseException if there is a parsing error.
*/
public void verifyExceptionSegments(SegmentedTimeline timeline,
String[] exceptionString,
Format fmt)
throws ParseException {
// fill in the exceptions
long[] exception = verifyFillInExceptions(timeline, exceptionString,
fmt);
int m = exception.length;
// verify list of exceptions
assertEquals(exception.length, timeline.getExceptionSegments().size());
SegmentedTimeline.Segment lastSegment = timeline.getSegment(
exception[m - 1]);
for (int i = 0; i < m; i++) {
SegmentedTimeline.Segment segment = timeline.getSegment(
exception[i]);
assertTrue(segment.inExceptionSegments());
// include current exception and last one
assertEquals(m - i, timeline.getExceptionSegmentCount(
segment.getSegmentStart(), lastSegment.getSegmentEnd()));
// exclude current exception and last one
assertEquals(Math.max(0, m - i - 2),
timeline.getExceptionSegmentCount(exception[i] + 1,
exception[m - 1] - 1));
}
}
private static void checkSubformat(Format[] subformats, int index, Format expected) {
Format subformat = subformats[index];
if (subformat == expected) {
return;
}
if ((subformat != null) && subformat.equals(expected)) {
return;
}
throw new RuntimeException("found unexpected subformat for argument " + index + ":\n expected: " + expected + "\n actual: " + subformat);
}
@Test
public void test_toFormat_parseObject_StringParsePosition_invalidPosition_tooSmall() throws Exception {
// SimpleDateFormat throws StringIndexOutOfBoundException
DateTimeFormatter dtf = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
ParsePosition pos = new ParsePosition(-1);
Format test = dtf.toFormat();
assertNull(test.parseObject("ONE30", pos));
assertTrue(pos.getErrorIndex() >= 0);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_toFormat_parseObject_StringParsePosition_nullParsePosition() throws Exception {
// SimpleDateFormat has this behavior
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
format.parseObject("ONE30", (ParsePosition) null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_toFormat_parseObject_StringParsePosition_nullParsePosition() throws Exception {
// SimpleDateFormat has this behavior
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
format.parseObject("ONE30", (ParsePosition) null);
}
private AttributedString createTickLabelAttributedString(double logy,
Format exponentFormatter) {
String baseStr = this.baseSymbol;
if (baseStr == null) {
baseStr = this.baseFormatter.format(this.base);
}
String exponentStr = exponentFormatter.format(logy);
AttributedString as = new AttributedString(baseStr + exponentStr);
as.addAttributes(getTickLabelFont().getAttributes(), 0, (baseStr
+ exponentStr).length());
as.addAttribute(TextAttribute.SUPERSCRIPT,
TextAttribute.SUPERSCRIPT_SUPER, baseStr.length(),
baseStr.length() + exponentStr.length());
return as;
}