Java 类org.apache.commons.lang3.time.DurationFormatUtils 实例源码

项目:Shadbot    文件:ShardManager.java   
private static void check() {
    LogUtils.infof("Checking dead shards...");
    for(ShadbotShard shardStatus : SHARDS_MAP.values()) {
        try {
            // Ignore shards with less than 100 guilds
            if(shardStatus.getShard().getGuilds().size() < 100) {
                continue;
            }
            long lastEventTime = TimeUtils.getMillisUntil(shardStatus.getLastEventTime());
            long lastMessageTime = TimeUtils.getMillisUntil(shardStatus.getLastMessageTime());
            if(lastEventTime > TimeUnit.SECONDS.toMillis(SHARD_TIMEOUT) || lastMessageTime > TimeUnit.SECONDS.toMillis(SHARD_TIMEOUT)) {
                LogUtils.infof(String.format("Restarting shard %d (Response time: %d ms | Last event: %s ago | Last message: %s ago)",
                        shardStatus.getID(),
                        shardStatus.getShard().getResponseTime(),
                        DurationFormatUtils.formatDurationWords(lastEventTime, true, true),
                        DurationFormatUtils.formatDurationWords(lastMessageTime, true, true)));
                shardStatus.restart();
            }
        } catch (Exception err) {
            LogUtils.errorf(err, "An error occurred while restarting a shard.");
        }
    }
    LogUtils.infof("Dead shards checked.");
}
项目:HCFCore    文件:FactionListener.java   
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerPreFactionJoin(PlayerJoinFactionEvent event) {
    Faction faction = event.getFaction();
    Optional<Player> optionalPlayer = event.getPlayer();
    if (faction instanceof PlayerFaction && optionalPlayer.isPresent()) {
        Player player = optionalPlayer.get();
        PlayerFaction playerFaction = (PlayerFaction) faction;

        if (!plugin.getEotwHandler().isEndOfTheWorld() && playerFaction.getRegenStatus() == RegenStatus.PAUSED) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions that are not regenerating DTR.");
            return;
        }

        long difference = (plugin.getUserManager().getUser(player.getUniqueId()).getLastFactionLeaveMillis() - System.currentTimeMillis()) + FACTION_JOIN_WAIT_MILLIS;
        if (difference > 0L && !player.hasPermission("hcf.faction.argument.staff.forcejoin")) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions after just leaving within " + FACTION_JOIN_WAIT_WORDS + ". " + "You gotta wait another "
                    + DurationFormatUtils.formatDurationWords(difference, true, true) + '.');
        }
        UUID uuid = player.getUniqueId();
        HCF.getInstance().getUserManager().users.putIfAbsent(uuid, new FactionUser(uuid));
    }
}
项目:HCFCore    文件:EventUptimeArgument.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    EventTimer eventTimer = plugin.getTimerManager().getEventTimer();

    if (eventTimer.getRemaining() <= 0L) {
        sender.sendMessage(ChatColor.RED + "There is not a running event.");
        return true;
    }

    EventFaction eventFaction = eventTimer.getEventFaction();
    sender.sendMessage(ChatColor.YELLOW + "Up-time of " + eventTimer.getName() + " timer"
            + (eventFaction == null ? "" : ": " + ChatColor.BLUE + '(' + eventFaction.getDisplayName(sender) + ChatColor.BLUE + ')') + ChatColor.YELLOW + " is " + ChatColor.GRAY
            + DurationFormatUtils.formatDurationWords(eventTimer.getUptime(), true, true) + ChatColor.YELLOW + ", started at " + ChatColor.GOLD
            + DateTimeFormats.HR_MIN_AMPM_TIMEZONE.format(eventTimer.getStartStamp()) + ChatColor.YELLOW + '.');

    return true;
}
项目:HCFCore    文件:EventTimer.java   
/**
 * Handles the winner for this event.
 *
 * @param winner
 *            the {@link Player} that won
 */
public void handleWinner(Player winner) {
    if (this.eventFaction == null)
        return;

    PlayerFaction playerFaction = plugin.getFactionManager().getPlayerFaction(winner);
    Bukkit.broadcastMessage(ChatColor.GOLD + "[" + "WIN" + "] " + ChatColor.RED + winner.getName() + ChatColor.AQUA
            + ChatColor.YELLOW + " has captured " + ChatColor.RED + this.eventFaction.getName()
            + ChatColor.YELLOW + " after " + ChatColor.RED + DurationFormatUtils.formatDurationWords(getUptime(), true, true) + " of up-time" + ChatColor.YELLOW + '.');

    EventType eventType = this.eventFaction.getEventType();
    World world = winner.getWorld();
    Location location = winner.getLocation();
    EventKey eventKey = plugin.getKeyManager().getEventKey();
    Collection<Inventory> inventories = eventKey.getInventories(eventType);
    ItemStack keyStack = eventKey.getItemStack(new EventKey.EventKeyData(eventType, inventories.isEmpty() ? 1 : plugin.getRandom().nextInt(inventories.size()) + 1));
    Map<Integer, ItemStack> excess = winner.getInventory().addItem(keyStack, EventSignListener.getEventSign(eventFaction.getName(), winner.getName()));
    for (ItemStack entry : excess.values()) {
        world.dropItemNaturally(location, entry);
    }

    this.clearCooldown(); // must always be cooled last as this nulls some variables.
}
项目:HCFCore    文件:AssassinClass.java   
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.hasItem() && event.getItem().getType() == Material.GOLDEN_CARROT) {
        Player player = event.getPlayer();
        if (plugin.getPvpClassManager().getEquippedClass(player) == this) {
            long timestamp = cooldowns.get(player.getUniqueId());
            long millis = System.currentTimeMillis();
            long remaining = timestamp == cooldowns.getNoEntryValue() ? 0L : timestamp - millis;
            if (remaining > 0L) {
                player.sendMessage(ChatColor.RED + "Cooldown still for " + DurationFormatUtils.formatDurationWords(remaining, true, true) + ".");
                return;
            }

            cooldowns.put(player.getUniqueId(), millis + 15000L);
            plugin.getEffectRestorer().setRestoreEffect(player, new PotionEffect(PotionEffectType.SPEED, 100, 4));
            plugin.getEffectRestorer().setRestoreEffect(player, new PotionEffect(PotionEffectType.INVISIBILITY, 100, 0));
        }
    }
}
项目:HCFCore    文件:FactionStuckArgument.java   
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
    if(!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command is only executable by players.");
        return true;
    }
    final Player player = (Player) sender;
    if(player.getWorld().getEnvironment() != World.Environment.NORMAL) {
        sender.sendMessage(ChatColor.RED + "You can only use this command from the overworld.");
        return true;
    }
    if(plugin.getFactionManager().getFactionAt(((Player) sender).getLocation()) instanceof SpawnFaction){
        sender.sendMessage(ChatColor.RED + "You cannot " + label + " " + this.getName() + " inside of Spawn");
        return true;
    }
    final StuckTimer stuckTimer = this.plugin.getTimerManager().getStuckTimer();
    if(!stuckTimer.setCooldown(player, player.getUniqueId())) {
        sender.sendMessage(ChatColor.YELLOW + "Your " + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has a remaining " + ChatColor.LIGHT_PURPLE + DurationFormatUtils.formatDurationWords(stuckTimer.getRemaining(player), true, true)+ChatColor.YELLOW + '.');
        return true;
    }
    sender.sendMessage(ChatColor.YELLOW + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has started. " + "\nTeleportation will commence in " + ChatColor.LIGHT_PURPLE + DurationFormatter.getRemaining(stuckTimer.getRemaining(player), true, false) + ChatColor.YELLOW + ". " + "\nThis will cancel if you move more than " + 5 + " blocks.");
    return true;
}
项目:HCFCore    文件:LivesSetDeathbanTimeArgument.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (args.length < 2) {
        sender.sendMessage(ChatColor.RED + "Usage: " + getUsage(label));
        return true;
    }

    long duration = JavaUtils.parse(args[1]);

    if (duration == -1L) {
        sender.sendMessage(ChatColor.RED + "Invalid duration, use the correct format: 10m 1s");
        return true;
    }

    SettingsYML.DEFAULT_DEATHBAN_DURATION = duration;
    Command.broadcastCommandMessage(sender, ChatColor.RED + "Base death-ban time set to " + DurationFormatUtils.formatDurationWords(duration, true, true) + " (not including multipliers, etc).");

    return true;
}
项目:HCFCore    文件:FactionListener.java   
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerPreFactionJoin(PlayerJoinFactionEvent event) {
    Faction faction = event.getFaction();
    Optional<Player> optionalPlayer = event.getPlayer();
    if (faction instanceof PlayerFaction && optionalPlayer.isPresent()) {
        Player player = optionalPlayer.get();
        PlayerFaction playerFaction = (PlayerFaction) faction;

        if (!plugin.getEotwHandler().isEndOfTheWorld() && playerFaction.getRegenStatus() == RegenStatus.PAUSED) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions that are not regenerating DTR.");
            return;
        }

        long difference = (plugin.getUserManager().getUser(player.getUniqueId()).getLastFactionLeaveMillis() - System.currentTimeMillis()) + FACTION_JOIN_WAIT_MILLIS;
        if (difference > 0L && !player.hasPermission("hcf.faction.argument.staff.forcejoin")) {
            event.setCancelled(true);
            player.sendMessage(ChatColor.RED + "You cannot join factions after just leaving within " + FACTION_JOIN_WAIT_WORDS + ". " + "You gotta wait another "
                    + DurationFormatUtils.formatDurationWords(difference, true, true) + '.');
        }
    }
}
项目:HCFCore    文件:EventUptimeArgument.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    EventTimer eventTimer = plugin.getTimerManager().getEventTimer();

    if (eventTimer.getRemaining() <= 0L) {
        sender.sendMessage(ChatColor.RED + "There is not a running event.");
        return true;
    }

    EventFaction eventFaction = eventTimer.getEventFaction();
    sender.sendMessage(ChatColor.YELLOW + "Up-time of " + eventTimer.getName() + " timer"
            + (eventFaction == null ? "" : ": " + ChatColor.BLUE + '(' + eventFaction.getDisplayName(sender) + ChatColor.BLUE + ')') + ChatColor.YELLOW + " is " + ChatColor.GRAY
            + DurationFormatUtils.formatDurationWords(eventTimer.getUptime(), true, true) + ChatColor.YELLOW + ", started at " + ChatColor.GOLD
            + DateTimeFormats.HR_MIN_AMPM_TIMEZONE.format(eventTimer.getStartStamp()) + ChatColor.YELLOW + '.');

    return true;
}
项目:HCFCore    文件:EventTimer.java   
/**
 * Handles the winner for this event.
 *
 * @param winner
 *            the {@link Player} that won
 */
public void handleWinner(Player winner) {
    if (this.eventFaction == null)
        return;

    PlayerFaction playerFaction = plugin.getFactionManager().getPlayerFaction(winner);
    Bukkit.broadcastMessage(ChatColor.GOLD + "[" + "WIN" + "] " + ChatColor.RED + winner.getName() + ChatColor.AQUA
            + ChatColor.YELLOW + " has captured " + ChatColor.RED + this.eventFaction.getName()
            + ChatColor.YELLOW + " after " + ChatColor.RED + DurationFormatUtils.formatDurationWords(getUptime(), true, true) + " of up-time" + ChatColor.YELLOW + '.');

    EventType eventType = this.eventFaction.getEventType();
    World world = winner.getWorld();
    Location location = winner.getLocation();
    EventKey eventKey = plugin.getKeyManager().getEventKey();
    Collection<Inventory> inventories = eventKey.getInventories(eventType);
    ItemStack keyStack = eventKey.getItemStack(new EventKey.EventKeyData(eventType, inventories.isEmpty() ? 1 : plugin.getRandom().nextInt(inventories.size()) + 1));
    Map<Integer, ItemStack> excess = winner.getInventory().addItem(keyStack, EventSignListener.getEventSign(eventFaction.getName(), winner.getName()));
    for (ItemStack entry : excess.values()) {
        world.dropItemNaturally(location, entry);
    }

    this.clearCooldown(); // must always be cooled last as this nulls some variables.
}
项目:HCFCore    文件:AssassinClass.java   
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.hasItem() && event.getItem().getType() == Material.GOLDEN_CARROT) {
        Player player = event.getPlayer();
        if (plugin.getPvpClassManager().getEquippedClass(player) == this) {
            long timestamp = cooldowns.get(player.getUniqueId());
            long millis = System.currentTimeMillis();
            long remaining = timestamp == cooldowns.getNoEntryValue() ? 0L : timestamp - millis;
            if (remaining > 0L) {
                player.sendMessage(ChatColor.RED + "Cooldown still for " + DurationFormatUtils.formatDurationWords(remaining, true, true) + ".");
                return;
            }

            cooldowns.put(player.getUniqueId(), millis + 15000L);
            plugin.getEffectRestorer().setRestoreEffect(player, new PotionEffect(PotionEffectType.SPEED, 100, 4));
            plugin.getEffectRestorer().setRestoreEffect(player, new PotionEffect(PotionEffectType.INVISIBILITY, 100, 0));
        }
    }
}
项目:HCFCore    文件:FactionStuckArgument.java   
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
    if(!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command is only executable by players.");
        return true;
    }
    final Player player = (Player) sender;
    if(player.getWorld().getEnvironment() != World.Environment.NORMAL) {
        sender.sendMessage(ChatColor.RED + "You can only use this command from the overworld.");
        return true;
    }
    if(plugin.getFactionManager().getFactionAt(((Player) sender).getLocation()) instanceof SpawnFaction){
        sender.sendMessage(ChatColor.RED + "You cannot " + label + " " + this.getName() + " inside of Spawn");
        return true;
    }
    final StuckTimer stuckTimer = this.plugin.getTimerManager().getStuckTimer();
    if(!stuckTimer.setCooldown(player, player.getUniqueId())) {
        sender.sendMessage(ChatColor.YELLOW + "Your " + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has a remaining " + ChatColor.LIGHT_PURPLE + DurationFormatUtils.formatDurationWords(stuckTimer.getRemaining(player), true, true)+ChatColor.YELLOW + '.');
        return true;
    }
    sender.sendMessage(ChatColor.YELLOW + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has started. " + "\nTeleportation will commence in " + ChatColor.LIGHT_PURPLE + DurationFormatter.getRemaining(stuckTimer.getRemaining(player), true, false) + ChatColor.YELLOW + ". " + "\nThis will cancel if you move more than " + 5 + " blocks.");
    return true;
}
项目:HCFCore    文件:LivesSetDeathbanTimeArgument.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (args.length < 2) {
        sender.sendMessage(ChatColor.RED + "Usage: " + getUsage(label));
        return true;
    }

    long duration = JavaUtils.parse(args[1]);

    if (duration == -1L) {
        sender.sendMessage(ChatColor.RED + "Invalid duration, use the correct format: 10m 1s");
        return true;
    }

    SettingsYML.DEFAULT_DEATHBAN_DURATION = duration;
    Command.broadcastCommandMessage(sender, ChatColor.RED + "Base death-ban time set to " + DurationFormatUtils.formatDurationWords(duration, true, true) + " (not including multipliers, etc).");

    return true;
}
项目:plugin-bt-jira    文件:AbstractCsvOutput.java   
/**
 * Write a duration using the "HH:mm:ss" format and in millisecond format, so 2 strings are added in the CSV output.
 * <code>null</code> management is performed there.
 * Empty {@link String} is written with <code>null</code> duration.
 * 
 * @param writer
 *            The target output.
 * @param duration
 *            The duration to write, in milliseconds.
 */
protected void writeDuration(final Writer writer, final Long duration) throws IOException {
    if (duration == null) {
        // null duration
        writer.write(";;");
    } else {
        writer.write(';');
        if (duration < 0) {
            // Add the sign before the HMS value
            writer.write('-');
        }
        writer.write(DurationFormatUtils.formatDuration(Math.abs(duration), "HH:mm:ss"));
        writer.write(';');
        writer.write(String.valueOf(duration));
    }
}
项目:Mastering-Mesos    文件:SingularityMailer.java   
private void prepareRequestInCooldownMail(SingularityRequest request) {
  final List<SingularityEmailDestination> emailDestination = getDestination(request, SingularityEmailType.REQUEST_IN_COOLDOWN);

  if (emailDestination.isEmpty()) {
    LOG.debug("Not configured to send request cooldown mail for");
    return;
  }

  final Map<String, Object> templateProperties = Maps.newHashMap();
  populateRequestEmailProperties(templateProperties, request);

  final String subject = String.format("Request %s has entered system cooldown — Singularity", request.getId());

  templateProperties.put("numFailures", configuration.getCooldownAfterFailures());
  templateProperties.put("cooldownDelayFormat", DurationFormatUtils.formatDurationHMS(TimeUnit.SECONDS.toMillis(configuration.getCooldownMinScheduleSeconds())));
  templateProperties.put("cooldownExpiresFormat", DurationFormatUtils.formatDurationHMS(TimeUnit.MINUTES.toMillis(configuration.getCooldownExpiresAfterMinutes())));

  final String body = Jade4J.render(requestInCooldownTemplate, templateProperties);

  queueMail(emailDestination, request, SingularityEmailType.REQUEST_IN_COOLDOWN, Optional.<String> absent(), subject, body);
}
项目:Mastering-Mesos    文件:SingularityDeployChecker.java   
private boolean isDeployOverdue(SingularityPendingDeploy pendingDeploy, Optional<SingularityDeploy> deploy) {
  if (!deploy.isPresent()) {
    LOG.warn("Can't determine if deploy {} is overdue because it was missing", pendingDeploy);
    return false;
  }

  if (pendingDeploy.getDeployProgress().isPresent() && pendingDeploy.getDeployProgress().get().isStepComplete()) {
    return false;
  }

  final long startTime = getStartTime(pendingDeploy);

  final long deployDuration = System.currentTimeMillis() - startTime;

  final long allowedTime = getAllowedMillis(deploy.get());

  if (deployDuration > allowedTime) {
    LOG.warn("Deploy {} is overdue (duration: {}), allowed: {}", pendingDeploy, DurationFormatUtils.formatDurationHMS(deployDuration), DurationFormatUtils.formatDurationHMS(allowedTime));

    return true;
  } else {
    LOG.trace("Deploy {} is not yet overdue (duration: {}), allowed: {}", pendingDeploy, DurationFormatUtils.formatDurationHMS(deployDuration), DurationFormatUtils.formatDurationHMS(allowedTime));

    return false;
  }
}
项目:Mastering-Mesos    文件:SingularityHealthchecker.java   
private ScheduledFuture<?> enqueueHealthcheckWithDelay(final SingularityTask task, long delaySeconds) {
  LOG.trace("Enqueuing a healthcheck for task {} with delay {}", task.getTaskId(), DurationFormatUtils.formatDurationHMS(TimeUnit.SECONDS.toMillis(delaySeconds)));

  return executorService.schedule(new Runnable() {

    @Override
    public void run() {
      try {
        asyncHealthcheck(task);
      } catch (Throwable t) {
        LOG.error("Uncaught throwable in async healthcheck", t);
        exceptionNotifier.notify(t, ImmutableMap.of("taskId", task.getTaskId().toString()));

        reEnqueueOrAbort(task);
      }
    }

  }, delaySeconds, TimeUnit.SECONDS);
}
项目:tenorite    文件:TempoController.java   
@RequestMapping("/t/{tempo}/m/{mode}/players/{name}")
public ModelAndView player(@PathVariable("tempo") Tempo tempo, @PathVariable("mode") String mode, @PathVariable("name") String name) {
    GameMode gameMode = gameModes.find(GameModeId.of(mode)).orElseThrow(NotAvailableException::new);

    PlayerStats playerStats = playerStatsRepository.playerStatsOps(tempo).playerStats(gameMode.getId(), name).orElseGet(() -> PlayerStats.of(gameMode.getId(), name));
    Map<Badge, BadgeLevel> badgeLevels = badgeRepository.badgeOps(tempo).badgeLevels(gameMode.getId(), name);

    Function<Long, String> x = m -> DurationFormatUtils.formatDurationWords(m, true, false);

    return
        new ModelAndView("player")
            .addObject("tempo", tempo)
            .addObject("name", name)
            .addObject("gameMode", gameMode)
            .addObject("gameModes", gameModes)
            .addObject("stats", playerStats)
            .addObject("badges", gameMode.getBadges())
            .addObject("badgeLevels", badgeLevels)
            .addObject("durationFormatter", x)
        ;
}
项目:engerek    文件:SimpleWorkflowNotifier.java   
private void appendDeadlineInformation(StringBuilder sb, WorkItemEvent event) {
    WorkItemType workItem = event.getWorkItem();
    if (!isDone(event) && workItem.getDeadline() != null) {
        XMLGregorianCalendar deadline = workItem.getDeadline();
        long before = XmlTypeConverter.toMillis(deadline) - System.currentTimeMillis();
        long beforeRounded = Math.round((double) before / 60000.0) * 60000L;
        String beforeWords = DurationFormatUtils.formatDurationWords(Math.abs(beforeRounded), true, true);
        String beforePhrase;
        if (beforeRounded > 0) {
            beforePhrase = " (in " + beforeWords + ")";
        } else if (beforeRounded < 0) {
            beforePhrase = " (" + beforeWords + " ago)";
        } else {
            beforePhrase = "";
        }
        sb.append("Deadline: ").append(textFormatter.formatDateTime(deadline)).append(beforePhrase).append("\n");
        sb.append("\n");
    }
}
项目:neo4j-json-loader    文件:DomainBasedAmbumMiniJsonTransformerTest.java   
@Test
public void testMini() throws Exception {
    String content = IOUtils.toString(getClass().getResourceAsStream("/json/album-mini.json"));
    String id = String.valueOf(System.currentTimeMillis());
    String type = "Album";
    List<JsonObjectDescriptor> descriptors = new ArrayList<>();
    descriptors.add(new JsonObjectDescriptor(type, Arrays.asList("id", "type"), "type"));
    JsonDocument jsonDocument = new JsonDocument(id, type, content, JsonMappingStrategy.DOMAIN_DRIVEN, descriptors);
    DomainDrivenJsonTransformer transformer = new DomainDrivenJsonTransformer();
    long start = System.currentTimeMillis();
    String transformedSet = transformer.transform(jsonDocument);
    long end = System.currentTimeMillis();
    System.out.println("---------RESULT---------");
    System.out.println(transformedSet);
    System.out.println("Time elapsed: " + DurationFormatUtils.formatDurationHMS(end - start));
}
项目:neo4j-json-loader    文件:DomainBasedAmbumMiniJsonTransformerTest.java   
@Test
public void testFull() throws Exception {
    String content = IOUtils.toString(getClass().getResourceAsStream("/json/album.json"));
    String id = String.valueOf(System.currentTimeMillis());
    String type = "Album";
    List<JsonObjectDescriptor> descriptors = new ArrayList<>();
    descriptors.add(new JsonObjectDescriptor(type, Arrays.asList("id", "type"), "type"));
    JsonDocument jsonDocument = new JsonDocument(id, type, content, JsonMappingStrategy.DOMAIN_DRIVEN, descriptors);
    DomainDrivenJsonTransformer transformer = new DomainDrivenJsonTransformer();
    long start = System.currentTimeMillis();
    String transformedSet = transformer.transform(jsonDocument);
    long end = System.currentTimeMillis();
    System.out.println("---------RESULT---------");
    System.out.println(transformedSet);
    System.out.println("Time elapsed: " + DurationFormatUtils.formatDurationHMS(end - start));
}
项目:neo4j-json-loader    文件:NodeJsonTransformerTest.java   
@Test
public void testMini() throws Exception {
    String content = IOUtils.toString(getClass().getResourceAsStream("/json/album-mini.json"));
    String id = String.valueOf(System.currentTimeMillis());
    String type = "Album";
    List<JsonObjectDescriptor> descriptors = new ArrayList<>();
    descriptors.add(new JsonObjectDescriptor(type, Arrays.asList("id", "type"), "type"));
    JsonDocument jsonDocument = new JsonDocument(id, type, content, JsonMappingStrategy.DOMAIN_DRIVEN, descriptors);
    DomainDrivenJsonTransformer transformer = new DomainDrivenJsonTransformer();
    long start = System.currentTimeMillis();
    String transformedSet = transformer.transform(jsonDocument);
    long end = System.currentTimeMillis();
    System.out.println("---------RESULT---------");
    System.out.println(transformedSet);
    System.out.println("Time elapsed: " + DurationFormatUtils.formatDurationHMS(end - start));
}
项目:neo4j-json-loader    文件:NodeJsonTransformerTest.java   
@Test
public void testFull() throws Exception {
    String content = IOUtils.toString(getClass().getResourceAsStream("/json/album.json"));
    String id = String.valueOf(System.currentTimeMillis());
    String type = "Album";
    List<JsonObjectDescriptor> descriptors = new ArrayList<>();
    descriptors.add(new JsonObjectDescriptor(type, Arrays.asList("id", "type"), "type"));
    JsonDocument jsonDocument = new JsonDocument(id, type, content, JsonMappingStrategy.DOMAIN_DRIVEN, descriptors);
    DomainDrivenJsonTransformer transformer = new DomainDrivenJsonTransformer();
    long start = System.currentTimeMillis();
    String transformedSet = transformer.transform(jsonDocument);
    long end = System.currentTimeMillis();
    System.out.println("---------RESULT---------");
    System.out.println(transformedSet);
    System.out.println("Time elapsed: " + DurationFormatUtils.formatDurationHMS(end - start));
}
项目:dhis2-core    文件:Clock.java   
/**
 * Timestamps the given message using the elapsed time of this Clock and
 * logs it using the logger.
 * @param message the message to log.
 * @return this Clock.
 */
public Clock logTime( String message )
{
    super.split();

    String time = DurationFormatUtils.formatDurationHMS( super.getSplitTime() ); 

    String msg = message + SEPARATOR + time;

    if ( log != null )
    {
        log.info( msg );
    }
    else
    {
        defaultLog.info( msg );
    }

    return this;
}
项目:cassandra-kmean    文件:StressMetrics.java   
public void summarise()
{
    output.println("\n");
    output.println("Results:");

    TimingIntervals opHistory = timing.getHistory();
    TimingInterval history = opHistory.combine(settings.samples.historyCount);
    output.println(String.format("op rate                   : %.0f %s", history.opRate(), opHistory.opRates()));
    output.println(String.format("partition rate            : %.0f %s", history.partitionRate(), opHistory.partitionRates()));
    output.println(String.format("row rate                  : %.0f %s", history.rowRate(), opHistory.rowRates()));
    output.println(String.format("latency mean              : %.1f %s", history.meanLatency(), opHistory.meanLatencies()));
    output.println(String.format("latency median            : %.1f %s", history.medianLatency(), opHistory.medianLatencies()));
    output.println(String.format("latency 95th percentile   : %.1f %s", history.rankLatency(.95f), opHistory.rankLatencies(0.95f)));
    output.println(String.format("latency 99th percentile   : %.1f %s", history.rankLatency(0.99f), opHistory.rankLatencies(0.99f)));
    output.println(String.format("latency 99.9th percentile : %.1f %s", history.rankLatency(0.999f), opHistory.rankLatencies(0.999f)));
    output.println(String.format("latency max               : %.1f %s", history.maxLatency(), opHistory.maxLatencies()));
    output.println(String.format("Total partitions          : %d %s",   history.partitionCount, opHistory.partitionCounts()));
    output.println(String.format("Total errors              : %d %s",   history.errorCount, opHistory.errorCounts()));
    output.println(String.format("total gc count            : %.0f", totalGcStats.count));
    output.println(String.format("total gc mb               : %.0f", totalGcStats.bytes / (1 << 20)));
    output.println(String.format("total gc time (s)         : %.0f", totalGcStats.summs / 1000));
    output.println(String.format("avg gc time(ms)           : %.0f", totalGcStats.summs / totalGcStats.count));
    output.println(String.format("stdev gc time(ms)         : %.0f", totalGcStats.sdvms));
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
            history.runTime(), "HH:mm:ss", true));
}
项目:SuperJump    文件:Battle.java   
@Override
protected void applyRatingChange(SJPlayer winner) {
    int winnerPoints = 0;
    final int MIN_RATING = 1, MAX_RATING = 40;
    String playerList = "";
    for (SJPlayer sjp : players) {
        if (sjp != winner) {
            float elo = (float) (1f / (1f + Math.pow(2f, ((sjp.getRating() - winner.getRating()) / 250f))));
            int rating = (int) Math.round(MAX_RATING * (1f - elo));
            if (rating < MIN_RATING) {
                rating = MIN_RATING;
            }
            winnerPoints += rating;
            sjp.setRating(sjp.getRating() - rating);
            SpleefLeague.getInstance().getPlayerManager().get(sjp).changeCoins(1);
            playerList += ChatColor.RED + sjp.getName() + ChatColor.WHITE + " (" + sjp.getRating() + ")" + ChatColor.GREEN + " loses " + ChatColor.GRAY + (rating) + ChatColor.WHITE + (-rating == 1 ? " point. " : " points.");
        }
    }
    winner.setRating(winner.getRating() + winnerPoints);
    SpleefLeague.getInstance().getPlayerManager().get(winner).changeCoins(2);
    playerList += ChatColor.RED + winner.getName() + ChatColor.WHITE + " (" + winner.getRating() + ")" + ChatColor.GREEN + " gets " + ChatColor.GRAY + winnerPoints + ChatColor.WHITE + (winnerPoints == 1 ? " point. " : " points. ");
    ChatManager.sendMessage(SuperJump.getInstance().getChatPrefix(), ChatColor.GREEN + "Game in arena " + ChatColor.WHITE + arena.getName() + ChatColor.GREEN + " is over " + ChatColor.WHITE + "(" + DurationFormatUtils.formatDuration(ticksPassed * 50, "HH:mm:ss", true) + ")" + ChatColor.GREEN + ". " + playerList, SuperJump.getInstance().getEndMessageChannel());
    this.players.forEach((p) -> {
        SuperJump.getInstance().getPlayerManager().save(p);
    });
}
项目:hawkbit    文件:SPDateTimeUtil.java   
/**
 * Creates a formatted string of a duration in format '1 year 2 months 3
 * days 4 hours 5 minutes 6 seconds' zero values will be ignored in the
 * formatted string.
 *
 * @param startMillis
 *            the start milliseconds of the duration
 * @param endMillis
 *            the end milliseconds of the duration
 * @param i18N
 *            the i18n service to determine the correct string for e.g.
 *            'year'
 * @return a formatted string for duration label
 */
public static String getDurationFormattedString(final long startMillis, final long endMillis,
        final VaadinMessageSource i18N) {
    final String formatDuration = DurationFormatUtils.formatPeriod(startMillis, endMillis, DURATION_FORMAT, false,
            getBrowserTimeZone());

    final StringBuilder formattedDuration = new StringBuilder();
    final String[] split = formatDuration.split(",");

    for (int index = 0; index < split.length; index++) {
        if (index != 0 && formattedDuration.length() > 0) {
            formattedDuration.append(' ');
        }
        final int value = Integer.parseInt(split[index]);
        if (value != 0) {
            final String suffix = (value == 1) ? i18N.getMessage(DURATION_I18N.get(index).getSingle())
                    : i18N.getMessage(DURATION_I18N.get(index).getPlural());
            formattedDuration.append(value).append(' ').append(suffix);
        }

    }
    return formattedDuration.toString();

}
项目:fim    文件:StateGenerator.java   
protected void displayStatistics(long duration, int fileCount, long filesContentLength, long totalBytesHashed) {
    String totalFileContentLengthStr = byteCountToDisplaySize(filesContentLength);
    String totalBytesHashedStr = byteCountToDisplaySize(totalBytesHashed);
    String durationStr = DurationFormatUtils.formatDuration(duration, "HH:mm:ss");

    long durationSeconds = duration / 1000;
    if (durationSeconds <= 0) {
        durationSeconds = 1;
    }

    long globalThroughput = totalBytesHashed / durationSeconds;
    String throughputStr = byteCountToDisplaySize(globalThroughput);

    String usingThreads = "";
    if (context.isDynamicScaling()) {
        usingThreads = String.format(", using %d %s", context.getThreadCount(), plural("thread", context.getThreadCount()));
    }

    if (context.getHashMode() == dontHash) {
        Logger.info(String.format("Scanned %d %s (%s)%s, during %s%n",
            fileCount, plural("file", fileCount), totalFileContentLengthStr, usingThreads, durationStr));
    } else {
        Logger.info(String.format("Scanned %d %s (%s)%s, hashed %s (avg %s/s), during %s%n",
            fileCount, plural("file", fileCount), totalFileContentLengthStr, usingThreads, totalBytesHashedStr, throughputStr, durationStr));
    }
}
项目:ACaZoo    文件:StressStatistics.java   
public void printStats()
{
    output.println("\n");
    if (tallyOpRateCount > 0) {
        output.println("Averages from the middle 80% of values:");
        output.println(String.format("interval_op_rate          : %d", 
                                     (tallyOpRateSum / tallyOpRateCount)));
        output.println(String.format("interval_key_rate         : %d", 
                                     (tallyKeyRateSum / tallyKeyRateCount)));
        output.println(String.format("latency median            : %.1f", 
                                     (tallyLatencySum / tallyLatencyCount)));
        output.println(String.format("latency 95th percentile   : %.1f",
                                     (tally95thLatencySum / tally95thLatencyCount)));
        output.println(String.format("latency 99.9th percentile : %.1f", 
                                     (tally999thLatencySum / tally999thLatencyCount)));
    }
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
        durationInSeconds*1000, "HH:mm:ss", true));
}
项目:AgileAlligators    文件:Clock.java   
/**
 * Timestamps the given message using the elapsed time of this Clock and
 * logs it using the logger.
 * @param message the message to log.
 * @return this Clock.
 */
public Clock logTime( String message )
{
    super.split();

    String time = DurationFormatUtils.formatDurationHMS( super.getSplitTime() ); 

    String msg = message + SEPARATOR + time;

    if ( log != null )
    {
        log.info( msg );
    }
    else
    {
        defaultLog.info( msg );
    }

    return this;
}
项目:scylla-tools-java    文件:StressMetrics.java   
public void summarise()
{
    output.println("\n");
    output.println("Results:");

    TimingIntervals opHistory = timing.getHistory();
    TimingInterval history = opHistory.combine(settings.samples.historyCount);
    output.println(String.format("op rate                   : %.0f %s", history.opRate(), opHistory.opRates()));
    output.println(String.format("partition rate            : %.0f %s", history.partitionRate(), opHistory.partitionRates()));
    output.println(String.format("row rate                  : %.0f %s", history.rowRate(), opHistory.rowRates()));
    output.println(String.format("latency mean              : %.1f %s", history.meanLatency(), opHistory.meanLatencies()));
    output.println(String.format("latency median            : %.1f %s", history.medianLatency(), opHistory.medianLatencies()));
    output.println(String.format("latency 95th percentile   : %.1f %s", history.rankLatency(.95f), opHistory.rankLatencies(0.95f)));
    output.println(String.format("latency 99th percentile   : %.1f %s", history.rankLatency(0.99f), opHistory.rankLatencies(0.99f)));
    output.println(String.format("latency 99.9th percentile : %.1f %s", history.rankLatency(0.999f), opHistory.rankLatencies(0.999f)));
    output.println(String.format("latency max               : %.1f %s", history.maxLatency(), opHistory.maxLatencies()));
    output.println(String.format("Total partitions          : %d %s",   history.partitionCount, opHistory.partitionCounts()));
    output.println(String.format("Total errors              : %d %s",   history.errorCount, opHistory.errorCounts()));
    output.println(String.format("total gc count            : %.0f", totalGcStats.count));
    output.println(String.format("total gc mb               : %.0f", totalGcStats.bytes / (1 << 20)));
    output.println(String.format("total gc time (s)         : %.0f", totalGcStats.summs / 1000));
    output.println(String.format("avg gc time(ms)           : %.0f", totalGcStats.summs / totalGcStats.count));
    output.println(String.format("stdev gc time(ms)         : %.0f", totalGcStats.sdvms));
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
            history.runTime(), "HH:mm:ss", true));
}
项目:midpoint    文件:SimpleWorkflowNotifier.java   
private void appendDeadlineInformation(StringBuilder sb, WorkItemEvent event) {
    WorkItemType workItem = event.getWorkItem();
    if (!isDone(event) && workItem.getDeadline() != null) {
        XMLGregorianCalendar deadline = workItem.getDeadline();
        long before = XmlTypeConverter.toMillis(deadline) - System.currentTimeMillis();
        long beforeRounded = Math.round((double) before / 60000.0) * 60000L;
        String beforeWords = DurationFormatUtils.formatDurationWords(Math.abs(beforeRounded), true, true);
        String beforePhrase;
        if (beforeRounded > 0) {
            beforePhrase = " (in " + beforeWords + ")";
        } else if (beforeRounded < 0) {
            beforePhrase = " (" + beforeWords + " ago)";
        } else {
            beforePhrase = "";
        }
        sb.append("Deadline: ").append(textFormatter.formatDateTime(deadline)).append(beforePhrase).append("\n");
        sb.append("\n");
    }
}
项目:GraphTrek    文件:StressMetrics.java   
public void summarise()
{
    output.println("\n");
    output.println("Results:");
    TimingInterval history = timing.getHistory();
    output.println(String.format("op rate                   : %.0f", history.opRate()));
    output.println(String.format("partition rate            : %.0f", history.partitionRate()));
    output.println(String.format("row rate                  : %.0f", history.rowRate()));
    output.println(String.format("latency mean              : %.1f", history.meanLatency()));
    output.println(String.format("latency median            : %.1f", history.medianLatency()));
    output.println(String.format("latency 95th percentile   : %.1f", history.rankLatency(.95f)));
    output.println(String.format("latency 99th percentile   : %.1f", history.rankLatency(0.99f)));
    output.println(String.format("latency 99.9th percentile : %.1f", history.rankLatency(0.999f)));
    output.println(String.format("latency max               : %.1f", history.maxLatency()));
    output.println(String.format("total gc count            : %.0f", totalGcStats.count));
    output.println(String.format("total gc mb               : %.0f", totalGcStats.bytes / (1 << 20)));
    output.println(String.format("total gc time (s)         : %.0f", totalGcStats.summs / 1000));
    output.println(String.format("avg gc time(ms)           : %.0f", totalGcStats.summs / totalGcStats.count));
    output.println(String.format("stdev gc time(ms)         : %.0f", totalGcStats.sdvms));
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
            history.runTime(), "HH:mm:ss", true));
}
项目:stratio-cassandra    文件:StressMetrics.java   
public void summarise()
{
    output.println("\n");
    output.println("Results:");

    TimingIntervals opHistory = timing.getHistory();
    TimingInterval history = opHistory.combine(settings.samples.historyCount);
    output.println(String.format("op rate                   : %.0f %s", history.opRate(), opHistory.opRates()));
    output.println(String.format("partition rate            : %.0f %s", history.partitionRate(), opHistory.partitionRates()));
    output.println(String.format("row rate                  : %.0f %s", history.rowRate(), opHistory.rowRates()));
    output.println(String.format("latency mean              : %.1f %s", history.meanLatency(), opHistory.meanLatencies()));
    output.println(String.format("latency median            : %.1f %s", history.medianLatency(), opHistory.medianLatencies()));
    output.println(String.format("latency 95th percentile   : %.1f %s", history.rankLatency(.95f), opHistory.rankLatencies(0.95f)));
    output.println(String.format("latency 99th percentile   : %.1f %s", history.rankLatency(0.99f), opHistory.rankLatencies(0.99f)));
    output.println(String.format("latency 99.9th percentile : %.1f %s", history.rankLatency(0.999f), opHistory.rankLatencies(0.999f)));
    output.println(String.format("latency max               : %.1f %s", history.maxLatency(), opHistory.maxLatencies()));
    output.println(String.format("Total partitions          : %d %s",   history.partitionCount, opHistory.partitionCounts()));
    output.println(String.format("Total errors              : %d %s",   history.errorCount, opHistory.errorCounts()));
    output.println(String.format("total gc count            : %.0f", totalGcStats.count));
    output.println(String.format("total gc mb               : %.0f", totalGcStats.bytes / (1 << 20)));
    output.println(String.format("total gc time (s)         : %.0f", totalGcStats.summs / 1000));
    output.println(String.format("avg gc time(ms)           : %.0f", totalGcStats.summs / totalGcStats.count));
    output.println(String.format("stdev gc time(ms)         : %.0f", totalGcStats.sdvms));
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
            history.runTime(), "HH:mm:ss", true));
}
项目:cassandra-cqlMod    文件:StressMetrics.java   
public void summarise()
{
    output.println("\n");
    output.println("Results:");
    TimingInterval history = timing.getHistory();
    output.println(String.format("real op rate              : %.0f", history.realOpRate()));
    output.println(String.format("adjusted op rate          : %.0f", history.adjustedOpRate()));
    output.println(String.format("adjusted op rate stderr   : %.0f", opRateUncertainty.getUncertainty()));
    output.println(String.format("key rate                  : %.0f", history.keyRate()));
    output.println(String.format("latency mean              : %.1f", history.meanLatency()));
    output.println(String.format("latency median            : %.1f", history.medianLatency()));
    output.println(String.format("latency 95th percentile   : %.1f", history.rankLatency(.95f)));
    output.println(String.format("latency 99th percentile   : %.1f", history.rankLatency(0.99f)));
    output.println(String.format("latency 99.9th percentile : %.1f", history.rankLatency(0.999f)));
    output.println(String.format("latency max               : %.1f", history.maxLatency()));
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
            history.runTime(), "HH:mm:ss", true));
}
项目:cassandra-trunk    文件:StressMetrics.java   
public void summarise()
{
    output.println("\n");
    output.println("Results:");
    TimingInterval history = timing.getHistory();
    output.println(String.format("real op rate              : %.0f", history.realOpRate()));
    output.println(String.format("adjusted op rate stderr   : %.0f", opRateUncertainty.getUncertainty()));
    output.println(String.format("key rate                  : %.0f", history.keyRate()));
    output.println(String.format("latency mean              : %.1f", history.meanLatency()));
    output.println(String.format("latency median            : %.1f", history.medianLatency()));
    output.println(String.format("latency 95th percentile   : %.1f", history.rankLatency(.95f)));
    output.println(String.format("latency 99th percentile   : %.1f", history.rankLatency(0.99f)));
    output.println(String.format("latency 99.9th percentile : %.1f", history.rankLatency(0.999f)));
    output.println(String.format("latency max               : %.1f", history.maxLatency()));
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
            history.runTime(), "HH:mm:ss", true));
}
项目:midpoint    文件:SimpleWorkflowNotifier.java   
private void appendDeadlineInformation(StringBuilder sb, WorkItemEvent event) {
    WorkItemType workItem = event.getWorkItem();
    if (!isDone(event) && workItem.getDeadline() != null) {
        XMLGregorianCalendar deadline = workItem.getDeadline();
        long before = XmlTypeConverter.toMillis(deadline) - System.currentTimeMillis();
        long beforeRounded = Math.round((double) before / 60000.0) * 60000L;
        String beforeWords = DurationFormatUtils.formatDurationWords(Math.abs(beforeRounded), true, true);
        String beforePhrase;
        if (beforeRounded > 0) {
            beforePhrase = " (in " + beforeWords + ")";
        } else if (beforeRounded < 0) {
            beforePhrase = " (" + beforeWords + " ago)";
        } else {
            beforePhrase = "";
        }
        sb.append("Deadline: ").append(textFormatter.formatDateTime(deadline)).append(beforePhrase).append("\n");
        sb.append("\n");
    }
}
项目:Singularity    文件:SmtpMailer.java   
private void prepareRequestInCooldownMail(SingularityRequest request) {
  final List<SingularityEmailDestination> emailDestination = getDestination(request, SingularityEmailType.REQUEST_IN_COOLDOWN);

  if (emailDestination.isEmpty()) {
    LOG.debug("Not configured to send request cooldown mail for {}", request);
    return;
  }

  final Map<String, Object> templateProperties = Maps.newHashMap();
  populateRequestEmailProperties(templateProperties, request, SingularityEmailType.REQUEST_IN_COOLDOWN);

  final String subject = String.format("Request %s has entered system cooldown — Singularity", request.getId());

  templateProperties.put("numFailures", configuration.getCooldownAfterFailures());
  templateProperties.put("cooldownDelayFormat", DurationFormatUtils.formatDurationHMS(TimeUnit.SECONDS.toMillis(configuration.getCooldownMinScheduleSeconds())));
  templateProperties.put("cooldownExpiresFormat", DurationFormatUtils.formatDurationHMS(TimeUnit.MINUTES.toMillis(configuration.getCooldownExpiresAfterMinutes())));

  final String body = Jade4J.render(requestInCooldownTemplate, templateProperties);

  queueMail(emailDestination, request, SingularityEmailType.REQUEST_IN_COOLDOWN, Optional.<String> absent(), subject, body);
}
项目:Singularity    文件:SingularityJobPoller.java   
private void checkTaskExecutionTimeLimit(long now, SingularityTaskId taskId, SingularityRequest request) {
  final long runtime = now - taskId.getStartedAt();

  if (request.getTaskExecutionTimeLimitMillis().or(configuration.getTaskExecutionTimeLimitMillis()).isPresent() &&
      runtime >= request.getTaskExecutionTimeLimitMillis().or(configuration.getTaskExecutionTimeLimitMillis()).get()) {

    taskManager.createTaskCleanup(new SingularityTaskCleanup(
        Optional.<String>absent(),
        TaskCleanupType.TASK_EXCEEDED_TIME_LIMIT,
        now,
        taskId,
        Optional.of(String.format("Task has run for %s, which exceeds the maximum execution time of %s",
            DurationFormatUtils.formatDurationHMS(runtime),
            DurationFormatUtils.formatDurationHMS(request.getTaskExecutionTimeLimitMillis().or(configuration.getTaskExecutionTimeLimitMillis()).get()))
        ),
        Optional.of(UUID.randomUUID().toString()),
        Optional.<SingularityTaskShellCommandRequestId>absent())
    );
  }
}
项目:Singularity    文件:SingularityDeployChecker.java   
private boolean isDeployOverdue(SingularityPendingDeploy pendingDeploy, Optional<SingularityDeploy> deploy) {
  if (!deploy.isPresent()) {
    LOG.warn("Can't determine if deploy {} is overdue because it was missing", pendingDeploy);
    return false;
  }

  if (pendingDeploy.getDeployProgress().isPresent() && pendingDeploy.getDeployProgress().get().isStepComplete()) {
    return false;
  }

  final long startTime = getStartTime(pendingDeploy);

  final long deployDuration = System.currentTimeMillis() - startTime;

  final long allowedTime = getAllowedMillis(deploy.get());

  if (deployDuration > allowedTime) {
    LOG.warn("Deploy {} is overdue (duration: {}), allowed: {}", pendingDeploy, DurationFormatUtils.formatDurationHMS(deployDuration), DurationFormatUtils.formatDurationHMS(allowedTime));

    return true;
  } else {
    LOG.trace("Deploy {} is not yet overdue (duration: {}), allowed: {}", pendingDeploy, DurationFormatUtils.formatDurationHMS(deployDuration), DurationFormatUtils.formatDurationHMS(allowedTime));

    return false;
  }
}