Example usage for org.joda.time Duration Duration

List of usage examples for org.joda.time Duration Duration

Introduction

In this page you can find the example usage for org.joda.time Duration Duration.

Prototype

public Duration(Object duration) 

Source Link

Document

Creates a duration from the specified object using the org.joda.time.convert.ConverterManager ConverterManager .

Usage

From source file:com.google.cloud.pubsub.FakeScheduledExecutorService.java

License:Open Source License

@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
    return schedulePendingCallable(
            new PendingCallable<>(new Duration(unit.toMillis(delay)), command, PendingCallableType.NORMAL));
}

From source file:com.google.cloud.pubsub.FakeScheduledExecutorService.java

License:Open Source License

@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
    return schedulePendingCallable(
            new PendingCallable<>(new Duration(unit.toMillis(delay)), callable, PendingCallableType.NORMAL));
}

From source file:com.google.cloud.pubsub.FakeScheduledExecutorService.java

License:Open Source License

@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
    return schedulePendingCallable(new PendingCallable<>(new Duration(unit.toMillis(initialDelay)), command,
            PendingCallableType.FIXED_RATE));
}

From source file:com.google.cloud.pubsub.FakeScheduledExecutorService.java

License:Open Source License

@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
        TimeUnit unit) {//from  ww w .  j a va  2s  .c om
    return schedulePendingCallable(new PendingCallable<>(new Duration(unit.toMillis(initialDelay)), command,
            PendingCallableType.FIXED_DELAY));
}

From source file:com.google.cloud.pubsub.PublisherSamples.java

License:Open Source License

@SuppressWarnings("unchecked")
public void simplePublisher() throws Exception {
    Publisher publisher = Publisher.Builder.newBuilder(topic).setMaxBatchDuration(new Duration(500))
            .setMaxBatchBytes(1 * 1000 * 1000).setRequestTimeout(Duration.standardSeconds(60)).build();

    startTimeMs = System.currentTimeMillis();
    System.out.println("Publishing messages at " + startTimeMs + " ms.");

    List<ListenableFuture<String>> results = new ArrayList<>();

    for (int i = 0; i < 1000; ++i) {
        PubsubMessage message = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8("" + i)).build();
        results.add(publisher.publish(message));
    }/*from   ww w  .ja  v  a 2  s  .  c  o  m*/

    System.out.println("Batched messages in " + (System.currentTimeMillis() - startTimeMs) + " ms.");

    handleResults(results);

    publisher.shutdown();
}

From source file:com.google.gitiles.ConfigUtil.java

License:Open Source License

/**
 * Read a duration value from the configuration.
 * <p>//from  ww  w  .  j  a v  a2  s.c  o  m
 * Durations can be written as expressions, for example {@code "1 s"} or
 * {@code "5 days"}. If units are not specified, milliseconds are assumed.
 *
 * @param config JGit config object.
 * @param section section to read, e.g. "google"
 * @param subsection subsection to read, e.g. "bigtable"
 * @param name variable to read, e.g. "deadline".
 * @param defaultValue value to use when the value is not assigned.
 * @return a standard duration representing the time read, or defaultValue.
 */
public static Duration getDuration(Config config, String section, String subsection, String name,
        Duration defaultValue) {
    String valStr = config.getString(section, subsection, name);
    if (valStr == null) {
        return defaultValue;
    }

    valStr = valStr.trim();
    if (valStr.length() == 0) {
        return defaultValue;
    }

    Matcher m = matcher("^([1-9][0-9]*(?:\\.[0-9]*)?)\\s*(.*)$", valStr);
    if (!m.matches()) {
        String key = section + (subsection != null ? "." + subsection : "") + "." + name;
        throw new IllegalStateException("Not time unit: " + key + " = " + valStr);
    }

    String digits = m.group(1);
    String unitName = m.group(2).trim();

    TimeUnit unit;
    if ("".equals(unitName)) {
        unit = TimeUnit.MILLISECONDS;
    } else if (anyOf(unitName, "ms", "millis", "millisecond", "milliseconds")) {
        unit = TimeUnit.MILLISECONDS;
    } else if (anyOf(unitName, "s", "sec", "second", "seconds")) {
        unit = TimeUnit.SECONDS;
    } else if (anyOf(unitName, "m", "min", "minute", "minutes")) {
        unit = TimeUnit.MINUTES;
    } else if (anyOf(unitName, "h", "hr", "hour", "hours")) {
        unit = TimeUnit.HOURS;
    } else if (anyOf(unitName, "d", "day", "days")) {
        unit = TimeUnit.DAYS;
    } else {
        String key = section + (subsection != null ? "." + subsection : "") + "." + name;
        throw new IllegalStateException("Not time unit: " + key + " = " + valStr);
    }

    try {
        if (digits.indexOf('.') == -1) {
            long val = Long.parseLong(digits);
            return new Duration(val * TimeUnit.MILLISECONDS.convert(1, unit));
        } else {
            double val = Double.parseDouble(digits);
            return new Duration((long) (val * TimeUnit.MILLISECONDS.convert(1, unit)));
        }
    } catch (NumberFormatException nfe) {
        String key = section + (subsection != null ? "." + subsection : "") + "." + name;
        throw new IllegalStateException("Not time unit: " + key + " = " + valStr, nfe);
    }
}

From source file:com.helger.datetime.config.PDTTypeConverterRegistrar.java

License:Apache License

public void registerTypeConverter(@Nonnull final ITypeConverterRegistry aRegistry) {
    // Register Joda native converters
    _registerJodaConverter();//from w  ww.ja va  2  s. co  m

    final Class<?>[] aSourceClasses = new Class<?>[] { String.class, Calendar.class, GregorianCalendar.class,
            Date.class, AtomicInteger.class, AtomicLong.class, BigDecimal.class, BigInteger.class, Byte.class,
            Double.class, Float.class, Integer.class, Long.class, Short.class };

    // DateTime
    aRegistry.registerTypeConverter(aSourceClasses, DateTime.class, new ITypeConverter() {
        @Nonnull
        public DateTime convert(@Nonnull final Object aSource) {
            return new DateTime(aSource, PDTConfig.getDefaultChronology());
        }
    });
    aRegistry.registerTypeConverter(LocalDate.class, DateTime.class, new ITypeConverter() {
        @Nonnull
        public DateTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createDateTime((LocalDate) aSource);
        }
    });
    aRegistry.registerTypeConverter(LocalTime.class, DateTime.class, new ITypeConverter() {
        @Nonnull
        public DateTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createDateTime((LocalTime) aSource);
        }
    });
    aRegistry.registerTypeConverter(LocalDateTime.class, DateTime.class, new ITypeConverter() {
        @Nonnull
        public DateTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createDateTime((LocalDateTime) aSource);
        }
    });

    // LocalDateTime
    aRegistry.registerTypeConverter(aSourceClasses, LocalDateTime.class, new ITypeConverter() {
        @Nonnull
        public LocalDateTime convert(@Nonnull final Object aSource) {
            return new LocalDateTime(aSource, PDTConfig.getDefaultChronology());
        }
    });
    aRegistry.registerTypeConverter(DateTime.class, LocalDateTime.class, new ITypeConverter() {
        @Nonnull
        public LocalDateTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createLocalDateTime((DateTime) aSource);
        }
    });
    aRegistry.registerTypeConverter(LocalDate.class, LocalDateTime.class, new ITypeConverter() {
        @Nonnull
        public LocalDateTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createLocalDateTime((LocalDate) aSource);
        }
    });
    aRegistry.registerTypeConverter(LocalTime.class, LocalDateTime.class, new ITypeConverter() {
        @Nonnull
        public LocalDateTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createLocalDateTime((LocalTime) aSource);
        }
    });

    // LocalDate
    aRegistry.registerTypeConverter(aSourceClasses, LocalDate.class, new ITypeConverter() {
        @Nonnull
        public LocalDate convert(@Nonnull final Object aSource) {
            return new LocalDate(aSource, PDTConfig.getDefaultChronology());
        }
    });
    aRegistry.registerTypeConverter(DateTime.class, LocalDate.class, new ITypeConverter() {
        @Nonnull
        public LocalDate convert(@Nonnull final Object aSource) {
            return PDTFactory.createLocalDate((DateTime) aSource);
        }
    });
    aRegistry.registerTypeConverter(LocalDateTime.class, LocalDate.class, new ITypeConverter() {
        @Nonnull
        public LocalDate convert(@Nonnull final Object aSource) {
            return PDTFactory.createLocalDate((LocalDateTime) aSource);
        }
    });

    // LocalTime
    aRegistry.registerTypeConverter(aSourceClasses, LocalTime.class, new ITypeConverter() {
        @Nonnull
        public LocalTime convert(@Nonnull final Object aSource) {
            return new LocalTime(aSource, PDTConfig.getDefaultChronology());
        }
    });
    aRegistry.registerTypeConverter(DateTime.class, LocalTime.class, new ITypeConverter() {
        @Nonnull
        public LocalTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createLocalTime((DateTime) aSource);
        }
    });
    aRegistry.registerTypeConverter(LocalDateTime.class, LocalTime.class, new ITypeConverter() {
        @Nonnull
        public LocalTime convert(@Nonnull final Object aSource) {
            return PDTFactory.createLocalTime((LocalDateTime) aSource);
        }
    });

    // Duration
    aRegistry.registerTypeConverter(new Class<?>[] { String.class, AtomicInteger.class, AtomicLong.class,
            BigDecimal.class, BigInteger.class, Byte.class, Double.class, Float.class, Integer.class,
            Long.class, Short.class }, Duration.class, new ITypeConverter() {
                @Nonnull
                public Duration convert(@Nonnull final Object aSource) {
                    return new Duration(aSource);
                }
            });

    // Period
    aRegistry.registerTypeConverter(new Class<?>[] { String.class, AtomicInteger.class, AtomicLong.class,
            BigDecimal.class, BigInteger.class, Byte.class, Double.class, Float.class, Integer.class,
            Long.class, Short.class }, Period.class, new ITypeConverter() {
                @Nonnull
                public Period convert(@Nonnull final Object aSource) {
                    return new Period(aSource);
                }
            });

    // MutablePeriod
    aRegistry.registerTypeConverter(new Class<?>[] { String.class, AtomicInteger.class, AtomicLong.class,
            BigDecimal.class, BigInteger.class, Byte.class, Double.class, Float.class, Integer.class,
            Long.class, Short.class }, MutablePeriod.class, new ITypeConverter() {
                @Nonnull
                public MutablePeriod convert(@Nonnull final Object aSource) {
                    return new MutablePeriod(aSource);
                }
            });
}

From source file:com.helger.genetic.tsp.result.evaluation.MainTSPRunnerAll.java

License:Apache License

private static void _runAll(final int nCrossoverPerc, final int nMutationPerc, final int nSeconds,
        final boolean bUseMaxPopulationSize) throws Exception {
    final Map<String, ICrossover> cm = new LinkedHashMap<String, ICrossover>();
    cm.put("Cycle", new CrossoverCycle(new DecisionMakerPercentage(nCrossoverPerc)));
    cm.put("EdgeRecombination", new CrossoverEdgeRecombination(new DecisionMakerPercentage(nCrossoverPerc)));
    cm.put("OnePointInt", new CrossoverOnePointInt(new DecisionMakerPercentage(nCrossoverPerc)));
    cm.put("PartiallyMapped", new CrossoverPartiallyMapped(new DecisionMakerPercentage(nCrossoverPerc)));

    final Map<String, Class<? extends IMutation>> mm = new LinkedHashMap<String, Class<? extends IMutation>>();
    if (false)/*  w ww  .j a v a 2  s  .  c  o  m*/
        mm.put("RandomExchange", MutationRandomExchange.class);
    if (false)
        mm.put("RandomMoveMultiple", MutationRandomMoveMultiple.class);
    if (false)
        mm.put("RandomMoveSingle", MutationRandomMoveSingle.class);
    if (false)
        mm.put("RandomPartialReverse", MutationRandomPartialReverse.class);
    if (false)
        mm.put("TSPMutationGreedy", TSPMutationGreedy.class);
    mm.put("TSPMutationGreedyBeginning", TSPMutationGreedyBeginning.class);

    System.out.println("Running " + nCrossoverPerc + "-" + cm.keySet() + "-" + nMutationPerc + "-" + mm.keySet()
            + "-" + nSeconds + (bUseMaxPopulationSize ? "-maxpop" : ""));
    final int nEstimatedSeconds = 47 * REPEATS * nSeconds * cm.size() * mm.size();
    System.out
            .println("  Estimated end time: " + PDTFactory.getCurrentDateTime().plusSeconds(nEstimatedSeconds));

    for (final Map.Entry<String, ICrossover> aEntryC : cm.entrySet()) {
        final ICrossover aCrossover = aEntryC.getValue();
        System.out.println(aEntryC.getKey());

        for (final Map.Entry<String, Class<? extends IMutation>> aEntryM : mm.entrySet()) {
            final StopWatch aSW = StopWatch.createdStarted();
            System.out.println("  " + aEntryM.getKey());
            final Class<? extends IMutation> aMutationClass = aEntryM.getValue();

            final WorkbookCreationHelper aWCH = new WorkbookCreationHelper(EExcelVersion.XLSX);
            aWCH.createNewSheet("STW CT");
            aWCH.addRow();
            aWCH.addCell("TSP");
            aWCH.addCell("Stdte");
            aWCH.addCell("Optimum");
            aWCH.addCell("Population");
            for (int i = 0; i < REPEATS; ++i) {
                aWCH.addCell("Generation " + (i + 1));
                aWCH.addCell("Distanz " + (i + 1));
                aWCH.addCell("Prozent " + (i + 1));
            }

            final Font aFont = aWCH.getWorkbook().createFont();
            aFont.setFontName("Calibri");
            aFont.setFontHeightInPoints((short) 11);
            aFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

            for (final Map.Entry<String, Integer> aEntry : TSPLIST.entrySet())
                _runTSP(aEntry.getKey(), aEntry.getValue().intValue(), aWCH, bUseMaxPopulationSize, nSeconds,
                        aCrossover, aMutationClass, nMutationPerc);

            aWCH.autoFilterAllColumns();
            aWCH.autoSizeAllColumns();
            aWCH.write("data/all/search-" + aEntryC.getKey() + "-" + nCrossoverPerc + "-" + aEntryM.getKey()
                    + "-" + nMutationPerc + "-" + nSeconds + "secs" + (bUseMaxPopulationSize ? "-maxpop" : "")
                    + ".xlsx");
            System.out.println("    Took " + new Duration(aSW.stopAndGetMillis()).toString());
        }
    }
}

From source file:com.igormaznitsa.jute.Utils.java

License:Apache License

public static String printTimeDelay(final long timeInMilliseconds) {
    final Duration duration = new Duration(timeInMilliseconds);
    final Period period = duration.toPeriod().normalizedStandard(PeriodType.time());
    return TIME_FORMATTER.print(period);
}

From source file:com.interact.listen.gui.GetVoicemailListServlet.java

private String marshalVoicemail(Voicemail voicemail, Marshaller marshaller) {
    StringBuilder json = new StringBuilder();
    json.append("{");
    json.append("\"id\":").append(voicemail.getId()).append(",");
    json.append("\"isNew\":").append(voicemail.getIsNew()).append(",");

    String date = marshaller.convertAndEscape(Date.class, voicemail.getDateCreated());
    json.append("\"dateCreated\":\"").append(date).append("\",");

    String leftBy = marshaller.convertAndEscape(String.class, voicemail.friendlyFrom());
    json.append("\"leftBy\":\"").append(leftBy).append("\",");

    Duration duration = new Duration(Long.parseLong(voicemail.getDuration()));
    json.append("\"duration\":\"").append(DateUtil.printDuration(duration)).append("\",");

    json.append("\"uri\":\"").append(voicemail.mp3FileUri()).append("\",");

    json.append("\"transcription\":");
    if (voicemail.getTranscription() == null || voicemail.getTranscription().trim().equals("")) {
        json.append("null");
    } else {/*from  w  w  w. ja va2s .  c om*/
        String transcription = marshaller.convertAndEscape(String.class, voicemail.getTranscription());
        json.append("\"").append(transcription).append("\"");
    }

    json.append("}");
    return json.toString();
}