Java Examples for org.joda.time.format.PeriodFormatter
The following java examples will help you to understand the usage of org.joda.time.format.PeriodFormatter. These source code samples are taken from different open source projects.
Example 1
Project: humanize-master File: TestJodaTime.java View source code |
@Test
public void periodFormat() {
PeriodFormatter fmt = PeriodFormat.getDefault();
Assert.assertEquals(new Period(0, 100000000).toString(fmt), "1 day, 3 hours, 46 minutes and 40 seconds");
fmt = PeriodFormat.wordBased(new Locale("es"));
Assert.assertEquals(new Period(0, 100000000).toString(fmt), "1 dÃa, 3 horas, 46 minutos y 40 segundos");
fmt = ISOPeriodFormat.standard();
Assert.assertEquals(new Period(0, 100000000).toString(fmt), "P1DT3H46M40S");
fmt = ISOPeriodFormat.alternate();
Assert.assertEquals(new Period(0, 100000000).toString(fmt), "P00000001T034640");
fmt = ISOPeriodFormat.alternateWithWeeks();
Assert.assertEquals(new Period(0, 100000000).toString(fmt), "P0000W0001T034640");
}
Example 2
Project: gobblin-master File: TimeBasedSubDirDatasetsFinder.java View source code |
/**
* Return true iff input folder time is between compaction.timebased.min.time.ago and
* compaction.timebased.max.time.ago.
*/
protected boolean folderWithinAllowedPeriod(Path inputFolder, DateTime folderTime) {
DateTime currentTime = new DateTime(this.timeZone);
PeriodFormatter periodFormatter = getPeriodFormatter();
DateTime earliestAllowedFolderTime = getEarliestAllowedFolderTime(currentTime, periodFormatter);
DateTime latestAllowedFolderTime = getLatestAllowedFolderTime(currentTime, periodFormatter);
if (folderTime.isBefore(earliestAllowedFolderTime)) {
log.info(String.format("Folder time for %s is %s, earlier than the earliest allowed folder time, %s. Skipping", inputFolder, folderTime, earliestAllowedFolderTime));
return false;
} else if (folderTime.isAfter(latestAllowedFolderTime)) {
log.info(String.format("Folder time for %s is %s, later than the latest allowed folder time, %s. Skipping", inputFolder, folderTime, latestAllowedFolderTime));
return false;
} else {
return true;
}
}
Example 3
Project: jerseyoauth2-master File: WebAppConfiguration.java View source code |
private Duration parseDuration(String initParameter, Duration defaultDuration) {
if (initParameter != null) {
PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d ").appendHours().appendSuffix("h ").appendMinutes().appendSuffix("min").toFormatter();
Period p = formatter.parsePeriod(initParameter);
return p.toDurationFrom(DateTime.now());
} else
return defaultDuration;
}
Example 4
Project: solarnetwork-common-master File: JodaPeriodFormatEditor.java View source code |
@Override
public String getAsText() {
Object val = getValue();
if (val == null) {
return null;
}
PeriodFormatter format = this.periodFormatters[0];
if (val instanceof ReadablePeriod) {
return format.print((ReadablePeriod) val);
}
throw new IllegalArgumentException("Unsupported period object [" + val.getClass() + "]: " + val);
}
Example 5
Project: cloudhopper-commons-master File: UptimeMain.java View source code |
public static void main(String[] args) {
//Period period = new Period(uptime, PeriodType.standard().withYearsRemoved().withWeeksRemoved().withMonthsRemoved().withMillisRemoved());
//MutablePeriod period = new Duration(uptime).toPeriod().toMutablePeriod();
long uptime = UPTIME_56_SECS;
// ah, ha -- this is super important -- need to normalize the period!
PeriodType periodType = PeriodType.standard().withYearsRemoved().withMonthsRemoved().withWeeksRemoved().withMillisRemoved();
Period period = new Period(uptime).normalizedStandard(periodType);
System.out.println("Uptime: " + uptime + " ms");
System.out.println("Weeks: " + period.getWeeks());
System.out.println("Days: " + period.getDays());
System.out.println("Millis: " + period.getMillis() + " ms");
// print out the uptime
String uptimeStyleString = PeriodFormatterUtil.getStandardUptimeStyle().print(period);
String linuxStyleString = PeriodFormatterUtil.getLinuxUptimeStyle().print(period);
System.out.println(uptimeStyleString);
System.out.println(linuxStyleString);
PeriodFormatter fmt = new PeriodFormatterBuilder().printZeroNever().appendDays().appendSuffix(" day ", " days ").appendHours().appendSuffix(" hours ").appendMinutes().appendSuffix(" mins ").printZeroAlways().appendSeconds().appendSuffix(" secs ").toFormatter();
String str0 = fmt.print(period);
System.out.println(str0);
String str1 = PeriodFormat.getDefault().print(period);
System.out.println(str1);
}
Example 6
Project: epicsarchiverap-master File: InstanceReport.java View source code |
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, ConfigService configService) throws IOException {
logger.info("Generating Instance report");
resp.setContentType(MimeTypeConstants.APPLICATION_JSON);
try (PrintWriter out = resp.getWriter()) {
LinkedList<Map<String, String>> result = new LinkedList<Map<String, String>>();
for (ApplianceInfo info : configService.getAppliancesInCluster()) {
HashMap<String, String> applianceInfo = new HashMap<String, String>();
result.add(applianceInfo);
applianceInfo.put("instance", info.getIdentity());
int pvCount = 0;
for (@SuppressWarnings("unused") String pvName : configService.getPVsForThisAppliance()) {
pvCount++;
}
applianceInfo.put("pvCount", Integer.toString(pvCount));
// The getApplianceMetrics here is not a typo. We redisplay some of the appliance metrics in this page.
JSONObject engineMetrics = GetUrlContent.getURLContentAsJSONObject(info.getEngineURL() + "/getApplianceMetrics");
JSONObject etlMetrics = GetUrlContent.getURLContentAsJSONObject(info.getEtlURL() + "/getApplianceMetrics");
JSONObject retrievalMetrics = GetUrlContent.getURLContentAsJSONObject(info.getRetrievalURL() + "/getApplianceMetrics");
if (engineMetrics != null && etlMetrics != null && retrievalMetrics != null) {
logger.debug("All of the components are working for " + info.getIdentity());
applianceInfo.put("status", "Working");
} else {
logger.debug("At least one of the components is not working for " + info.getIdentity());
StringWriter buf = new StringWriter();
buf.append("Stopped - ");
if (engineMetrics == null)
buf.append("engine ");
if (etlMetrics == null)
buf.append("ETL ");
if (retrievalMetrics == null)
buf.append("retrieval ");
applianceInfo.put("status", buf.toString());
}
GetUrlContent.combineJSONObjects(applianceInfo, engineMetrics);
GetUrlContent.combineJSONObjects(applianceInfo, etlMetrics);
GetUrlContent.combineJSONObjects(applianceInfo, retrievalMetrics);
long vmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
Period vmInterval = new Period(vmStartTime, System.currentTimeMillis(), PeriodType.yearMonthDayTime());
PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever().appendYears().appendSuffix(" year", " years").appendMonths().appendSuffix(" month", " months").appendDays().appendSuffix(" day", " days").appendSeparator(" ").printZeroAlways().appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
applianceInfo.put("MGMT_uptime", formatter.print(new Period(vmInterval)));
applianceInfo.put("errors", Integer.toString(0));
applianceInfo.put("capacityUtilized", "N/A");
}
out.println(JSONValue.toJSONString(result));
}
}
Example 7
Project: ho.la.urv-master File: ReportActivity.java View source code |
private void refresh(Evalos eva) {
PeriodFormatter HHMMFormater = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2).appendHours().appendSeparator(":").appendMinutes().toFormatter();
long accumulatedBalance = 0;
// Fill Monday
mReportTableMondayTheoretical.setText(eva.getDay(Day.MONDAY).getShiftDisplay());
if (Day.today() >= Day.MONDAY) {
Period mondayReal = eva.getDay(Day.MONDAY).getAccumulate();
if (mondayReal != null) {
mReportTableMondayReal.setText(HHMMFormater.print(mondayReal));
accumulatedBalance += eva.computeBalance(eva.getDay(Day.MONDAY).getShiftDisplay(), HHMMFormater.print(mondayReal));
mReportTableMondayBalance.setText(milisToDisplayTime(accumulatedBalance));
}
}
// Fill Tuesday
mReportTableTuesdayTheoretical.setText(eva.getDay(Day.TUESDAY).getShiftDisplay());
if (Day.today() >= Day.TUESDAY) {
Period tuesdayReal = eva.getDay(Day.TUESDAY).getAccumulate();
if (tuesdayReal != null) {
mReportTableTuesdayReal.setText(HHMMFormater.print(tuesdayReal));
accumulatedBalance += eva.computeBalance(eva.getDay(Day.TUESDAY).getShiftDisplay(), HHMMFormater.print(tuesdayReal));
mReportTableTuesdayBalance.setText(milisToDisplayTime(accumulatedBalance));
}
}
// Fill Wednesday
mReportTableWednesdayTheoretical.setText(eva.getDay(Day.WEDNESDAY).getShiftDisplay());
if (Day.today() >= Day.WEDNESDAY) {
Period wednesdayReal = eva.getDay(Day.WEDNESDAY).getAccumulate();
if (wednesdayReal != null) {
mReportTableWednesdayReal.setText(HHMMFormater.print(wednesdayReal));
accumulatedBalance += eva.computeBalance(eva.getDay(Day.WEDNESDAY).getShiftDisplay(), HHMMFormater.print(wednesdayReal));
mReportTableWednesdayBalance.setText(milisToDisplayTime(accumulatedBalance));
}
}
// Fill Thursday
mReportTableThursdayTheoretical.setText(eva.getDay(Day.THURSDAY).getShiftDisplay());
if (Day.today() >= Day.THURSDAY) {
Period thursdayReal = eva.getDay(Day.THURSDAY).getAccumulate();
if (thursdayReal != null) {
mReportTableThursdayReal.setText(HHMMFormater.print(thursdayReal));
accumulatedBalance += eva.computeBalance(eva.getDay(Day.THURSDAY).getShiftDisplay(), HHMMFormater.print(thursdayReal));
mReportTableThursdayBalance.setText(milisToDisplayTime(accumulatedBalance));
}
}
// Fill Friday
mReportTableFridayTheoretical.setText(eva.getDay(Day.FRIDAY).getShiftDisplay());
if (Day.today() >= Day.FRIDAY) {
Period fridayReal = eva.getDay(Day.FRIDAY).getAccumulate();
if (fridayReal != null) {
mReportTableFridayReal.setText(HHMMFormater.print(fridayReal));
accumulatedBalance += eva.computeBalance(eva.getDay(Day.FRIDAY).getShiftDisplay(), HHMMFormater.print(fridayReal));
mReportTableFridayBalance.setText(milisToDisplayTime(accumulatedBalance));
}
}
// Fill Saturday
mReportTableSaturdayTheoretical.setText(eva.getDay(Day.SATURDAY).getShiftDisplay());
if (Day.today() >= Day.SATURDAY) {
Period saturdayReal = eva.getDay(Day.SATURDAY).getAccumulate();
if (saturdayReal != null) {
mReportTableSaturdayReal.setText(HHMMFormater.print(saturdayReal));
accumulatedBalance += eva.computeBalance(eva.getDay(Day.SATURDAY).getShiftDisplay(), HHMMFormater.print(saturdayReal));
mReportTableSaturdayBalance.setText(milisToDisplayTime(accumulatedBalance));
}
}
// Fill Sunday
mReportTableSundayTheoretical.setText(eva.getDay(Day.SUNDAY).getShiftDisplay());
if (Day.today() >= Day.SUNDAY) {
Period sundayReal = eva.getDay(Day.SUNDAY).getAccumulate();
if (sundayReal != null) {
mReportTableSundayReal.setText(HHMMFormater.print(sundayReal));
accumulatedBalance += eva.computeBalance(eva.getDay(Day.SUNDAY).getShiftDisplay(), HHMMFormater.print(sundayReal));
mReportTableSundayBalance.setText(milisToDisplayTime(accumulatedBalance));
}
}
}
Example 8
Project: molgenis-master File: ProgressImpl.java View source code |
@Override
public void success() {
jobExecution.setEndDate(new Date());
jobExecution.setStatus(SUCCESS);
jobExecution.setProgressInt(jobExecution.getProgressMax());
Duration yourDuration = Duration.millis(timeRunning());
Period period = yourDuration.toPeriod();
PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d ").appendMinutes().appendSuffix("m ").appendSeconds().appendSuffix("s ").appendMillis().appendSuffix("ms ").toFormatter();
String timeSpent = periodFormatter.print(period);
JOB_EXECUTION_LOG.info("Execution successful. Time spent: {}", timeSpent);
sendEmail(jobExecution.getSuccessEmail(), jobExecution.getType() + " job succeeded.", jobExecution.getLog());
update();
JobExecutionContext.unset();
}
Example 9
Project: RedReader-master File: RRTime.java View source code |
public static String formatDurationFrom(final Context context, final long startTime) {
final String space = " ";
final String comma = ",";
final String separator = comma + space;
final long endTime = utcCurrentTimeMillis();
final DateTime dateTime = new DateTime(endTime);
final DateTime localDateTime = dateTime.withZone(DateTimeZone.getDefault());
Period period = new Duration(startTime, endTime).toPeriodTo(localDateTime);
PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendYears().appendSuffix(space).appendSuffix(context.getString(R.string.time_year), context.getString(R.string.time_years)).appendSeparator(separator).appendMonths().appendSuffix(space).appendSuffix(context.getString(R.string.time_month), context.getString(R.string.time_months)).appendSeparator(separator).appendDays().appendSuffix(space).appendSuffix(context.getString(R.string.time_day), context.getString(R.string.time_days)).appendSeparator(separator).appendHours().appendSuffix(space).appendSuffix(context.getString(R.string.time_hour), context.getString(R.string.time_hours)).appendSeparator(separator).appendMinutes().appendSuffix(space).appendSuffix(context.getString(R.string.time_min), context.getString(R.string.time_mins)).appendSeparator(separator).appendSeconds().appendSuffix(space).appendSuffix(context.getString(R.string.time_sec), context.getString(R.string.time_secs)).appendSeparator(separator).appendMillis().appendSuffix(space).appendSuffix(context.getString(R.string.time_ms)).toFormatter();
String duration = periodFormatter.print(period.normalizedStandard(PeriodType.yearMonthDayTime()));
List<String> parts = Arrays.asList(duration.split(comma));
if (parts.size() >= 2) {
duration = parts.get(0) + comma + parts.get(1);
}
return String.format(context.getString(R.string.time_ago), duration);
}
Example 10
Project: spring-rest-server-master File: HeaderUtil.java View source code |
private Period getSessionMaxAge() {
String maxAge = environment.getRequiredProperty("auth.session.maxAge");
PeriodFormatter format = new PeriodFormatterBuilder().appendDays().appendSuffix("d", "d").printZeroRarelyFirst().appendHours().appendSuffix("h", "h").printZeroRarelyFirst().appendMinutes().appendSuffix("m", "m").toFormatter();
Period sessionMaxAge = format.parsePeriod(maxAge);
if (LOG.isDebugEnabled()) {
LOG.debug("Session maxAge is: " + formatIfNotZero(sessionMaxAge.getDays(), "days", "day") + formatIfNotZero(sessionMaxAge.getHours(), "hours", "hour") + formatIfNotZero(sessionMaxAge.getMinutes(), "minutes", "minute"));
}
return sessionMaxAge;
}
Example 11
Project: bennu-vaadin-master File: VaadinProxiesCodeGeneratorTask.java View source code |
@Override
public void execute() throws BuildException {
super.execute();
DateTime start = new DateTime();
final Properties properties = new MultiProperty();
try {
properties.load(new FileInputStream(buildDir.getAbsolutePath() + "/WEB-INF/classes/configuration.properties"));
File timestampFile = new File(srcBaseDir, "vaadin-timestamp");
long latestBuildTime = srcBaseDir != null ? srcBaseDir.lastModified() : 0;
boolean shouldCompile = false;
// final String preInitClassnames =
// properties.getProperty("pre.init.classnames");
// System.out.println("Pre-init class names: " + preInitClassnames);
// if (preInitClassnames != null) {
// final String[] classnames = preInitClassnames.split(",");
// for (final String classname : classnames) {
// if (classname != null && !classname.isEmpty()) {
// try {
// Class.forName(classname.trim());
// } catch (final ClassNotFoundException e) {
// throw new Error(e);
// }
// }
// }
// }
List<URL> domainModelURLs = new ArrayList<URL>();
for (FileSet fileset : filesets) {
if (fileset.getDir().exists()) {
DirectoryScanner scanner = fileset.getDirectoryScanner(getProject());
String[] includedFiles = scanner.getIncludedFiles();
for (String includedFile : includedFiles) {
String filePath = fileset.getDir().getAbsolutePath() + "/" + includedFile;
File file = new File(filePath);
boolean isModified = file.lastModified() > latestBuildTime;
// System.out.println(includedFile + " : " + (isModified
// ? "not up to date" : "up to date"));
domainModelURLs.add(new File(filePath).toURI().toURL());
shouldCompile = shouldCompile || isModified;
}
}
}
// first, get the domain model
DomainModel model = DomainModelParser.getDomainModel(domainModelURLs, false);
VaadinProxiesCodeGenerator generator = new VaadinProxiesCodeGenerator(model, srcBaseDir, vaadinSrcDir, packageSourceLocations);
generator.generate();
timestampFile.delete();
timestampFile.createNewFile();
// } else {
// System.out.println("All dml files are up to date, skipping generation");
// }
} catch (IOException e) {
throw new BuildException(e);
} catch (JClassAlreadyExistsException e) {
throw new BuildException(e);
}
Duration processingTime = new Duration(start, new DateTime());
PeriodFormatter formatter = new PeriodFormatterBuilder().appendMinutes().appendSuffix("m").appendSeconds().appendSuffix("s").toFormatter();
System.out.println("Vaadin Generation Took: " + formatter.print(processingTime.toPeriod()));
}
Example 12
Project: my-ministry-assistant-master File: Helper.java View source code |
public static String getMinuteDuration(Cursor cursor) {
SimpleDateFormat saveDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
Calendar start = Calendar.getInstance(Locale.getDefault());
Calendar end = Calendar.getInstance(Locale.getDefault());
Duration dur = new Duration(new DateTime(start), new DateTime(start));
Duration durchange = new Duration(new DateTime(start), new DateTime(start));
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
try {
start.setTime(saveDateFormat.parse(cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.DATE_START))));
} catch (Exception e) {
start = Calendar.getInstance(Locale.getDefault());
}
try {
end.setTime(saveDateFormat.parse(cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.DATE_END))));
} catch (Exception e) {
end = Calendar.getInstance(Locale.getDefault());
}
durchange = new Duration(new DateTime(start), new DateTime(end));
dur = dur.withDurationAdded(durchange, 1);
}
cursor.close();
PeriodFormatter retVal = new PeriodFormatterBuilder().printZeroAlways().appendMinutes().toFormatter();
return retVal.print(dur.toPeriod());
}
Example 13
Project: prissma-master File: ContextUnit.java View source code |
/**
* Retrieves the specified property value from the context unit.
* Used by GEO and TIME context units.
* @param prop
* @return
* @throws ContextUnitException
*/
public double getComplexCtxUnitProp(Property prop) throws ContextUnitException {
if (!instance.isResource())
throw new ContextUnitException();
if (this.type != CtxUnitType.GEO && this.type != CtxUnitType.TIME && instance.isResource())
throw new ContextUnitException();
else {
Statement stat = ((Resource) instance).getProperty(prop);
if (stat == null)
throw new ContextUnitException();
// TIME conversions
if (prop.equals(PrissmaProperties.pStart)) {
String timeStr = stat.getLiteral().getString();
DateTimeFormatter dtf = ISODateTimeFormat.timeParser();
// UTC by default
DateTime startTime = dtf.withZone(DateTimeZone.UTC).parseDateTime(timeStr);
long millis = startTime.getMillis();
long seconds = millis / 1000;
return seconds;
} else if (prop.equals(PrissmaProperties.pDuration)) {
String durationStr = stat.getLiteral().getString();
PeriodFormatter pf = ISOPeriodFormat.standard();
Period period = pf.parsePeriod(durationStr);
int seconds = period.toStandardSeconds().getSeconds();
return seconds;
}
return stat.getLiteral().getDouble();
}
}
Example 14
Project: BudgetForce2-master File: StringConverter.java View source code |
//-----------------------------------------------------------------------
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
Example 15
Project: csv2rdf4lod-automation-master File: StringConverter.java View source code |
//-----------------------------------------------------------------------
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
Example 16
Project: D-MARLA-master File: StringConverter.java View source code |
//-----------------------------------------------------------------------
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
Example 17
Project: fenixedu-ist-teacher-service-master File: DistributionTeacherServicesByCourseDTO.java View source code |
public String getDescription() {
StringBuilder finalString = new StringBuilder(teacherUsername);
finalString.append(" - ");
finalString.append(teacherName);
finalString.append(" - ");
PeriodFormatter periodFormatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2).appendHours().appendSuffix(":").appendMinutes().toFormatter();
finalString.append(periodFormatter.print(getTimeSpentByTeacher().toPeriod()));
return finalString.toString();
}
Example 18
Project: Ginkou-master File: StringConverter.java View source code |
//-----------------------------------------------------------------------
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
Example 19
Project: h2o-3-master File: PrettyPrint.java View source code |
public static String toAge(Date from, Date to) {
if (from == null || to == null)
return "N/A";
final Period period = new Period(from.getTime(), to.getTime());
DurationFieldType[] dtf = new ArrayList<DurationFieldType>() {
{
add(DurationFieldType.years());
add(DurationFieldType.months());
add(DurationFieldType.days());
if (period.getYears() == 0 && period.getMonths() == 0 && period.getDays() == 0) {
add(DurationFieldType.hours());
add(DurationFieldType.minutes());
}
}
}.toArray(new DurationFieldType[0]);
PeriodFormatter pf = PeriodFormat.getDefault();
return pf.print(period.normalizedStandard(PeriodType.forFields(dtf)));
}
Example 20
Project: jacclog-master File: AnalyzeLogEntriesShellCommand.java View source code |
private void analyzeEntries() {
if (service != null) {
final DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd");
final DateTime from = format.parseDateTime(this.from);
final DateTime to = (this.to != null) ? format.parseDateTime(this.to) : from.plusDays(1);
final Interval interval = new Interval(from, to);
final Period period = interval.toPeriod();
final StringBuffer buffer = new StringBuffer();
buffer.append("Analyse the log entries from '");
buffer.append(from.toString()).append('\'');
buffer.append(" to '").append(to);
// print the period
final String space = " ";
buffer.append("'. The period includes ");
final PeriodFormatter dateFormat = new PeriodFormatterBuilder().appendYears().appendSuffix(" year", " years").appendSeparator(space).appendMonths().appendSuffix(" month", " months").appendSeparator(space).appendWeeks().appendSuffix(" week", " weeks").appendSeparator(space).appendDays().appendSuffix(" day", " days").appendSeparator(space).appendHours().appendSuffix(" hour", " hours").appendSeparator(space).appendMinutes().appendSuffix(" minute", " minutes").appendSeparator(space).toFormatter();
dateFormat.printTo(buffer, period);
buffer.append('.');
System.out.println(buffer.toString());
final long maxResults = service.count(interval);
if (maxResults > 0) {
int maxCount = 0;
if (proceed(maxResults)) {
final long startTime = System.currentTimeMillis();
final LogEntryAnalysisResult result = analyzerService.analyze(interval).toResult();
final Map<UserAgentInfo, AtomicInteger> stats = result.getUserAgentInfos();
System.out.println("User agent information count: " + stats.size());
String name;
String osName;
int count;
for (final Entry<UserAgentInfo, AtomicInteger> entry : stats.entrySet()) {
name = entry.getKey().getName();
osName = entry.getKey().getOsName();
count = entry.getValue().get();
maxCount += count;
System.out.println(name + " (" + osName + ") \t" + count);
}
System.out.println("Sum: " + maxCount);
final long elapsedTime = System.currentTimeMillis() - startTime;
final Period p = new Period(elapsedTime);
System.out.println("Total processing time: " + p.toString(FORMATTER));
}
} else {
System.out.println("There is nothing to analyze.");
}
}
}
Example 21
Project: joda-time-master File: Interval.java View source code |
/**
* Parses a {@code Interval} from the specified string, using any offset it contains.
* <p>
* The String formats are described by
* {@link ISODateTimeFormat#dateTimeParser()}{@code .withOffsetParsed()}
* and {@link ISOPeriodFormat#standard()}, and may be 'datetime/datetime',
* 'datetime/period' or 'period/datetime'.
* <p>
* Sometimes this method and {@code new Interval(str)} return different results.
* This can be confusing as the difference is not visible in {@link #toString()}.
* <p>
* When passed a string without an offset, such as '2010-06-30T01:20/P1D',
* both the constructor and this method use the default time-zone.
* As such, {@code Interval.parseWithOffset("2010-06-30T01:20/P1D")} and
* {@code new Interval("2010-06-30T01:20/P1D"))} are equal.
* <p>
* However, when this method is passed a string with an offset,
* the offset is directly parsed and stored.
* As such, {@code Interval.parseWithOffset("2010-06-30T01:20+02:00/P1D")} and
* {@code new Interval("2010-06-30T01:20+02:00/P1D"))} are NOT equal.
* The object produced via this method has a zone of {@code DateTimeZone.forOffsetHours(2)}.
* The object produced via the constructor has a zone of {@code DateTimeZone.getDefault()}.
*
* @param str the string to parse, not null
* @since 2.9
*/
public static Interval parseWithOffset(String str) {
int separator = str.indexOf('/');
if (separator < 0) {
throw new IllegalArgumentException("Format requires a '/' separator: " + str);
}
String leftStr = str.substring(0, separator);
if (leftStr.length() <= 0) {
throw new IllegalArgumentException("Format invalid: " + str);
}
String rightStr = str.substring(separator + 1);
if (rightStr.length() <= 0) {
throw new IllegalArgumentException("Format invalid: " + str);
}
DateTimeFormatter dateTimeParser = ISODateTimeFormat.dateTimeParser().withOffsetParsed();
PeriodFormatter periodParser = ISOPeriodFormat.standard();
DateTime start = null;
Period period = null;
// before slash
char c = leftStr.charAt(0);
if (c == 'P' || c == 'p') {
period = periodParser.withParseType(PeriodType.standard()).parsePeriod(leftStr);
} else {
start = dateTimeParser.parseDateTime(leftStr);
}
// after slash
c = rightStr.charAt(0);
if (c == 'P' || c == 'p') {
if (period != null) {
throw new IllegalArgumentException("Interval composed of two durations: " + str);
}
period = periodParser.withParseType(PeriodType.standard()).parsePeriod(rightStr);
return new Interval(start, period);
} else {
DateTime end = dateTimeParser.parseDateTime(rightStr);
if (period != null) {
return new Interval(period, end);
} else {
return new Interval(start, end);
}
}
}
Example 22
Project: Moola-master File: TempTest.java View source code |
public static void main(String[] args) { DateTime todayDateObj = new DateTime(2014, 8, 9, 0, 0, 0); DateTime backDaysObj = todayDateObj.minusDays(9); DateTime backMonthObj = backDaysObj.minusMonths(10); DateTime backYearObj = backMonthObj.minusYears(10); System.out.println(todayDateObj); System.out.println(backDaysObj); System.out.println(backMonthObj); System.out.println(backYearObj); System.out.println(backYearObj.plusYears(10).plusMonths(10).plusDays(9)); // DateTimeZone zone = DateTimeZone.forID("America/Argentina/San_Luis"); // System.out.println(zone.getShortName(System.currentTimeMillis())); // System.out.println(LONDON.getShortName(System.currentTimeMillis())); // System.out.println(PARIS.getShortName(System.currentTimeMillis())); // System.out.println(NEWYORK.getShortName(System.currentTimeMillis())); // // for (String id : DateTimeZone.getAvailableIDs()) { // DateTimeZone z = DateTimeZone.forID(id); // String str = z.getShortName(System.currentTimeMillis()); // String str2 = z.getName(System.currentTimeMillis()); // if (str.startsWith("+") || str.startsWith("-")) { // System.out.println(z + " " + str + " " + str2 + " " + z.getNameKey(System.currentTimeMillis())); // System.out.println(DateTimeFormat.forPattern("z Z").withZone(z).print(System.currentTimeMillis())); // } // } // Locale.setDefault(Locale.FRENCH); // // PeriodFormatter f1 = PeriodFormat.getDefault(); // PeriodFormatter f2 = PeriodFormat.wordBased(); // PeriodFormatter f3 = PeriodFormat.wordBased(Locale.GERMAN); // String str1 = f1.withLocale(Locale.ITALIAN).print(Period.months(2).withDays(3)); // String str2 = f2.withLocale(Locale.ITALIAN).print(Period.months(2).withDays(3)); // String str3 = f3.withLocale(Locale.ITALIAN).print(Period.months(2).withDays(3)); // System.out.println(str1); // System.out.println(str2); // System.out.println(str3); //// DateTimeFormatter formatter = DateTimeFormat.forPattern("'added' MMMM dd yyyy 'at' HH:mm").withZoneUTC(); // DateTimeFormatter formatter = new DateTimeFormatterBuilder() // .appendLiteral("added ") // .appendMonthOfYearText() // .appendLiteral(' ') // .appendDayOfMonth(2) // .appendLiteral(' ') // .appendYear(4, 4) // .appendLiteral(" at ") //// .append(DateTimeFormat.forPattern("HH:mm")) // .appendHourOfDay(2) // .appendLiteral(":") // .appendMinuteOfDay(2) // .toFormatter() // .withZoneUTC(); // // String s1 = "added December 11 2014 at 05:45"; // String s2 = "added December 11 2014 at 14:45"; // // DateTime date1 = DateTime.parse(s1, formatter); // DateTime date2 = DateTime.parse(s2, formatter); // // System.out.println(date1); // System.out.println(date2); // DateTimeZone MST = DateTimeZone.forID("MST"); // DateTime start = new DateTime(2014, 8, 12, 9, 0, MST); // DateTime past1 = new DateTime(MST).minusDays(2); // DateTime later1 = past1.plusSeconds((int) new Duration(past1, start).getStandardSeconds()); // System.out.println(past1); // System.out.println(start); // System.out.println(new Period(past1, start)); // System.out.println(later1); // DateTime past2 = past1.withMillisOfSecond(0); // DateTime later2 = past2.plusSeconds((int) new Duration(past2, start).getStandardSeconds()); // System.out.println(later2); // Locale poland = new Locale("pl", "PL"); // DateTimeFormatter a = DateTimeFormat.forStyle("S-").withLocale(poland); // DateTimeFormatter b = DateTimeFormat.forStyle("M-").withLocale(poland); // System.out.println(a.print(0)); // System.out.println(b.print(0)); // // DateFormat e = DateFormat.getDateInstance(DateFormat.SHORT, poland); // System.out.println(e.format(new Date())); // DateFormat f = DateFormat.getDateInstance(DateFormat.MEDIUM, poland); // System.out.println(f.format(new Date())); // LocalDate start = new LocalDate(2014, 7, 31); // LocalDate end = new LocalDate(2014, 9, 17); // Period p = Period.fieldDifference(start, end); // LocalDate recalculatedEnd = start.plus(p); // System.out.println(p); // System.out.println(end); // System.out.println(recalculatedEnd); // DateTime tomorrow = new DateTime().plusDays(1); // // Interval i1 = new Interval(today, today); // Interval i2 = new Interval(today, tomorrow); // Interval i3 = new Interval(tomorrow, tomorrow); // // System.out.println(i1); // System.out.println(i2); // System.out.println(i3); // // if (i1.isBefore(i2)) System.out.println("i1 before i2"); // "i1 before i2" // if (i2.isBefore(i1)) System.out.println("i2 before i1"); // "" // if (i2.isBefore(i3)) System.out.println("i2 before i3"); // "i2 before i3" // TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); // DateTimeZone.setDefault(DateTimeZone.forID("America/Los_Angeles")); // Calendar cLocal = Calendar.getInstance(); // cLocal.set(2014, 0, 31, 16, 0, 0); // cLocal.set(Calendar.MILLISECOND, 0); // System.out.format("Local.instant=%d\n", cLocal.getTimeInMillis()); //output: 1391212800000 // // Calendar cUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC")); // cUTC.set(2014, 1, 1, 0, 0, 0); // cUTC.set(Calendar.MILLISECOND, 0); // System.out.format("UTC.instant=%d\n", cUTC.getTimeInMillis()); //output: 1391212800000 // // LocalDate local = new LocalDate(cLocal.getTimeInMillis()); // System.out.println(local + " " + local.getLocalMillis()); // System.out.format("local=%s .instant=%d\n", local.toString(), local.toDate().getTime()); //output: local=2014-01-31 .instant=1391155200000 // LocalDate utc = new LocalDate(cUTC.getTimeInMillis(), DateTimeZone.UTC); // System.out.println(utc + " " + utc.getLocalMillis()); // System.out.format("utc=%s .instant=%d\n", utc.toString(), utc.toDate().getTime());//output: utc=2014-02-01 .instant=1391241600000 // // Period p1 = Period.fieldDifference(utc,local); // Period p = p1.normalizedStandard(PeriodType.millis()); //java.lang.ArithmeticException: Value cannot fit in an int: 2592000000 // DateTimeZone zone = DateTimeZone.forOffsetMillis(p.getMillis()); // Assert.assertEquals(DateTimeZone.forOffsetHours(-8), zone); // // DateTime dtLocal = new DateTime(2014, 1, 31, 16, 00); //server time // DateTime dtUTC = new DateTime(2014, 2, 1, 0, 0, DateTimeZone.UTC); //Assume UTC = server+8 hours (actual code uses DateTime.now(DateTimeZone.UTC)) // LocalDate local = dtLocal.toLocalDate(); // LocalDate utc = dtUTC.toLocalDate(); // System.out.println(local); // System.out.println(utc); // // Period p = Period.fieldDifference(utc,local).normalizedStandard(PeriodType.millis()); //Throws a java.lang.ArithmeticException: Value cannot fit in an int: xx // System.out.println(p); // DateTime dtLocal = new DateTime(2014, 1, 31, 15, 59); //Server time // DateTime dtUTC = new DateTime(2014, 1, 31, 12, 59, DateTimeZone.UTC); //Assume UTC = server+8 hours (actual code uses DateTime.now(DateTimeZone.UTC)) // // LocalDate local = dtLocal.toLocalDate(); // LocalDate utc = dtUTC.toLocalDate(); // // Period p = Period.fieldDifference(utc,local).normalizedStandard(PeriodType.millis()); // // DateTimeZone timeZone = DateTimeZone.forID("America/Havana"); // long milli = 1352005199998L; // MutableDateTime dt = new MutableDateTime(milli, timeZone); // // now dt is 2012-11-04T00:59:59.998-04:00 // // int year = dt.getYear(); // 2012 // int month = dt.getMonthOfYear(); // 11 // int day = dt.getDayOfMonth(); // 4 // // Interval theDay = new LocalDate(year, month, day).toInterval(timeZone); // // theDay is 2012-11-04T00:00:00.000-05:00/2012-11-05T00:00:00.000-05:00, // // which does not include dt. // System.out.println(theDay); // // Interval lastDay = new LocalDate(year, month, day-1).toInterval(timeZone); // // lastDay is 2012-11-03T00:00:00.000-04:00/2012-11-04T00:00:00.000-05:00 // // i.e. joda thinks that 2012-11-04T00:59:59.998-04:00 is an instance of 2012-11-3 // // instead of 2012-11-04 // System.out.println(lastDay); // TimeZone.setDefault(TimeZone.getTimeZone("GMT")); // DateTimeZone.setDefault(DateTimeZone.forOffsetHoursMinutes(5, 30)); // DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy").withZoneUTC(); // DateTime dateTime = DateTime.parse("10/06/2014", dateTimeFormatter).toDateTime(DateTimeZone.UTC); // System.out.println(dateTime.getZone()); // long value = dateTime.getMillis()/1000; // System.out.println(dateTime); // System.out.println(value); // System.out.println(new Date(value * 1000)); // parseDate("dd/MM/yyyy", "10/06/2014") giving me 1402338600 // which is // GMT: Mon, 09 Jun 2014 18:30:00 GMT // Your time zone: 6/10/2014 12:00:00 AM GMT+5.5 // System.out.println(new LocalDate(ISOChronology.getInstanceUTC())); // System.out.println(new LocalDate(CopticChronology.getInstanceUTC())); // System.out.println(new LocalDate(EthiopicChronology.getInstanceUTC())); // // LocalDate coptic = new LocalDate(1, 1, 1, CopticChronology.getInstanceUTC()); // System.out.println(coptic); // System.out.println(coptic.toDateTimeAtStartOfDay(DateTimeZone.UTC).withChronology(ISOChronology.getInstanceUTC()).toLocalDate()); // // LocalDate ethiopic = new LocalDate(1, 1, 1, EthiopicChronology.getInstanceUTC()); // System.out.println(ethiopic); // System.out.println(ethiopic.toDateTimeAtStartOfDay(DateTimeZone.UTC).withChronology(ISOChronology.getInstanceUTC()).toLocalDate()); // DateTimeZone tz = DateTimeZone.forID("America/Argentina/Buenos_Aires"); // DateTimeZone.setDefault(tz); // DateTimeFormatter df = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss zzz"); // // df.parseMillis(df.print(System.currentTimeMillis())); // DateTimeZone branco = DateTimeZone.forID("America/Rio_Branco"); // System.out.println(branco); // Instant old = new Instant(0L); // Instant i = new Instant(branco.nextTransition(old.getMillis())); // while (old.equals(i) == false) { // System.out.println(i); // old = i; // i = new Instant(branco.nextTransition(old.getMillis())); // } // // DateTime dt = new DateTime(2008, 6, 23, 23, 0, branco); // System.out.println(dt); // dt = dt.plusMinutes(30); // System.out.println(dt); // dt = dt.plusMinutes(30); // System.out.println(dt); // dt = dt.plusMinutes(30); // System.out.println(dt); // dt = dt.plusMinutes(30); // System.out.println(dt); // dt = dt.plusMinutes(30); // System.out.println(dt); // dt = dt.plusMinutes(30); // System.out.println(dt); // dt = dt.plusMinutes(30); // System.out.println(dt); // DateTimeZone HONG_KONG_TZ = DateTimeZone.forID("Asia/Hong_Kong"); // DateTime date1 = new DateTime(2013, 10, 2, 11, 30, 53, 512, HONG_KONG_TZ); // DateTime date2 = date1.toDateTime(DateTimeZone.UTC); // System.out.println(date1); // System.out.println(date2); // // System.out.println(date1.compareTo(date2)); // System.out.println(date1.toLocalDate().compareTo(date2.toLocalDate())); // System.out.println(DateTimeComparator.getInstance().compare(date1, date2)); // System.out.println(DateTimeComparator.getDateOnlyInstance().compare(date1, date2)); // System.out.println(DateTimeComparator.getDateOnlyInstance().compare(date1, date1.plusMinutes(1))); // TimeZone jdkMST = TimeZone.getTimeZone("MST"); // TimeZone jdkDenver = TimeZone.getTimeZone("America/Denver"); // DateTimeZone mst = DateTimeZone.forTimeZone(jdkMST); // DateTimeZone mst2 = DateTimeZone.forID(jdkMST.getID()); // System.out.println(jdkMST); // jdkMST.setID("America/Denver"); // System.out.println(jdkMST); // System.out.println(jdkDenver); // System.out.println(jdkDenver.equals(jdkMST)); // System.out.println(jdkMST.getID()); // System.out.println(mst.getID() + (mst.isFixed() ? " Fixed" : " DST")); // System.out.println(mst2.getID() + (mst2.isFixed() ? " Fixed" : " DST")); // DateTimeZone m = DateTimeZone.forID("MST7MDT"); // System.out.println(m + (m.isFixed() ? " Fixed" : " DST")); // System.out.println(DateTimeFormat.forPattern("s").print(321234)); // System.out.println(DateTimeFormat.forPattern("ss").print(321234)); // System.out.println(DateTimeFormat.forPattern("sss").print(321234)); // System.out.println(DateTimeFormat.forPattern("S").print(321234)); // System.out.println(DateTimeFormat.forPattern("SS").print(321234)); // System.out.println(DateTimeFormat.forPattern("SSS").print(321234)); // System.out.println(DateTimeFormat.forPattern("SSSS").print(321234)); // // DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); // MutableDateTime result = new MutableDateTime(2000, 1, 1, 0, 0, 0, 0, NEWYORK); // System.out.println("4 = " + f.parseInto(result, "2 29", 0)); // System.out.println("" + new MutableDateTime(2000, 2, 29, 0, 0, 0, 0, NEWYORK) + " = " + result); // Chronology chronology = GJChronology.getInstance(); // // LocalDate start = new LocalDate(2013, 5, 31, chronology); // LocalDate expectedEnd = new LocalDate(-1, 5, 31, chronology); // 1 BC //// System.out.println(expectedEnd.plusYears(2013).equals(start)); // System.out.println(start.minusYears(2013).equals(expectedEnd)); //// System.out.println(start.plus(Period.years(-2013)).equals(expectedEnd)); // Period p1 = new Period(5L, PeriodType.hours()); // System.out.println(p1); // String string = p1.toString(); // System.out.println(string); // Period p2 = Period.parse(string); // System.out.println(p2); // Locale.setDefault(Locale.CHINA); // TimeZone sTimeZone = java.util.TimeZone.getTimeZone("GMT-01:00"); // System.out.println(Locale.getDefault()); // System.out.println(sTimeZone.getDisplayName()); // DateTimeZone dtz = DateTimeZone.forTimeZone(sTimeZone); // System.out.println(dtz.getID()); // DateTime n = DateTime.now(); // final DateTime now = n.toDateTimeISO(); // final DateTime parsed = DateTime.parse(now.toString()).withZone(null); // final DateTime parsed2 = new DateTime(now.toString()); // System.out.println(now.getZone() + " " + parsed.getZone()); // System.out.println(now + " " + parsed); // System.out.println(now.getZone() + " " + parsed2.getZone()); // System.out.println(now + " " + parsed2); // // MutableDateTime time = new MutableDateTime(DateTimeZone.forOffsetHours(1)); //// time.setZone(DateTimeZone.forOffsetHours(1)); // time.setRounding(time.getChronology().dayOfMonth(), MutableDateTime.ROUND_FLOOR); // // MutableDateTime utcTime = new MutableDateTime(DateTimeZone.UTC); // utcTime.setRounding(utcTime.getChronology().dayOfMonth(), MutableDateTime.ROUND_FLOOR); // // time.setMillis(90000); // utcTime.setMillis(90000); // System.out.println("time: " + time + ", utc " + utcTime); // System.out.println("time_millis: " + time.getMillis() + ", utc_millis " + utcTime.getMillis()); // //// MutableDateTime time = new MutableDateTime(DateTimeZone.forOffsetHours(1)); ////// time.setZone(DateTimeZone.forOffsetHours(1)); //// time.setRounding(time.getChronology().minuteOfHour(), MutableDateTime.ROUND_FLOOR); //// //// MutableDateTime utcTime = new MutableDateTime(DateTimeZone.UTC); //// utcTime.setRounding(utcTime.getChronology().minuteOfHour(), MutableDateTime.ROUND_FLOOR); //// //// time.setMillis(90000); //// utcTime.setMillis(90000); //// System.out.println("time: " + time + ", utc " + utcTime); //// System.out.println("time_millis: " + time.getMillis() + ", utc_millis " + utcTime.getMillis()); }
Example 23
Project: TCSlackNotifierPlugin-master File: SlackServerAdapter.java View source code |
private void postFailureBuild(SRunningBuild build) {
String message = "";
PeriodFormatter durationFormatter = new PeriodFormatterBuilder().printZeroRarelyFirst().appendHours().appendSuffix(" hour", " hours").appendSeparator(" ").printZeroRarelyLast().appendMinutes().appendSuffix(" minute", " minutes").appendSeparator(" and ").appendSeconds().appendSuffix(" second", " seconds").toFormatter();
Duration buildDuration = new Duration(1000 * build.getDuration());
message = String.format("Project '%s' build failed! ( %s )", build.getFullName(), durationFormatter.print(buildDuration.toPeriod()));
postToSlack(build, message, false);
}
Example 24
Project: TinyTravelTracker-master File: StringConverter.java View source code |
//-----------------------------------------------------------------------
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
Example 25
Project: VarexJ-master File: StringConverter.java View source code |
//-----------------------------------------------------------------------
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
Example 26
Project: way-master File: StringConverter.java View source code |
//-----------------------------------------------------------------------
/**
* Extracts duration values from an object of this converter's type, and
* sets them into the given ReadWritableDuration.
*
* @param period period to get modified
* @param object the String to convert, must not be null
* @param chrono the chronology to use
* @return the millisecond duration
* @throws ClassCastException if the object is invalid
*/
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
String str = (String) object;
PeriodFormatter parser = ISOPeriodFormat.standard();
period.clear();
int pos = parser.parseInto(period, str, 0);
if (pos < str.length()) {
if (pos < 0) {
// Parse again to get a better exception thrown.
parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
}
throw new IllegalArgumentException("Invalid format: \"" + str + '"');
}
}
Example 27
Project: cms-ce-master File: ExpressionFunctions.java View source code |
public String currentDatePlusOffset(String format, String periodStr) {
DateTime nowDateTime = timeService.getNowAsDateTime();
PeriodFormatter periodFormatter = ISOPeriodFormat.standard();
Period period = periodFormatter.parsePeriod(periodStr);
DateTime offsetDateTime = nowDateTime.plus(period);
SimpleDateFormat fmt = new SimpleDateFormat(format);
return fmt.format(offsetDateTime.toDate());
}
Example 28
Project: elw-master File: FormatTool.java View source code |
private PeriodFormatter lookupPeriodFormatter(String pattern) { synchronized (dtfCache) { final PeriodFormatter cached = pfCache.get(pattern); if (cached != null) { return cached; } final PeriodFormatter created = createDefaultPeriodFormatted(pattern).withLocale(locale); pfCache.put(pattern, created); return created; } }
Example 29
Project: jresponder-master File: MessageRefImpl.java View source code |
/**
* Gets the JR_WAIT_AFTER_LAST_MESSAGE property and parses it as an
* ISO8601 duration and returns the number of milliseconds it represents.
* Returns null if not set.
* @throws IllegalArgumentException if the value is in an invalid format
* @return
*/
@Override
public Long getWaitAfterLastMessage() {
// try to parse time from message
String myWaitAfterLastMessageString = this.getProp(MessageRefProp.JR_WAIT_AFTER_LAST_MESSAGE);
if (myWaitAfterLastMessageString == null) {
logger().debug("No JR_WAIT_AFTER_LAST_MESSAGE property found on message (message={})", getName());
return null;
}
PeriodFormatter myPeriodFormatter = ISOPeriodFormat.standard();
try {
long myDuration = myPeriodFormatter.parsePeriod(myWaitAfterLastMessageString).toStandardDuration().getMillis();
return myDuration;
} catch (IllegalArgumentException e) {
logger().error("Unable to parse JR_WAIT_AFTER_LAST_MESSAGE value for (message={}), value was: \"{}\" (this is a problem you need to fix!!! e.g. for one day, use \"P1D\")", new Object[] { getName(), myWaitAfterLastMessageString });
throw new IllegalArgumentException("Error parsing JR_WAIT_AFTER_LAST_MESSAGE value: " + myWaitAfterLastMessageString, e);
}
}
Example 30
Project: BlackboardVCPortlet-master File: SessionImpl.java View source code |
@Override public String getTimeFancyText(DateTime from, DateTime to) { final String prefix = "Join in "; if (to != null) { Duration d = new Duration(to, from); Period timeUntil = new Period(to.toInstant(), from.toInstant(), PeriodType.dayTime()); long standardDays = d.getStandardDays(); if (standardDays > 0) { PeriodFormatter daysHours = new PeriodFormatterBuilder().appendDays().appendSuffix(" day", " days").appendSeparator(", and ").appendHours().appendSuffix(" hour", " hours").toFormatter(); return prefix + daysHours.print(timeUntil.normalizedStandard(PeriodType.dayTime())); } else { PeriodFormatter dafaultFormatter = new PeriodFormatterBuilder().appendHours().appendSuffix(" hour", " hours").appendSeparator(", and ").appendMinutes().appendSuffix(" minute", " minutes").toFormatter(); return prefix + dafaultFormatter.print(timeUntil.normalizedStandard(PeriodType.dayTime())); } } else { return null; } }
Example 31
Project: constellio-master File: LDAPConfigurationManager.java View source code |
private Duration newDuration(Map<String, String> configs, String key) {
String durationString = getString(configs, key, null);
if (durationString != null) {
//format (\\d*d)(\\d*h)(\\d*mn) (d == day)
PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendLiteral("d").appendHours().appendLiteral("h").appendMinutes().appendLiteral("mn").toFormatter();
Duration duration = formatter.parsePeriod(durationString).toStandardDuration();
return duration;
}
return null;
}
Example 32
Project: gina-puffinfeeder-android-viewer-master File: ImageViewFrameActivty.java View source code |
/**
* Calculates how long it has been since the time stored in the parameters.
* @param pic Date and time to compare with.
* @return String describing how long it has been since the time described in the parameters.
*/
private String findTimeDifference(DateTime pic) {
DateTime now = new DateTime(System.currentTimeMillis());
Period diff = new Period(pic, now);
PeriodFormatter toastFormatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" year, ", " years, ").appendMonths().appendSuffix(" month, ", " months, ").appendWeeks().appendSuffix(" week, ", " weeks, ").appendDays().appendSuffix(" day,", " days,").appendSeparator(" and ").printZeroAlways().appendHours().appendSuffix(" hour", " hours").appendLiteral(" ago.").toFormatter();
return toastFormatter.print(diff);
}
Example 33
Project: lasso-master File: MainActivity.java View source code |
private void setTimeAgoPill(DateTime start) {
if (start == null) {
return;
}
Minutes minutes = Minutes.minutesBetween(start, Instant.now());
PeriodFormatterBuilder periodFormatterBuilder = new PeriodFormatterBuilder();
if (minutes.toStandardWeeks().getWeeks() > 1) {
periodFormatterBuilder.appendWeeks().appendSuffix(getApplicationContext().getString(R.string.week), getApplicationContext().getString(R.string.weeks));
} else if (minutes.toStandardDays().getDays() > 1) {
periodFormatterBuilder.appendDays().appendSuffix(getApplicationContext().getString(R.string.day), getApplicationContext().getString(R.string.days));
} else if (minutes.toStandardHours().getHours() > 1) {
periodFormatterBuilder.appendHours().appendSuffix(getApplicationContext().getString(R.string.hour), getApplicationContext().getString(R.string.hours));
} else {
periodFormatterBuilder.appendMinutes().appendSuffix(getApplicationContext().getString(R.string.minute), getApplicationContext().getString(R.string.minutes));
}
periodFormatterBuilder.appendLiteral(" ago");
PeriodFormatter formatter = periodFormatterBuilder.toFormatter();
String pattern = "(\\d+)(.*)";
Pattern r = Pattern.compile(pattern);
Log.d("minutes", "Minutes: " + formatter.print(minutes));
Matcher m = r.matcher(formatter.print(minutes));
if (m.find()) {
String number = m.group(1);
String ago = m.group(2);
minago.update(ago, number);
}
}
Example 34
Project: w3act-master File: User.java View source code |
/**
* This method calculates memership period for the user.
* @return
*/
public String calculate_membership() {
String res = "";
Logger.debug("createdAt: " + createdAt + ", last_access: " + last_access + ", last_login: " + last_login);
try {
long timestampCreated = createdAt.getTime();
Date dateCreated = new Date(timestampCreated * 1000);
long timestampLastAccess = Long.valueOf(last_access);
Date dateLastAccess = new Date(timestampLastAccess * 1000);
Logger.debug("date created: " + dateCreated);
Logger.debug("date last access: " + dateLastAccess);
DateTime dt1 = new DateTime(dateCreated);
DateTime dt2 = new DateTime(dateLastAccess);
Period period = new Period(dt1, dt2);
PeriodFormatterBuilder formaterBuilder = new PeriodFormatterBuilder().appendMonths().appendSuffix(" months ").appendWeeks().appendSuffix(" weeks");
PeriodFormatter pf = formaterBuilder.toFormatter();
// Logger.debug(pf.print(period));
res = pf.print(period);
} catch (Exception e) {
Logger.debug("date difference calculation error: " + e);
}
return res;
}
Example 35
Project: OpenClinica-master File: RuleController.java View source code |
@RequestMapping(value = "/studies/{study}/validateAndTestRule", method = RequestMethod.POST)
@ResponseBody
public org.openclinica.ns.rules_test.v31.RulesTest create(@RequestBody org.openclinica.ns.rules_test.v31.RulesTest ruleTest, Model model, HttpSession session, @PathVariable("study") String studyOid) throws Exception {
ResourceBundleProvider.updateLocale(new Locale("en_US"));
RulesPostImportContainer rpic = mapRulesToRulesPostImportContainer(ruleTest.getRules());
StudyDAO studyDao = new StudyDAO(dataSource);
StudyBean currentStudy = studyDao.findByOid(studyOid);
UserAccountBean userAccount = getUserAccount();
mayProceed(userAccount, currentStudy);
getRulePostImportContainerService(currentStudy, userAccount);
rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleDefs(rpic);
rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleSetDefs(rpic);
Response response = new Response();
response.setValid(Boolean.TRUE);
if (rpic.getInValidRuleDefs().size() > 0 || rpic.getInValidRuleSetDefs().size() > 0) {
response.setValid(Boolean.FALSE);
for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getInValidRuleDefs()) {
for (String error : beanWrapper.getImportErrors()) {
org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
messageType.setMessage(error);
response.getMessages().add(messageType);
}
}
for (AuditableBeanWrapper<RuleSetBean> beanWrapper : rpic.getInValidRuleSetDefs()) {
for (String error : beanWrapper.getImportErrors()) {
org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
messageType.setMessage(error);
response.getMessages().add(messageType);
}
}
}
HashMap<String, String> p = new HashMap<String, String>();
for (ParameterType parameterType : ruleTest.getParameters()) {
p.put(parameterType.getKey(), parameterType.getValue());
}
ExpressionObjectWrapper eow = new ExpressionObjectWrapper(dataSource, currentStudy, rpic.getRuleDefs().get(0).getExpression(), rpic.getRuleSets().get(0));
ExpressionProcessor ep = ExpressionProcessorFactory.createExpressionProcessor(eow);
// Run expression with populated HashMap
DateTime start = new DateTime();
HashMap<String, String> result = ep.testEvaluateExpression(p);
DateTime end = new DateTime();
Duration dur = new Duration(start, end);
PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder().printZeroAlways().appendSecondsWithMillis().appendSuffix(" second", " seconds").toFormatter();
yearsAndMonths.print(dur.toPeriod());
// Run expression with empty HashMap to check rule validity, because
// using illegal test values will cause invalidity
HashMap<String, String> k = new HashMap<String, String>();
HashMap<String, String> theResult = ep.testEvaluateExpression(k);
ruleTest.getParameters().clear();
for (Map.Entry<String, String> entry : result.entrySet()) {
ParameterType parameterType = new ParameterType();
parameterType.setKey(entry.getKey());
parameterType.setValue(entry.getValue());
ruleTest.getParameters().add(parameterType);
}
// if (theResult.get("ruleValidation").equals("rule_valid") && result.get("ruleValidation").equals("rule_invalid")) {
// result.put("ruleValidation", "rule_valid");
// result.put("ruleEvaluatesTo", resword.getString("test_rules_rule_fail") + " " +
// result.get("ruleValidationFailMessage"));
// result.remove("ruleValidationFailMessage");
// }
// Put on screen
// request.setAttribute("duration", yearsAndMonths.print(dur.toPeriod()));
RulesTestMessagesType messageType = new RulesTestMessagesType();
messageType.setKey("duration");
messageType.setValue(yearsAndMonths.print(dur.toPeriod()));
ruleTest.getRulesTestMessages().add(messageType);
return ruleTest;
}
Example 36
Project: presto-master File: DateTimeUtils.java View source code |
public static long parsePeriodMillis(PeriodFormatter periodFormatter, String value, IntervalField startField, IntervalField endField) {
try {
Period period = parsePeriod(periodFormatter, value);
return IntervalDayTime.toMillis(period.getValue(DAY_FIELD), period.getValue(HOUR_FIELD), period.getValue(MINUTE_FIELD), period.getValue(SECOND_FIELD), period.getValue(MILLIS_FIELD));
} catch (IllegalArgumentException e) {
throw invalidInterval(e, value, startField, endField);
}
}
Example 37
Project: SAX-master File: SAXProcessor.java View source code |
/**
* Generic method to convert the milliseconds into the elapsed time string.
*
* @param start Start timestamp.
* @param finish End timestamp.
* @return String representation of the elapsed time.
*/
public static String timeToString(long start, long finish) {
// in milliseconds
Duration duration = new Duration(finish - start);
PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds().appendSuffix("s").appendMillis().appendSuffix("ms").toFormatter();
return formatter.print(duration.toPeriod());
}
Example 38
Project: whole-master File: SchemaDataTypeParsers.java View source code |
public static PeriodFormatter durationFormatter() {
if (duration == null) {
duration = new PeriodFormatterBuilder().rejectSignedValues(true).appendLiteral("P").appendYears().appendSuffix("Y").appendMonths().appendSuffix("M").appendWeeks().appendSuffix("W").appendDays().appendSuffix("D").appendSeparatorIfFieldsAfter("T").appendHours().appendSuffix("H").appendMinutes().appendSuffix("M").appendSecondsWithOptionalMillis().appendSuffix("S").toFormatter();
}
return duration;
}
Example 39
Project: eMonocot-master File: Functions.java View source code |
/**
*
* @param start
* Set the start date
* @param end
* Set the end date
* @return a formatted period
*/
public static String formatPeriod(Date start, Date end) {
DateTime startDate = new DateTime(start);
DateTime endDate = new DateTime(end);
Period period = new Interval(startDate, endDate).toPeriod();
PeriodFormatter formatter = new PeriodFormatterBuilder().minimumPrintedDigits(2).appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
return formatter.print(period);
}
Example 40
Project: knox-master File: GatewayConfigImpl.java View source code |
@Override
public long getGatewayDeploymentsBackupAgeLimit() {
PeriodFormatter f = new PeriodFormatterBuilder().appendDays().toFormatter();
String s = get(DEPLOYMENTS_BACKUP_AGE_LIMIT, "-1");
long d;
try {
Period p = Period.parse(s, f);
d = p.toStandardDuration().getMillis();
if (d < 0) {
d = -1;
}
} catch (Exception e) {
d = -1;
}
return d;
}
Example 41
Project: openhab1-addons-master File: SonosZonePlayer.java View source code |
public boolean updateAlarm(SonosAlarm alarm) {
if (alarm != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("AlarmClock"));
Action action = service.getAction("ListAlarms");
ActionInvocation invocation = new ActionInvocation(action);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
PeriodFormatter pFormatter = new PeriodFormatterBuilder().printZeroAlways().appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
try {
invocation.setInput("ID", Integer.toString(alarm.getID()));
invocation.setInput("StartLocalTime", formatter.print(alarm.getStartTime()));
invocation.setInput("Duration", pFormatter.print(alarm.getDuration()));
invocation.setInput("Recurrence", alarm.getRecurrence());
invocation.setInput("RoomUUID", alarm.getRoomUUID());
invocation.setInput("ProgramURI", alarm.getProgramURI());
invocation.setInput("ProgramMetaData", alarm.getProgramMetaData());
invocation.setInput("PlayMode", alarm.getPlayMode());
invocation.setInput("Volume", Integer.toString(alarm.getVolume()));
if (alarm.getIncludeLinkedZones()) {
invocation.setInput("IncludeLinkedZones", "1");
} else {
invocation.setInput("IncludeLinkedZones", "0");
}
if (alarm.getEnabled()) {
invocation.setInput("Enabled", "1");
} else {
invocation.setInput("Enabled", "0");
}
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}", ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}", ex.getMessage());
}
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
Example 42
Project: java-saml-master File: Util.java View source code |
/**
* Interprets a ISO8601 duration value relative to a given timestamp.
*
* @param durationString
* The duration, as a string.
* @param timestamp
* The unix timestamp we should apply the duration to.
*
* @return the new timestamp, after the duration is applied In Seconds.
*
* @throws IllegalArgumentException
*/
public static long parseDuration(String durationString, long timestamp) throws IllegalArgumentException {
boolean haveMinus = false;
if (durationString.startsWith("-")) {
durationString = durationString.substring(1);
haveMinus = true;
}
PeriodFormatter periodFormatter = ISOPeriodFormat.standard().withLocale(new Locale("UTC"));
Period period = periodFormatter.parsePeriod(durationString);
DateTime dt = new DateTime(timestamp * 1000, DateTimeZone.UTC);
DateTime result = null;
if (haveMinus) {
result = dt.minus(period);
} else {
result = dt.plus(period);
}
return result.getMillis() / 1000;
}
Example 43
Project: Traktoid-master File: DateHelper.java View source code |
public static String getRuntime(int runtime) {
PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever().appendHours().appendSeparatorIfFieldsBefore("h").minimumPrintedDigits(2).appendMinutes().appendSeparatorIfFieldsBefore("m").toFormatter();
return formatter.print(new Period(runtime * 60 * 1000));
}
Example 44
Project: gocd-master File: RunDuration.java View source code |
public String duration(PeriodFormatter formatter) {
return "In Progress";
}
Example 45
Project: kickmaterial-master File: PeriodToStringConverter.java View source code |
/**
* Shorter syntax for creating {@link PeriodFormatterAndValue}
*
* @param formatter
* @param value
* @return
*/
private static PeriodFormatterAndValue pav(@Nonnull PeriodFormatter formatter, int value) {
return new PeriodFormatterAndValue(formatter, value);
}
Example 46
Project: lightblue-migrator-master File: NMPMonitor.java View source code |
/**
* Returns the period in msecs
*/
private static long parsePeriod(String periodStr) {
PeriodFormatter fmt = PeriodFormat.getDefault();
Period p = fmt.parsePeriod(periodStr);
return p.toStandardDuration().getMillis();
}
Example 47
Project: gson-jodatime-serialisers-master File: PeriodConverter.java View source code |
/**
* Gson invokes this call-back method during serialization when it encounters a field of the
* specified type. <p>
*
* In the implementation of this call-back method, you should consider invoking
* {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
* non-trivial field of the {@code src} object. However, you should never invoke it on the
* {@code src} object itself since that will cause an infinite loop (Gson will call your
* call-back method again).
* @param src the object that needs to be converted to Json.
* @param typeOfSrc the actual type (fully genericized version) of the source object.
* @return a JsonElement corresponding to the specified object.
*/
@Override
public JsonElement serialize(Period src, Type typeOfSrc, JsonSerializationContext context) {
final PeriodFormatter fmt = ISOPeriodFormat.standard();
return new JsonPrimitive(fmt.print(src));
}
Example 48
Project: substeps-core-master File: DetailedJsonBuilder.java View source code |
private String convert(long runningDurationMillis) {
Duration duration = new Duration(runningDurationMillis);
PeriodFormatter formatter = PeriodFormat.getDefault();
return formatter.print(duration.toPeriod());
}