org.joda.time.format.PeriodFormat Java Examples

The following examples show how to use org.joda.time.format.PeriodFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InstantValidator.java    From verify-service-provider with MIT License 6 votes vote down vote up
public void validate(DateTime instant, String instantName) {
    Duration age = new Duration(instant, DateTime.now());
    if (age.isLongerThan(MAXIMUM_INSTANT_AGE)) {
        throw new SamlResponseValidationException(String.format("%s is too far in the past %s",
            instantName,
            PeriodFormat.getDefault().print(age.toPeriod()))
        );
    }

    if (dateTimeComparator.isAfterNow(instant)) {
        throw new SamlResponseValidationException(String.format("%s is in the future %s",
            instantName,
            instant.withZone(UTC).toString(dateHourMinuteSecond()))
        );
    }
}
 
Example #2
Source File: ListOfflineWorkflowsTool.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
    try (OfflineApplication app = new RemoteOfflineApplicationImpl()) {
        Map<String, OfflineWorkflowStatus> statuses = app.listWorkflows();
        Table table = new Table(4, BorderStyle.CLASSIC_WIDE);
        table.addCell("ID");
        table.addCell("Running");
        table.addCell("Step");
        table.addCell("Time");
        for (Map.Entry<String, OfflineWorkflowStatus> entry : statuses.entrySet()) {
            String workflowId = entry.getKey();
            OfflineWorkflowStatus status = entry.getValue();
            Duration remaining = null;
            if (status.getStartTime() != null) {
                remaining = Duration.millis(status.getStartParameters().getDuration() * 60 * 1000)
                        .minus(new Duration(status.getStartTime(), DateTime.now()));
            }
            table.addCell(workflowId);
            table.addCell(Boolean.toString(status.isRunning()));
            table.addCell(status.getStep() != null ? status.getStep().toString() : "");
            table.addCell(remaining != null ? PeriodFormat.getDefault().print(remaining.toPeriod()) : "");
        }
        context.getOutputStream().println(table.render());
    }
}
 
Example #3
Source File: VirtualAssetPerformanceTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
    public void performance() throws RepositoryNotFoundException {
        //      dmojito repo-create -n perftest3 -d "" -l  "ar-SA" "zh-CN" "zh-TW" "cs-CZ" "da-DK" "de-DE" "el-GR" "en-GB" "es-AR" "es-MX" "es-ES" "fi-FI" "fr-FR" "hi-IN" "hu-HU" "id-ID" "it-IT" "ja-JP" "ko-KR" "ms-MY" "nb-NO" "nl-NL" "pl-PL" "pt-BR" "pt-PT" "ro-RO" "ru-RU" "sk-SK" "sv-SE" "th-TH" "tl-PH" "tr-TR" "uk-UA" "vi-VN"
        String repoName = "perftest3";

        Repository repository = repositoryClient.getRepositoryByName(repoName);

        VirtualAsset v = new VirtualAsset();
        v.setPath("default");
        v.setRepositoryId(repository.getId());
        v.setDeleted(false);
        VirtualAsset virtualAsset = virtualAssetClient.createOrUpdate(v);

        logger.debug("virtual asset id: {}", virtualAsset.getId());

        DateTime start = DateTime.now();
//        createSourceStrings(virtualAsset);
//        importTranslations(repository, virtualAsset);

        pullSourceString(virtualAsset, repository);


        pullTranslations(virtualAsset, repository);
        logger.debug("total: {}", PeriodFormat.getDefault().print(new Period(start, DateTime.now())));
    }
 
Example #4
Source File: VirtualAssetPerformanceTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
void pullTranslations(VirtualAsset virtualAsset, Repository repository) {
        logger.debug("pull translations");

        repository.getRepositoryLocales().stream()
                .sorted(Comparator.comparing(rl -> rl.getLocale().getBcp47Tag()))
                .filter(rl -> rl.getParentLocale() != null)
                .forEach(rl -> {
                    logger.debug("localized locale: {}", rl.getLocale().getBcp47Tag());
                    long start = System.currentTimeMillis();
                    List<VirtualAssetTextUnit> virtualAssetTextUnits = virtualAssetClient.getLocalizedTextUnits(virtualAsset.getId(), rl.getLocale().getId(), "REMOVE_UNTRANSLATED");
                    long end = System.currentTimeMillis();
                    logger.debug("file generation: {}", PeriodFormat.getDefault().print(new Period(start, end)));

//                    ObjectMapper objectMapper = new ObjectMapper();
//                    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
//                    logger.debug(objectMapper.writeValueAsStringUnchecked(virtualAssetTextUnits));
                });
    }
 
Example #5
Source File: SimpleDoFnRunner.java    From beam with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation") // Allowed Skew is deprecated for users, but must be respected
private void checkTimestamp(Instant timestamp) {
  // The documentation of getAllowedTimestampSkew explicitly permits Long.MAX_VALUE to be used
  // for infinite skew. Defend against underflow in that case for timestamps before the epoch
  if (fn.getAllowedTimestampSkew().getMillis() != Long.MAX_VALUE
      && timestamp.isBefore(elem.getTimestamp().minus(fn.getAllowedTimestampSkew()))) {
    throw new IllegalArgumentException(
        String.format(
            "Cannot output with timestamp %s. Output timestamps must be no earlier than the "
                + "timestamp of the current input (%s) minus the allowed skew (%s). See the "
                + "DoFn#getAllowedTimestampSkew() Javadoc for details on changing the allowed "
                + "skew.",
            timestamp,
            elem.getTimestamp(),
            PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod())));
  }
}
 
Example #6
Source File: AsyncPutCallStatsReporter.java    From kinesis-log4j-appender with Apache License 2.0 5 votes vote down vote up
/**
 * This method is invoked when a log record is successfully sent to Kinesis.
 * Though this is not too useful for production use cases, it provides a good
 * debugging tool while tweaking parameters for the appender.
 */
@Override
public void onSuccess(PutRecordRequest request, PutRecordResult result) {
  successfulRequestCount++;
  if (logger.isDebugEnabled() && (successfulRequestCount + failedRequestCount) % 3000 == 0) {
    logger.debug("Appender (" + appenderName + ") made " + successfulRequestCount
        + " successful put requests out of total " + (successfulRequestCount + failedRequestCount) + " in "
        + PeriodFormat.getDefault().print(new Period(startTime, DateTime.now())) + " since start");
  }
}
 
Example #7
Source File: TestPeriod_Basics.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testToString_PeriodFormatter() {
    Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8);
    assertEquals("1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", test.toString(PeriodFormat.getDefault()));
    
    test = new Period(0, 0, 0, 0, 0, 0, 0, 0);
    assertEquals("0 milliseconds", test.toString(PeriodFormat.getDefault()));
}
 
Example #8
Source File: TestPeriod_Basics.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testToString_PeriodFormatter() {
    Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8);
    assertEquals("1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", test.toString(PeriodFormat.getDefault()));
    
    test = new Period(0, 0, 0, 0, 0, 0, 0, 0);
    assertEquals("0 milliseconds", test.toString(PeriodFormat.getDefault()));
}
 
Example #9
Source File: FlinkAbstractParDoWrapper.java    From flink-dataflow with Apache License 2.0 5 votes vote down vote up
protected void checkTimestamp(WindowedValue<IN> ref, Instant timestamp) {
	if (timestamp.isBefore(ref.getTimestamp().minus(doFn.getAllowedTimestampSkew()))) {
		throw new IllegalArgumentException(String.format(
				"Cannot output with timestamp %s. Output timestamps must be no earlier than the "
						+ "timestamp of the current input (%s) minus the allowed skew (%s). See the "
						+ "DoFn#getAllowedTimestmapSkew() Javadoc for details on changing the allowed skew.",
				timestamp, ref.getTimestamp(),
				PeriodFormat.getDefault().print(doFn.getAllowedTimestampSkew().toPeriod())));
	}
}
 
Example #10
Source File: Main.java    From spork with Apache License 2.0 5 votes vote down vote up
private static void printScriptRunTime(DateTime startTime) {
    DateTime endTime = new DateTime();
    Duration duration = new Duration(startTime, endTime);
    Period period = duration.toPeriod().normalizedStandard(PeriodType.time());
    log.info("Pig script completed in "
            + PeriodFormat.getDefault().print(period)
            + " (" + duration.getMillis() + " ms)");
}
 
Example #11
Source File: Utils.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given a duration in milliseconds, this method returns a human-readable period string.
 *
 * @param duration a duration in milliseconds, nonnegative
 * @return a String
 */
public static String makePeriodString(long duration) {
  if (duration < 0) {
    throw new IllegalArgumentException("duration should be nonnegative.");
  }
  Period period = new Period(duration).normalizedStandard();
  period = withMostSignificantNonZeroFieldsOnly(period, 1);
  return PeriodFormat.wordBased(Locale.ENGLISH).print(period);
}
 
Example #12
Source File: NexusContextListener.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void contextDestroyed(final ServletContextEvent event) {
  // event is ignored, apparently can also be null

  // remove our dynamic filter
  if (registration != null) {
    registration.unregister();
    registration = null;
  }

  // log uptime before triggering activity which may run into problems
  long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
  log.info("Uptime: {} ({})", PeriodFormat.getDefault().print(new Period(uptime)),
      System.getProperty(NEXUS_FULL_EDITION, UNKNOWN));

  try {
    moveToPhase(OFF);
  }
  catch (final Exception e) {
    log.error("Failed to stop nexus", e);
  }

  extender.doStop(); // stop tracking bundles

  if (servletContext != null) {
    servletContext = null;
  }

  injector = null;

  SharedMetricRegistries.remove("nexus");
}
 
Example #13
Source File: FileResourceEventListener.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void logMessage( String storageId, FileResource fileResource, Period timeDiff )
{
    if ( storageId == null )
    {
        log.error( String.format( "Saving content for file resource failed: %s", fileResource.getUid() ) );
        return;
    }

    log.info( String.format( "File stored with key: %s'. Upload finished in %s", storageId, timeDiff.toString( PeriodFormat.getDefault() ) ) );
}
 
Example #14
Source File: SimpleDoFnRunnerTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Demonstrates that attempting to output an element before the timestamp of the current element
 * plus the value of {@link DoFn#getAllowedTimestampSkew()} throws, but between that value and the
 * current timestamp succeeds.
 */
@Test
public void testSkew() {
  SkewingDoFn fn = new SkewingDoFn(Duration.standardMinutes(10L));
  DoFnRunner<Duration, Duration> runner =
      new SimpleDoFnRunner<>(
          null,
          fn,
          NullSideInputReader.empty(),
          new ListOutputManager(),
          new TupleTag<>(),
          Collections.emptyList(),
          mockStepContext,
          null,
          Collections.emptyMap(),
          WindowingStrategy.of(new GlobalWindows()),
          DoFnSchemaInformation.create(),
          Collections.emptyMap());

  runner.startBundle();
  // Outputting between "now" and "now - allowed skew" succeeds.
  runner.processElement(
      WindowedValue.timestampedValueInGlobalWindow(Duration.standardMinutes(5L), new Instant(0)));
  thrown.expect(UserCodeException.class);
  thrown.expectCause(isA(IllegalArgumentException.class));
  thrown.expectMessage("must be no earlier");
  thrown.expectMessage(
      String.format("timestamp of the current input (%s)", new Instant(0).toString()));
  thrown.expectMessage(
      String.format(
          "the allowed skew (%s)",
          PeriodFormat.getDefault().print(Duration.standardMinutes(10L).toPeriod())));
  // Outputting before "now - allowed skew" fails.
  runner.processElement(
      WindowedValue.timestampedValueInGlobalWindow(Duration.standardHours(1L), new Instant(0)));
}
 
Example #15
Source File: SimpleDoFnRunnerTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Demonstrates that attempting to output an element before the timestamp of the current element
 * with zero {@link DoFn#getAllowedTimestampSkew() allowed timestamp skew} throws.
 */
@Test
public void testBackwardsInTimeNoSkew() {
  SkewingDoFn fn = new SkewingDoFn(Duration.ZERO);
  DoFnRunner<Duration, Duration> runner =
      new SimpleDoFnRunner<>(
          null,
          fn,
          NullSideInputReader.empty(),
          new ListOutputManager(),
          new TupleTag<>(),
          Collections.emptyList(),
          mockStepContext,
          null,
          Collections.emptyMap(),
          WindowingStrategy.of(new GlobalWindows()),
          DoFnSchemaInformation.create(),
          Collections.emptyMap());

  runner.startBundle();
  // An element output at the current timestamp is fine.
  runner.processElement(
      WindowedValue.timestampedValueInGlobalWindow(Duration.ZERO, new Instant(0)));
  thrown.expect(UserCodeException.class);
  thrown.expectCause(isA(IllegalArgumentException.class));
  thrown.expectMessage("must be no earlier");
  thrown.expectMessage(
      String.format("timestamp of the current input (%s)", new Instant(0).toString()));
  thrown.expectMessage(
      String.format(
          "the allowed skew (%s)", PeriodFormat.getDefault().print(Duration.ZERO.toPeriod())));
  // An element output before (current time - skew) is forbidden
  runner.processElement(
      WindowedValue.timestampedValueInGlobalWindow(Duration.millis(1L), new Instant(0)));
}
 
Example #16
Source File: VirtualAssetPerformanceTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
private void pullSourceString(VirtualAsset virtualAsset, Repository repository) {
        repository.getRepositoryLocales().stream()
                .filter(rl -> rl.getParentLocale() == null)
                .forEach(rl -> {
                    logger.debug("root locale: {}", rl.getLocale().getBcp47Tag());
                    long start = System.currentTimeMillis();
                    List<VirtualAssetTextUnit> virtualAssetTextUnits = virtualAssetClient.getLocalizedTextUnits(virtualAsset.getId(), rl.getLocale().getId(), "REMOVE_UNTRANSLATED");
                    long end = System.currentTimeMillis();
                    logger.debug("file generation: {}", PeriodFormat.getDefault().print(new Period(start, end)));

//                    ObjectMapper objectMapper = new ObjectMapper();
//                    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
//                    logger.debug(objectMapper.writeValueAsStringUnchecked(virtualAssetTextUnits));
                });
    }
 
Example #17
Source File: Usage.java    From amforeas with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Calculates the time Amforeas has been running and returns a string representing it, i.e. 2 days 10 hours...
 * @return a string with the uptime.
 */
public String getUptime () {
    Period period = new Period(this.start, new DateTime());
    return PeriodFormat.getDefault().print(period);
}
 
Example #18
Source File: ValidationLogicImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String getFormattedExpirationMinutes() {
	int expirationMinutes = serverConfigurationService.getInt(MAX_PASSWORD_RESET_MINUTES, MAX_PASSWORD_RESET_MINUTES_DEFAULT);
	Period period = new Period(expirationMinutes * 60 * 1000);
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(rl.getLocale());
	return periodFormatter.print(period);
}
 
Example #19
Source File: FilePublisher.java    From kinesis-log4j-appender with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
  if (args.length != 1) {
    System.err.println("Usage: java " + FilePublisher.class.getName() + " <file_path>");
    System.err.println();
    System.err.println("<file_path>\t-\tabsolute path for the input file, this file will be read line by line and ");
    System.err.println("\t\t\tpublished to Kinesis");
    System.exit(1);
  }
  String fileAbsolutePath = args[0];
  File logFile = new File(fileAbsolutePath);
  if (!logFile.exists() || !logFile.canRead()) {
    System.err.println("File " + args[0] + " doesn't exist or is not readable.");
    System.exit(2);
  }

  Logger kinesisLogger = Logger.getLogger("KinesisLogger");
  int i = 0;
  DateTime startTime = DateTime.now();
  BufferedReader reader = new BufferedReader(new FileReader(logFile));
  LOGGER.info("Started reading: " + fileAbsolutePath);
  String line = null;
  while ((line = reader.readLine()) != null) {
    kinesisLogger.info(line);
    i++;
    if (i % 100 == 0 && LOGGER.isDebugEnabled()) {
      LOGGER.debug("Total " + i + " records written to logger");
    }
  }
  reader.close();
  long bufferedRecordsCount = getBufferedRecordsCountFromKinesisAppenders();
  while (bufferedRecordsCount > 0) {
    LOGGER.info("Publisher threads within log4j appender are still working on sending " + bufferedRecordsCount
        + " buffered records to Kinesis");
    try {
      Thread.sleep(SLEEP_INTERVAL);
    } catch (InterruptedException e) {
      // do nothing
    }
    bufferedRecordsCount = getBufferedRecordsCountFromKinesisAppenders();
  }
  LOGGER.info("Published " + i + " records from " + fileAbsolutePath + " to the logger, took "
      + PeriodFormat.getDefault().print(new Period(startTime, DateTime.now())));
}
 
Example #20
Source File: TimeValue.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public String format(PeriodType type) {
    Period period = new Period(millis());
    return PeriodFormat.getDefault().withParseType(type).print(period);
}
 
Example #21
Source File: UptimeMain.java    From cloudhopper-commons with Apache License 2.0 4 votes vote down vote up
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 #22
Source File: ValidationLogicImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String getFormattedExpirationMinutes() {
	int expirationMinutes = serverConfigurationService.getInt(MAX_PASSWORD_RESET_MINUTES, MAX_PASSWORD_RESET_MINUTES_DEFAULT);
	Period period = new Period(expirationMinutes * 60 * 1000);
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(rl.getLocale());
	return periodFormatter.print(period);
}
 
Example #23
Source File: ProfilingTimer.java    From Word2VecJava with MIT License 4 votes vote down vote up
/** @return a human-readable formatted string for the given amount of nanos */
private static String formatElapsed(long nanos) {
	return String.format("%s (%6.3g nanoseconds)",
			PeriodFormat.getDefault().print(Period.millis((int)(nanos / 1000))),
			(double) nanos);
}
 
Example #24
Source File: CassandraUtils.java    From sstable-tools with Apache License 2.0 4 votes vote down vote up
public static String toDurationString(long duration, TimeUnit unit, boolean color) {
    return wrapQuiet(PeriodFormat.getDefault().print(new Duration(unit.toMillis(duration)).toPeriod()), color);
}
 
Example #25
Source File: VirtualAssetPerformanceTest.java    From mojito with Apache License 2.0 4 votes vote down vote up
String getElapsedTime(PollableTask pollableTask) {
    Period period = new Period(pollableTask.getCreatedDate(), pollableTask.getFinishedDate());
    return PeriodFormat.getDefault().print(period);
}
 
Example #26
Source File: PasswordResetProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes	->	2 hours 2 minutes
 * 121 minutes	->	2 hours 1 minute
 * 120 minutes	->	2 hours
 * 62 minutes	->	1 hour 2 minutes
 * 61 minutes	->	1 hour 1 minute
 * 60 minutes	->	1 hour
 * 2 minutes	->	2 minutes
 * 1 minutes	->	1 minute
 * 0 minutes	->	0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}
 
Example #27
Source File: FormProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes  ->      2 hours 2 minutes
 * 121 minutes  ->      2 hours 1 minute
 * 120 minutes  ->      2 hours
 * 62 minutes   ->      1 hour 2 minutes
 * 61 minutes   ->      1 hour 1 minute
 * 60 minutes   ->      1 hour
 * 2 minutes    ->      2 minutes
 * 1 minutes    ->      1 minute
 * 0 minutes    ->      0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}
 
Example #28
Source File: FormProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes  ->      2 hours 2 minutes
 * 121 minutes  ->      2 hours 1 minute
 * 120 minutes  ->      2 hours
 * 62 minutes   ->      1 hour 2 minutes
 * 61 minutes   ->      1 hour 1 minute
 * 60 minutes   ->      1 hour
 * 2 minutes    ->      2 minutes
 * 1 minutes    ->      1 minute
 * 0 minutes    ->      0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}
 
Example #29
Source File: PasswordResetProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes	->	2 hours 2 minutes
 * 121 minutes	->	2 hours 1 minute
 * 120 minutes	->	2 hours
 * 62 minutes	->	1 hour 2 minutes
 * 61 minutes	->	1 hour 1 minute
 * 60 minutes	->	1 hour
 * 2 minutes	->	2 minutes
 * 1 minutes	->	1 minute
 * 0 minutes	->	0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}