下面列出了怎么用org.joda.time.DateTimeUtils的API类实例代码及写法,或者点击链接到github查看源代码。
TimestampedEvent(Event base) {
super(base);
// setBody(base.getBody());
Map<String, String> headers =base.getHeaders();
String timestampString = headers != null ?headers.get("timestamp"):null;
if (SimpleStringUtil.isEmpty(timestampString)) {
timestampString = headers.get("@timestamp");
}
if (SimpleStringUtil.isEmpty(timestampString)) {
this.timestamp = DateTimeUtils.currentTimeMillis();
headers.put("timestamp", String.valueOf(timestamp ));
} else {
this.timestamp = Long.valueOf(timestampString);
}
setHeaders(headers);
}
@Test
public void testWallTimeWatermarkEstimator() {
DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis());
WatermarkEstimator<Instant> watermarkEstimator =
new WatermarkEstimators.WallTime(new Instant());
DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1).getMillis());
assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1), watermarkEstimator.currentWatermark());
DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2).getMillis());
// Make sure that we don't mutate state even if the clock advanced
assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1), watermarkEstimator.getState());
assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2), watermarkEstimator.currentWatermark());
assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2), watermarkEstimator.getState());
// Handle the case if the clock ever goes backwards. Could happen if we resumed processing
// on a machine that had misconfigured clock or due to clock skew.
DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1).getMillis());
assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2), watermarkEstimator.currentWatermark());
}
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
// overridden as superclass algorithm can't handle
// 2004-02-29 + 48 months -> 2008-02-29 type dates
if (valueToAdd == 0) {
return values;
}
if (DateTimeUtils.isContiguous(partial)) {
long instant = 0L;
for (int i = 0, isize = partial.size(); i < isize; i++) {
instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]);
}
instant = add(instant, valueToAdd);
return GJChronology.this.get(partial, instant);
} else {
return super.add(partial, fieldIndex, values, valueToAdd);
}
}
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
// overridden as superclass algorithm can't handle
// 2004-02-29 + 48 months -> 2008-02-29 type dates
if (valueToAdd == 0) {
return values;
}
if (DateTimeUtils.isContiguous(partial)) {
long instant = 0L;
for (int i = 0, isize = partial.size(); i < isize; i++) {
instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]);
}
instant = add(instant, valueToAdd);
return GJChronology.this.get(partial, instant);
} else {
return super.add(partial, fieldIndex, values, valueToAdd);
}
}
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
// overridden as superclass algorithm can't handle
// 2004-02-29 + 48 months -> 2008-02-29 type dates
if (valueToAdd == 0) {
return values;
}
if (DateTimeUtils.isContiguous(partial)) {
long instant = 0L;
for (int i = 0, isize = partial.size(); i < isize; i++) {
instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]);
}
instant = add(instant, valueToAdd);
return GJChronology.this.get(partial, instant);
} else {
return super.add(partial, fieldIndex, values, valueToAdd);
}
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
/**
* Creates a new period based on another using the {@link ConverterManager}.
*
* @param period the period to convert
* @param type which set of fields this period supports, null means use type from object
* @param chrono the chronology to use, null means ISO default
* @throws IllegalArgumentException if period is invalid
* @throws IllegalArgumentException if an unsupported field's value is non-zero
*/
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
super();
PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
type = (type == null ? converter.getPeriodType(period) : type);
type = checkPeriodType(type);
iType = type;
if (this instanceof ReadWritablePeriod) {
iValues = new int[size()];
chrono = DateTimeUtils.getChronology(chrono);
converter.setInto((ReadWritablePeriod) this, period, chrono);
} else {
iValues = new MutablePeriod(period, type, chrono).getValues();
}
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
@Before
public void setUp() throws Exception {
// Init zone info
Context context = InstrumentationRegistry.getInstrumentation().getContext();
JodaTimeAndroid.init(context);
// Force the system into 24-hour time for tests
ContentResolver cr = context.getContentResolver();
mOldTime1224Setting = Settings.System.getString(cr, Settings.System.TIME_12_24);
Settings.System.putString(cr, Settings.System.TIME_12_24, "24");
// Force all tests to be in the US locale; that way we can test output in consistent manner
Application app = (Application) ApplicationProvider.getApplicationContext();
Resources res = app.getBaseContext().getResources();
Configuration config = res.getConfiguration();
Locale.setDefault(Locale.US);
config.locale = Locale.US;
res.updateConfiguration(config, res.getDisplayMetrics());
// Force the default timezone
mDefaultJodaTz = DateTimeZone.forID("America/New_York");
mOldDefaultJodaTz = DateTimeZone.getDefault();
DateTimeZone.setDefault(mDefaultJodaTz);
// ...And for the system as well
mDefaultSystemTz = TimeZone.getTimeZone("America/Chicago");
mOldDefaultSystemTz = TimeZone.getDefault();
TimeZone.setDefault(mDefaultSystemTz);
// Force current "now" time, so all tests can be consistent
mNow = new DateTime(YEAR, MONTH_OF_YEAR, DAY_OF_MONTH, HOUR_OF_DAY,
MINUTE_OF_HOUR, SECOND_OF_MINUTE, MILLIS_OF_SECOND, mDefaultJodaTz);
DateTimeUtils.setCurrentMillisFixed(mNow.getMillis());
}
/**
* Determines the correct chronology to use.
*
* @param chrono the proposed chronology
* @return the actual chronology
*/
private Chronology selectChronology(Chronology chrono) {
chrono = DateTimeUtils.getChronology(chrono);
if (iChrono != null) {
chrono = iChrono;
}
if (iZone != null) {
chrono = chrono.withZone(iZone);
}
return chrono;
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
@Test
public void should_generate_feed() throws IOException {
DefaultEnvironment env = new DefaultEnvironment(new EnvironmentType("mamute"));
QuestionRssEntryFactory factory = new QuestionRssEntryFactory(env);
RssFeedFactory rssFeedFactory = new RssFeedFactory(env, factory);
QuestionBuilder builder = new QuestionBuilder();
DateTimeUtils.setCurrentMillisFixed(100);
User user1 = user("author1", "[email protected]");
user1.setPhotoUri(new URL("http://imagemsuser1.com"));
Question question1 = builder.withAuthor(user1)
.withTitle("first question")
.withDescription("question")
.withId(1l)
.build();
User user2 = user("author2", "[email protected]");
user2.setPhotoUri(new URL("http://imagemsuser2.com"));
Question question2 = builder.withId(2l)
.withTitle("second question")
.withAuthor(user2)
.build();
ByteArrayOutputStream output = new ByteArrayOutputStream();
rssFeedFactory.build(Arrays.<RssContent>asList(question1, question2), output, "title", "description");
output.close();
String xml = new String(output.toByteArray());
assertTrue(xml.contains("first question"));
assertTrue(xml.contains("second question"));
assertTrue(xml.contains("http://imagemsuser1.com"));
assertTrue(xml.contains("http://imagemsuser2.com"));
DateTimeUtils.setCurrentMillisSystem();
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
DateTimeUtils.setCurrentMillisFixed(0L);
when(codePipelineClient.getJobDetails(any(GetJobDetailsRequest.class))).thenReturn(getJobDetailsResult);
when(getJobDetailsResult.getJobDetails()).thenReturn(jobDetails);
when(jobDetails.getData()).thenReturn(jobData);
when(jobData.getArtifactCredentials()).thenReturn(JOB_CREDENTIALS);
credentialsProvider = new AWSCodePipelineJobCredentialsProvider(JOB_ID, codePipelineClient);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
/**
* Determines the correct chronology to use.
*
* @param chrono the proposed chronology
* @return the actual chronology
*/
private Chronology selectChronology(Chronology chrono) {
chrono = DateTimeUtils.getChronology(chrono);
if (iChrono != null) {
chrono = iChrono;
}
if (iZone != null) {
chrono = chrono.withZone(iZone);
}
return chrono;
}
@Test
public void selectCurrentTimestamp() throws Exception {
long before = DateTimeUtils.currentTimeMillis();
SQLResponse response = execute("select current_timestamp from sys.cluster");
long after = DateTimeUtils.currentTimeMillis();
assertThat(response.cols(), arrayContaining("current_timestamp(3)"));
assertThat((long) response.rows()[0][0], allOf(greaterThanOrEqualTo(before), lessThanOrEqualTo(after)));
}
/**
* Determines the correct chronology to use.
*
* @param chrono the proposed chronology
* @return the actual chronology
*/
private Chronology selectChronology(Chronology chrono) {
chrono = DateTimeUtils.getChronology(chrono);
if (iChrono != null) {
chrono = iChrono;
}
if (iZone != null) {
chrono = chrono.withZone(iZone);
}
return chrono;
}
/**
* Constructs a bucket, with the option of specifying the pivot year for
* two-digit year parsing.
*
* @param instantLocal the initial millis from 1970-01-01T00:00:00, local time
* @param chrono the chronology to use
* @param locale the locale to use
* @param pivotYear the pivot year to use when parsing two-digit years
* @since 2.0
*/
public DateTimeParserBucket(long instantLocal, Chronology chrono,
Locale locale, Integer pivotYear, int defaultYear) {
super();
chrono = DateTimeUtils.getChronology(chrono);
iMillis = instantLocal;
iZone = chrono.getZone();
iChrono = chrono.withUTC();
iLocale = (locale == null ? Locale.getDefault() : locale);
iPivotYear = pivotYear;
iDefaultYear = defaultYear;
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
f = new DateTimeFormatterBuilder()
.appendDayOfWeekShortText()
.appendLiteral(' ')
.append(ISODateTimeFormat.dateTimeNoMillis())
.toFormatter();
g = ISODateTimeFormat.dateTimeNoMillis();
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(DateTimeZone.forID("Europe/London"));
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
ISO = ISOChronology.getInstance();
JULIAN = JulianChronology.getInstance();
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(UK);
}
/**
* Constructs an interval from a start and end instant.
*
* @param start start of this interval, null means now
* @param end end of this interval, null means now
* @throws IllegalArgumentException if the end is before the start
*/
protected BaseInterval(ReadableInstant start, ReadableInstant end) {
super();
if (start == null && end == null) {
iStartMillis = iEndMillis = DateTimeUtils.currentTimeMillis();
iChronology = ISOChronology.getInstance();
} else {
iChronology = DateTimeUtils.getInstantChronology(start);
iStartMillis = DateTimeUtils.getInstantMillis(start);
iEndMillis = DateTimeUtils.getInstantMillis(end);
checkInterval(iStartMillis, iEndMillis);
}
}
/**
* CQL-based import requires us to provide list of values we want to insert (it it's
* smart enough to figure everything else automatically). So, we convert each input
* row into a list of values, and wrap all of them in CQLRecord.
*
* @param inputRow byte representation of the input row as it was read from Avro file
* @return wraps the record into something that blends nicely into Crunch
*/
@Override
public CQLRecord map(ByteBuffer inputRow) {
LegacyInputFormat row = LegacyInputFormat.parse(inputRow);
long ts = Objects.firstNonNull(row.getTimestamp(), DateTimeUtils.currentTimeMillis());
int ttl = Objects.firstNonNull(row.getTtl(), 0l).intValue();
CharSequence key = row.getRowkey();
List values = Lists.newArrayList(key, row.getColname(), row.getColval());
return CQLRecord.create(key, ts, ttl, values);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}