下面列出了怎么用org.joda.time.PeriodType的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testBaselineAggregateComputeMultiIndex() {
BaselineAggregate baseline = BaselineAggregate.fromOffsets(BaselineAggregateType.MEDIAN, makePeriods(PeriodType.millis(), -1200L, -4500L), DateTimeZone.UTC);
Map<MetricSlice, DataFrame> data = new HashMap<>();
data.put(BASE_SLICE.withStart(13800).withEnd(15800),
new DataFrame()
.addSeries(COL_TIME, LongSeries.buildFrom(13800L, 13800L, 14300L, 14300L, 14800L, 14800L, 15300L, 15300L))
.addSeries("string", StringSeries.buildFrom("A", "B", "A", "B", "A", "B", "A", "B"))
.addSeries(COL_VALUE, 400d, 4000d, 500d, 5000d, 600d, 6000d, 700d, 7000d)
.setIndex(COL_TIME, "string")
);
data.put(BASE_SLICE.withStart(10500).withEnd(12500),
new DataFrame()
.addSeries(COL_TIME, LongSeries.buildFrom(10500L, 11000L, 11500L, 12000L, 10500, 11000L, 11500L, 12000L))
.addSeries("string", StringSeries.buildFrom("A", "A", "A", "A", "B", "B", "B", "B"))
.addSeries(COL_VALUE, 500d, 600d, 700d, 800d, 5000d, 6000d, 7000d, 8000d)
.setIndex(COL_TIME, "string")
);
DataFrame result = baseline.gather(BASE_SLICE, data).sortedBy("string", COL_TIME);
assertEquals(result.getLongs(COL_TIME), 15000L, 15500L, 16000L, 16500L, 15000L, 15500L, 16000L, 16500L);
assertEquals(result.getStrings("string"), "A", "A", "A", "A", "B", "B", "B", "B");
assertEquals(result.getDoubles(COL_VALUE), 450d, 550d, 650d, 750d, 4500d, 5500d, 6500d, 7500d);
}
private Bitmap getIconFromMinutes(Times t) {
int left = new Period(LocalDateTime.now(), t.getTime(LocalDate.now(), t.getNextTime()), PeriodType.minutes()).getMinutes();
Resources r = getContext().getResources();
int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, r.getDisplayMetrics());
Bitmap b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(0xFFFFFFFF);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(size);
paint.setTextSize(size * size / paint.measureText((left < 10 ? left * 10 : left) + ""));
float yPos = c.getHeight() / 2f - (paint.descent() + paint.ascent()) / 2;
c.drawText(left + "", size / 2f, yPos, paint);
return b;
}
public boolean isKerahat() {
LocalDateTime now = LocalDateTime.now();
int untilSun = new Period(getTime(now.toLocalDate(), Vakit.SUN.ordinal()), now, PeriodType.minutes()).getMinutes();
if (untilSun >= 0 && untilSun < Preferences.KERAHAT_SUNRISE.get()) {
return true;
}
int untilDhuhr = new Period(now, getTime(now.toLocalDate(), Vakit.DHUHR.ordinal()), PeriodType.minutes()).getMinutes();
if ((untilDhuhr >= 0) && (untilDhuhr < (Preferences.KERAHAT_ISTIWA.get()))) {
return true;
}
int untilMaghrib = new Period(now, getTime(now.toLocalDate(), Vakit.MAGHRIB.ordinal()), PeriodType.minutes()).getMinutes();
return (untilMaghrib >= 0) && (untilMaghrib < (Preferences.KERAHAT_SUNSET.get()));
}
private Bitmap getIconFromMinutes(Times t) {
int left = new Period(LocalDateTime.now(), t.getTime(LocalDate.now(), t.getNextTime()), PeriodType.minutes()).getMinutes();
Resources r = getContext().getResources();
int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, r.getDisplayMetrics());
Bitmap b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(0xFFFFFFFF);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(size);
paint.setTextSize(size * size / paint.measureText((left < 10 ? left * 10 : left) + ""));
float yPos = c.getHeight() / 2f - (paint.descent() + paint.ascent()) / 2;
c.drawText(left + "", size / 2f, yPos, paint);
return b;
}
/**
* Format the duration in milliseconds to a human readable String, with "yr", "days", "hr" etc prefixes
*
*
* @param durationMs Duration in milliseconds
* @return Human readable string
*/
public static String formatDuration(long durationMs){
Period period = Period.seconds((int)(durationMs/1000L));
Period p2 = period.normalizedStandard(PeriodType.yearMonthDayTime());
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears()
.appendSuffix(" yr ")
.appendMonths()
.appendSuffix(" months ")
.appendDays()
.appendSuffix(" days ")
.appendHours()
.appendSuffix(" hr ")
.appendMinutes()
.appendSuffix(" min ")
.appendSeconds()
.appendSuffix(" sec")
.toFormatter();
return formatter.print(p2);
}
boolean isSupported(PeriodType type, int field) {
switch (field) {
default:
return false;
case YEARS:
return type.isSupported(DurationFieldType.years());
case MONTHS:
return type.isSupported(DurationFieldType.months());
case WEEKS:
return type.isSupported(DurationFieldType.weeks());
case DAYS:
return type.isSupported(DurationFieldType.days());
case HOURS:
return type.isSupported(DurationFieldType.hours());
case MINUTES:
return type.isSupported(DurationFieldType.minutes());
case SECONDS:
return type.isSupported(DurationFieldType.seconds());
case MILLIS:
return type.isSupported(DurationFieldType.millis());
case SECONDS_MILLIS: // drop through
case SECONDS_OPTIONAL_MILLIS:
return type.isSupported(DurationFieldType.seconds()) ||
type.isSupported(DurationFieldType.millis());
}
}
boolean isSupported(PeriodType type, int field) {
switch (field) {
default:
return false;
case YEARS:
return type.isSupported(DurationFieldType.years());
case MONTHS:
return type.isSupported(DurationFieldType.months());
case WEEKS:
return type.isSupported(DurationFieldType.weeks());
case DAYS:
return type.isSupported(DurationFieldType.days());
case HOURS:
return type.isSupported(DurationFieldType.hours());
case MINUTES:
return type.isSupported(DurationFieldType.minutes());
case SECONDS:
return type.isSupported(DurationFieldType.seconds());
case MILLIS:
return type.isSupported(DurationFieldType.millis());
case SECONDS_MILLIS: // drop through
case SECONDS_OPTIONAL_MILLIS:
return type.isSupported(DurationFieldType.seconds()) ||
type.isSupported(DurationFieldType.millis());
}
}
boolean isSupported(PeriodType type, int field) {
switch (field) {
default:
return false;
case YEARS:
return type.isSupported(DurationFieldType.years());
case MONTHS:
return type.isSupported(DurationFieldType.months());
case WEEKS:
return type.isSupported(DurationFieldType.weeks());
case DAYS:
return type.isSupported(DurationFieldType.days());
case HOURS:
return type.isSupported(DurationFieldType.hours());
case MINUTES:
return type.isSupported(DurationFieldType.minutes());
case SECONDS:
return type.isSupported(DurationFieldType.seconds());
case MILLIS:
return type.isSupported(DurationFieldType.millis());
case SECONDS_MILLIS: // drop through
case SECONDS_OPTIONAL_MILLIS:
return type.isSupported(DurationFieldType.seconds()) ||
type.isSupported(DurationFieldType.millis());
}
}
@Override
public String toNonNullValue(Period value) {
final String periodString;
if (STANDARD.equals(value.getPeriodType())) {
periodString = value.toString();
} else {
if (PeriodType.class.equals(value.getPeriodType().getClass())) {
periodString = value.toString() + "{" + value.getPeriodType().getName() + "}";
} else {
throw new IllegalArgumentException("Subclasses of PeriodType are unsupported");
}
}
return periodString;
}
/**
* Helper for parsing a period string from config (e.g. '3 days', '1min', '3600000')
*
* @param period
* @return
*/
public static Period parsePeriod(String period) {
Matcher m = PATTERN_PERIOD.matcher(period);
if (!m.find()) {
throw new IllegalArgumentException(String.format("Could not parse period expression '%s'", period));
}
int size = Integer.valueOf(m.group(1).trim());
PeriodType t = PeriodType.millis();
if (m.group(2).length() > 0) {
t = parsePeriodType(m.group(2).trim());
}
return new Period().withFieldAdded(t.getFieldType(0), size);
}
boolean isSupported(PeriodType type, int field) {
switch (field) {
default:
return false;
case YEARS:
return type.isSupported(DurationFieldType.years());
case MONTHS:
return type.isSupported(DurationFieldType.months());
case WEEKS:
return type.isSupported(DurationFieldType.weeks());
case DAYS:
return type.isSupported(DurationFieldType.days());
case HOURS:
return type.isSupported(DurationFieldType.hours());
case MINUTES:
return type.isSupported(DurationFieldType.minutes());
case SECONDS:
return type.isSupported(DurationFieldType.seconds());
case MILLIS:
return type.isSupported(DurationFieldType.millis());
case SECONDS_MILLIS: // drop through
case SECONDS_OPTIONAL_MILLIS:
return type.isSupported(DurationFieldType.seconds()) ||
type.isSupported(DurationFieldType.millis());
}
}
@MemberOrder(name = "breakDate", sequence = "1")
public BreakOption changeDates(
final LocalDate breakDate,
final LocalDate excerciseDate) {
setBreakDate(breakDate);
setExerciseDate(excerciseDate);
LocalDateInterval ldi = new LocalDateInterval(excerciseDate, breakDate, AbstractInterval.IntervalEnding.EXCLUDING_END_DATE);
final String s = JodaPeriodUtils.asSimpleString(new Period(ldi.asInterval(), PeriodType.yearMonthDay()));
setNotificationPeriod(s);
// re-create events
removeExistingEvents();
createEvents();
return this;
}
boolean isSupported(PeriodType type, int field) {
switch (field) {
default:
return false;
case YEARS:
return type.isSupported(DurationFieldType.years());
case MONTHS:
return type.isSupported(DurationFieldType.months());
case WEEKS:
return type.isSupported(DurationFieldType.weeks());
case DAYS:
return type.isSupported(DurationFieldType.days());
case HOURS:
return type.isSupported(DurationFieldType.hours());
case MINUTES:
return type.isSupported(DurationFieldType.minutes());
case SECONDS:
return type.isSupported(DurationFieldType.seconds());
case MILLIS:
return type.isSupported(DurationFieldType.millis());
case SECONDS_MILLIS: // drop through
case SECONDS_OPTIONAL_MILLIS:
return type.isSupported(DurationFieldType.seconds()) ||
type.isSupported(DurationFieldType.millis());
}
}
public void testSetInto_Object() throws Exception {
MutablePeriod m = new MutablePeriod(PeriodType.yearMonthDayTime());
ReadablePeriodConverter.INSTANCE.setInto(m, new Period(0, 0, 0, 3, 0, 4, 0, 5), null);
assertEquals(0, m.getYears());
assertEquals(0, m.getMonths());
assertEquals(0, m.getWeeks());
assertEquals(3, m.getDays());
assertEquals(0, m.getHours());
assertEquals(4, m.getMinutes());
assertEquals(0, m.getSeconds());
assertEquals(5, m.getMillis());
}
/**
* Constructor.
*
* @param printer the internal printer, null if cannot print
* @param parser the internal parser, null if cannot parse
* @param locale the locale to use
* @param type the parse period type
*/
private PeriodFormatter(
PeriodPrinter printer, PeriodParser parser,
Locale locale, PeriodType type) {
super();
iPrinter = printer;
iParser = parser;
iLocale = locale;
iParseType = type;
}
public void testParsePeriod_parseType() {
Period expect = new Period(0, 0, 0, 4, 5, 6, 7, 8, PeriodType.dayTime());
assertEquals(expect, f.withParseType(PeriodType.dayTime()).parsePeriod("P4DT5H6M7.008S"));
try {
f.withParseType(PeriodType.dayTime()).parsePeriod("P3W4DT5H6M7.008S");
fail();
} catch (IllegalArgumentException ex) {}
}
public void testSetIntoPeriod_Object5() throws Exception {
MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime());
StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M56.S", null);
assertEquals(2, m.getYears());
assertEquals(4, m.getWeeks());
assertEquals(3, m.getDays());
assertEquals(12, m.getHours());
assertEquals(24, m.getMinutes());
assertEquals(56, m.getSeconds());
assertEquals(0, m.getMillis());
}
/**
* Returns an instance of BaselineAggregate for the specified type and offsets
*
* @see BaselineAggregateType
*
* @param type aggregation type
* @param offsets time offsets
* @return BaselineAggregate with given type and offsets
*/
public static BaselineAggregate fromOffsets(BaselineAggregateType type, List<Period> offsets, DateTimeZone timeZone) {
if (offsets.isEmpty()) {
throw new IllegalArgumentException("Must provide at least one offset");
}
PeriodType periodType = offsets.get(0).getPeriodType();
for (Period p : offsets) {
if (!periodType.equals(p.getPeriodType())) {
throw new IllegalArgumentException(String.format("Expected uniform period type but found '%s' and '%s'", periodType, p.getPeriodType()));
}
}
return new BaselineAggregate(type, offsets, timeZone, periodType);
}
public void testSetIntoPeriod_Object7() throws Exception {
MutablePeriod m = new MutablePeriod(1, 0, 1, 1, 1, 1, 1, 1, PeriodType.yearWeekDayTime());
StringConverter.INSTANCE.setInto(m, "P2Y4W3D", null);
assertEquals(2, m.getYears());
assertEquals(4, m.getWeeks());
assertEquals(3, m.getDays());
assertEquals(0, m.getHours());
assertEquals(0, m.getMinutes());
assertEquals(0, m.getSeconds());
assertEquals(0, m.getMillis());
}
/**
* Creates a period from the given interval endpoints.
*
* @param startInstant interval start, null means now
* @param endInstant interval end, null means now
* @param type which set of fields this period supports, null means standard
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
if (startInstant == null && endInstant == null) {
iType = type;
iValues = new int[size()];
} else {
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
}
/**
* 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();
}
}
public void testSetIntoPeriod_Object1() throws Exception {
Interval i = new Interval(100L, 223L);
MutablePeriod m = new MutablePeriod(PeriodType.millis());
ReadableIntervalConverter.INSTANCE.setInto(m, i, null);
assertEquals(0, m.getYears());
assertEquals(0, m.getMonths());
assertEquals(0, m.getWeeks());
assertEquals(0, m.getDays());
assertEquals(0, m.getHours());
assertEquals(0, m.getMinutes());
assertEquals(0, m.getSeconds());
assertEquals(123, m.getMillis());
}
public void testSetIntoPeriod_Object3() throws Exception {
MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime());
StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48.034S", null);
assertEquals(2, m.getYears());
assertEquals(4, m.getWeeks());
assertEquals(3, m.getDays());
assertEquals(12, m.getHours());
assertEquals(24, m.getMinutes());
assertEquals(48, m.getSeconds());
assertEquals(34, m.getMillis());
}
/**
* Creates a period from the given start point and duration.
*
* @param startInstant the interval start, null means now
* @param duration the duration of the interval, null means zero-length
* @param type which set of fields this period supports, null means standard
*/
protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) {
super();
type = checkPeriodType(type);
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long durationMillis = DateTimeUtils.getDurationMillis(duration);
long endMillis = FieldUtils.safeAdd(startMillis, durationMillis);
Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
/**
* 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();
}
}
public void testSetIntoPeriod_Object3() throws Exception {
MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime());
StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48.034S", null);
assertEquals(2, m.getYears());
assertEquals(4, m.getWeeks());
assertEquals(3, m.getDays());
assertEquals(12, m.getHours());
assertEquals(24, m.getMinutes());
assertEquals(48, m.getSeconds());
assertEquals(34, m.getMillis());
}
@Test
public void testBaselineAggregateFrom() {
BaselineAggregate baseline = BaselineAggregate.fromOffsets(BaselineAggregateType.MEDIAN, makePeriods(PeriodType.millis(), -1200L, -4500L), DateTimeZone.UTC);
List<MetricSlice> slices = baseline.scatter(BASE_SLICE);
Assert.assertEquals(slices.size(), 2);
Assert.assertEquals(slices.get(0).getMetricId(), 12345);
Assert.assertEquals(slices.get(0).getStart(), 13800);
Assert.assertEquals(slices.get(0).getEnd(), 15800);
Assert.assertEquals(slices.get(1).getMetricId(), 12345);
Assert.assertEquals(slices.get(1).getStart(), 10500);
Assert.assertEquals(slices.get(1).getEnd(), 12500);
}
public void testWithGetParseTypeMethods() {
PeriodFormatter f2 = f.withParseType(PeriodType.dayTime());
assertEquals(PeriodType.dayTime(), f2.getParseType());
assertSame(f2, f2.withParseType(PeriodType.dayTime()));
f2 = f.withParseType(null);
assertEquals(null, f2.getParseType());
assertSame(f2, f2.withParseType(null));
}
private DurationFieldType[] getDurationFieldTypes() {
List<DurationFieldType> result = new ArrayList<DurationFieldType>();
if (getIncludedFields() == null) {
result.add(DurationFieldType.hours());
result.add(DurationFieldType.minutes());
} else {
PeriodType standard = PeriodType.standard();
for (int index = 0; index < standard.size(); index++) {
if (getIncludedFields().contains(standard.getFieldType(index).getName())) {
result.add(standard.getFieldType(index));
}
}
}
return result.toArray(new DurationFieldType[] {});
}
/**
* Creates a period from the given interval endpoints.
*
* @param startInstant interval start, null means now
* @param endInstant interval end, null means now
* @param type which set of fields this period supports, null means standard
* @throws IllegalArgumentException if period type is invalid
*/
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
super();
type = checkPeriodType(type);
if (startInstant == null && endInstant == null) {
iType = type;
iValues = new int[size()];
} else {
long startMillis = DateTimeUtils.getInstantMillis(startInstant);
long endMillis = DateTimeUtils.getInstantMillis(endInstant);
Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
iType = type;
iValues = chrono.get(this, startMillis, endMillis);
}
}