Search in sources :

Example 26 with ChronoUnit

use of java.time.temporal.ChronoUnit in project de-DiscordBot by DACH-Discord.

the class ModStuff method command_Mute.

@CommandSubscriber(command = "mute", help = "Einen Nutzer für eine bestimmte Zeit muten", pmAllowed = false, permissionLevel = CommandPermissions.MODERATOR)
public void command_Mute(final IMessage message, final String muteUserString, final String muteDurationInput) {
    final List<IUser> mentions = message.getMentions();
    if (mentions.size() < 1) {
        Util.sendMessage(message.getChannel(), ":x: Fehler: Kein Nutzer angegeben!");
        return;
    } else if (mentions.size() > 1) {
        Util.sendMessage(message.getChannel(), ":x: Fehler: mehrere Nutzer erwähnt");
        return;
    }
    final IUser muteUser = mentions.get(0);
    if (muteUser == null) {
        Util.sendMessage(message.getChannel(), ":x: Fehler: Nutzer nicht gefunden!");
        return;
    }
    Pattern pattern = Pattern.compile("(\\d+)\\s?([smhd])\\s?(.*)");
    Matcher matcher = pattern.matcher(muteDurationInput);
    if (!matcher.matches()) {
        Util.sendMessage(message.getChannel(), "Ungültige Eingabe! Mögliche Zeitformate sind s, m, h und d.");
        return;
    }
    IRole muteRole = message.getGuild().getRoleByID(muteRoleID);
    // Wird ausgeführt, um Nutzer wieder zu entmuten
    Runnable unmuteTask = () -> {
        mutedUsers.remove(muteUser.getStringID());
        muteUser.removeRole(muteRole);
        System.out.println("Unmuted user " + Util.makeUserString(muteUser, message.getGuild()) + ".");
    };
    final int muteDuration = Integer.parseInt(matcher.group(1));
    final String muteDurationUnitString = matcher.group(2);
    ChronoUnit muteDurationUnit = parseChronoUnit(muteDurationUnitString);
    if (mutedUsers.containsKey(muteUser.getStringID())) {
        // Überprüfen, ob angegebener Zeitpunkt nach dem bisherigen Zeitpunkt liegt
        ScheduledFuture oldFuture = mutedUsers.get(muteUser.getStringID());
        LocalDateTime oldDateTime = LocalDateTime.now().plusSeconds(oldFuture.getDelay(TimeUnit.SECONDS));
        LocalDateTime newDateTime = LocalDateTime.now().plus(muteDuration, muteDurationUnit);
        if (newDateTime.isBefore(oldDateTime)) {
            // neuer Zeitpunkt ist vor altem -> nichts tun (längerer Mute bleibt bestehen)
            Util.sendMessage(message.getChannel(), "Nutzer ist bereits für einen längeren Zeitraum gemuted!");
            return;
        } else {
            // neuer Zeitpunkt ist nach altem -> neu schedulen
            mutedUsers.remove(muteUser.getStringID(), oldFuture);
            oldFuture.cancel(false);
        }
    } else {
        muteUser.addRole(muteRole);
        System.out.println("Muted user " + Util.makeUserString(muteUser, message.getGuild()) + ".");
    }
    ScheduledFuture newFuture = scheduler.schedule(unmuteTask, muteDuration, chronoUnitToTimeUnit(muteDurationUnit));
    mutedUsers.put(muteUser.getStringID(), newFuture);
    // :mute:
    message.addReaction(ReactionEmoji.of("\uD83D\uDD07"));
    String customMessage = matcher.group(3);
    if (customMessage.isEmpty()) {
        customMessage = "kein";
    }
    final String muteMessage = "**Du wurdest für " + muteDuration + ' ' + muteDurationUnitString + " gemuted!** \nHinweis: _" + customMessage + " _";
    if (!muteUser.isBot()) {
        Util.sendPM(muteUser, muteMessage);
    }
    // Modlog
    IChannel modLogChannel = message.getGuild().getChannelByID(this.modlogChannelID);
    final String modLogMessage = String.format("**%s** hat Nutzer **%s** für %s %s **gemuted**. \nHinweis: _%s _", Util.makeUserString(message.getAuthor(), message.getGuild()), Util.makeUserString(muteUser, message.getGuild()), muteDuration, muteDurationUnitString, customMessage);
    Util.sendMessage(modLogChannel, modLogMessage);
}
Also used : LocalDateTime(java.time.LocalDateTime) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ScheduledFuture(java.util.concurrent.ScheduledFuture) ChronoUnit(java.time.temporal.ChronoUnit) CommandSubscriber(de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)

Example 27 with ChronoUnit

use of java.time.temporal.ChronoUnit in project de-DiscordBot by DACH-Discord.

the class ModStuff method command_Selfmute.

@CommandSubscriber(command = "selfmute", help = "Schalte dich selber für die angegebene Zeit stumm", pmAllowed = false)
public void command_Selfmute(final IMessage message, final String muteDurationInput) {
    IUser muteUser = message.getAuthor();
    Pattern pattern = Pattern.compile("(\\d+)\\s?([smhd])\\s?(.*)");
    Matcher matcher = pattern.matcher(muteDurationInput);
    if (!matcher.matches()) {
        Util.sendMessage(message.getChannel(), "Ungültige Eingabe! Mögliche Zeitformate sind s, m, h und d.");
        return;
    }
    IRole muteRole = message.getGuild().getRoleByID(muteRoleID);
    // Wird ausgeführt, um Nutzer wieder zu entmuten
    Runnable unmuteTask = () -> {
        mutedUsers.remove(muteUser.getStringID());
        muteUser.removeRole(muteRole);
        System.out.println("Unmuted user " + Util.makeUserString(muteUser, message.getGuild()) + ". (was selfmuted)");
    };
    final int muteDuration = Integer.parseInt(matcher.group(1));
    final String muteDurationUnitString = matcher.group(2);
    ChronoUnit muteDurationUnit = parseChronoUnit(muteDurationUnitString);
    if (mutedUsers.containsKey(muteUser.getStringID())) {
        // Überprüfen, ob angegebener Zeitpunkt nach dem bisherigen Zeitpunkt liegt
        ScheduledFuture oldFuture = mutedUsers.get(muteUser.getStringID());
        LocalDateTime oldDateTime = LocalDateTime.now().plusSeconds(oldFuture.getDelay(TimeUnit.SECONDS));
        LocalDateTime newDateTime = LocalDateTime.now().plus(muteDuration, muteDurationUnit);
        if (newDateTime.isBefore(oldDateTime)) {
            // neuer Zeitpunkt ist vor altem -> nichts tun (längerer Mute bleibt bestehen)
            Util.sendMessage(message.getChannel(), "Nutzer ist bereits für einen längeren Zeitraum gemuted!");
            return;
        } else {
            // neuer Zeitpunkt ist nach altem -> neu schedulen
            mutedUsers.remove(muteUser.getStringID(), oldFuture);
            oldFuture.cancel(false);
        }
    } else {
        muteUser.addRole(muteRole);
        System.out.println("User " + Util.makeUserString(muteUser, message.getGuild()) + " selfmuted.");
    }
    ScheduledFuture newFuture = scheduler.schedule(unmuteTask, muteDuration, chronoUnitToTimeUnit(muteDurationUnit));
    mutedUsers.put(muteUser.getStringID(), newFuture);
    // :mute:
    message.addReaction(ReactionEmoji.of("\uD83D\uDD07"));
}
Also used : LocalDateTime(java.time.LocalDateTime) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ScheduledFuture(java.util.concurrent.ScheduledFuture) ChronoUnit(java.time.temporal.ChronoUnit) CommandSubscriber(de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)

Example 28 with ChronoUnit

use of java.time.temporal.ChronoUnit in project java-certification by springapidev.

the class ChronoUnitValues method main.

public static void main(String[] args) {
    System.out.println("ChronoUnit DateBased TimeBased Duration");
    System.out.println("---------------------------------------");
    for (ChronoUnit unit : ChronoUnit.values()) {
        System.out.printf("%10s \t %b \t\t %b \t\t %s %n", unit, unit.isDateBased(), unit.isTimeBased(), unit.getDuration());
    }
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit)

Example 29 with ChronoUnit

use of java.time.temporal.ChronoUnit in project j2objc by google.

the class OffsetTimeTest method test_plus_minus_invalidUnits.

@Test
public void test_plus_minus_invalidUnits() {
    for (ChronoUnit unit : EnumSet.range(ChronoUnit.DAYS, ChronoUnit.FOREVER)) {
        try {
            NOON_UTC.plus(1, unit);
            fail("Adding 1 " + unit + " should have failed.");
        } catch (UnsupportedTemporalTypeException expected) {
        }
        try {
            NOON_UTC.minus(1, unit);
            fail("Subtracting 1 " + unit + " should have failed.");
        } catch (UnsupportedTemporalTypeException expected) {
        }
    }
}
Also used : UnsupportedTemporalTypeException(java.time.temporal.UnsupportedTemporalTypeException) ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.Test)

Example 30 with ChronoUnit

use of java.time.temporal.ChronoUnit in project scylla by bptlab.

the class BatchPluginUtils method assignToBatchCluster.

/**
 * Called when a batch activity is enabled
 * Assigns the process instance to a cluster (creates a new one if needed)
 * Takes care of scheduling of the cluster start events
 * @param processInstance : Instance of process where the batch activity was started
 * @param nodeId : NodeId of the subprocess
 * @param parentalBeginEvent : Begin event of the subprocess task
 */
void assignToBatchCluster(ProcessInstance processInstance, int nodeId, TaskBeginEvent parentalBeginEvent) {
    ProcessModel processModel = processInstance.getProcessModel();
    ProcessSimulationComponents simulationComponents = parentalBeginEvent.getSimulationComponents();
    /*Map<Integer, BatchActivity> batchActivities = (Map<Integer, BatchActivity>) pSimComponents.getSimulationConfiguration()
                .getExtensionValue(PLUGIN_NAME, "batchActivities");*/
    Map<Integer, BatchActivity> batchActivities = getBatchActivities(processModel);
    BatchActivity batchActivity = batchActivities.get(nodeId);
    BatchCluster cluster = null;
    // (1) select the right batch cluster
    // (1a) check if there is already a batch with the data view (= a cluster the instance can be added to)
    String processId = processModel.getId();
    Map<Integer, List<BatchCluster>> batchClustersOfProcess = batchClusters.computeIfAbsent(processId, (s) -> new HashMap<Integer, List<BatchCluster>>());
    List<BatchCluster> clusters = batchClustersOfProcess.get(nodeId);
    if (clusters != null) {
        cluster = clusters.stream().filter(BatchCluster::hasNotStarted).filter(eachCluster -> eachCluster.isProcessInstanceMatchingGroupingCharacteristic(processInstance)).findFirst().orElse(null);
    }
    // (1b) if not, create a new one
    if (cluster == null) {
        Model model = processInstance.getModel();
        boolean showInTrace = processInstance.traceIsOn();
        TimeInstant currentSimulationTime = processInstance.presentTime();
        cluster = BatchCluster.create(model, currentSimulationTime, simulationComponents, batchActivity, showInTrace);
        // schedule BatchClusterStart at current time plus maximum timeout
        BatchClusterEnableEvent clusterStartEvent = new BatchClusterEnableEvent(processInstance, cluster);
        cluster.setEnableEvent(clusterStartEvent);
        Duration timeout = batchActivity.getActivationRule().getTimeOut(parentalBeginEvent, processInstance);
        cluster.setCurrentTimeOut(timeout);
        long timeoutInSeconds = timeout.get(ChronoUnit.SECONDS);
        TimeSpan timeSpan = new TimeSpan(timeoutInSeconds, TimeUnit.SECONDS);
        clusterStartEvent.schedule(timeSpan);
        // (4) add cluster to not started clusters
        batchClustersOfProcess.computeIfAbsent(nodeId, (i) -> new ArrayList<BatchCluster>()).add(cluster);
    }
    // (2) add process instance to cluster
    cluster.addProcessInstance(processInstance, parentalBeginEvent);
    // Instance can be first in cluster => nothing to update
    if (cluster.hasNotStarted() && cluster.getProcessInstances().size() > 1) {
        // if the dueDate of the current instance is earlier as of the instances added before, the cluster begin event is rescheduled
        // Duration timeoutForCurrentInstance = batchActivity.getActivationRule().getTimeOut(parentalBeginEvent, processInstance);
        // New situation; the timeouts might have changed so adapt the set timeout
        Duration newTimeout = cluster.getParentalStartEvents().stream().map(each -> batchActivity.getActivationRule().getTimeOut(each, each.getProcessInstance())).min(Duration::compareTo).get();
        TimeUnit timeUnit = TimeUnit.SECONDS;
        ChronoUnit chronoUnit = ChronoUnit.valueOf(timeUnit.toString());
        // If the new timeout from the current point in time occurs before the current timeout
        if (!newTimeout.equals(cluster.getCurrentTimeOut())) {
            // set new timeout for the cluster
            cluster.setCurrentTimeOut(newTimeout);
            long clusterAge = (long) (parentalBeginEvent.getSimulationTimeOfSource().getTimeAsDouble(timeUnit) - cluster.getCreationTime().getTimeAsDouble(timeUnit));
            // reschedule the cluster beginEvent
            long timeoutFromNow = newTimeout.get(chronoUnit) - clusterAge;
            if (timeoutFromNow < 0)
                timeoutFromNow = 0;
            TimeSpan timeSpan = new TimeSpan(timeoutFromNow, timeUnit);
            // Scheduled with timeout from current point in time
            BatchClusterEnableEvent clusterStartEvent = cluster.getEnableEvent();
            clusterStartEvent.cancel();
            clusterStartEvent.schedule(timeSpan);
        }
    }
    // (4) check if bc can be started
    if (cluster.getState() == BatchClusterState.MAXLOADED || cluster.getState() == BatchClusterState.READY) {
        // (2a) if bc is maxloaded, reschedule BatchClusterStart
        // there is only one event already scheduled for the cluster which is the BatchClusterStart
        BatchClusterEnableEvent clusterStartEvent = cluster.getEnableEvent();
        if (clusterStartEvent.isScheduled())
            clusterStartEvent.cancel();
        // schedule for immediate execution
        clusterStartEvent.schedule();
    }
}
Also used : ProcessModel(de.hpi.bpt.scylla.model.process.ProcessModel) TaskCancelEvent(de.hpi.bpt.scylla.simulation.event.TaskCancelEvent) TimeInstant(desmoj.core.simulator.TimeInstant) ProcessSimulationComponents(de.hpi.bpt.scylla.simulation.ProcessSimulationComponents) Set(java.util.Set) HashMap(java.util.HashMap) TaskEvent(de.hpi.bpt.scylla.simulation.event.TaskEvent) ArrayList(java.util.ArrayList) EventAbstract(desmoj.core.simulator.EventAbstract) HashSet(java.util.HashSet) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) Duration(java.time.Duration) Map(java.util.Map) TaskTerminateEvent(de.hpi.bpt.scylla.simulation.event.TaskTerminateEvent) TimeSpan(desmoj.core.simulator.TimeSpan) ProcessInstance(de.hpi.bpt.scylla.simulation.ProcessInstance) Model(desmoj.core.simulator.Model) TaskBeginEvent(de.hpi.bpt.scylla.simulation.event.TaskBeginEvent) ProcessModel(de.hpi.bpt.scylla.model.process.ProcessModel) ArrayList(java.util.ArrayList) Duration(java.time.Duration) TimeSpan(desmoj.core.simulator.TimeSpan) ProcessSimulationComponents(de.hpi.bpt.scylla.simulation.ProcessSimulationComponents) ProcessModel(de.hpi.bpt.scylla.model.process.ProcessModel) Model(desmoj.core.simulator.Model) TimeUnit(java.util.concurrent.TimeUnit) ArrayList(java.util.ArrayList) List(java.util.List) TimeInstant(desmoj.core.simulator.TimeInstant) ChronoUnit(java.time.temporal.ChronoUnit)

Aggregations

ChronoUnit (java.time.temporal.ChronoUnit)42 Test (org.junit.jupiter.api.Test)11 Test (org.junit.Test)6 LocalDateTime (java.time.LocalDateTime)5 Matcher (java.util.regex.Matcher)5 Duration (java.time.Duration)4 Map (java.util.Map)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 ChronoLocalDateTime (java.time.chrono.ChronoLocalDateTime)3 ArrayList (java.util.ArrayList)3 Pattern (java.util.regex.Pattern)3 Given (cucumber.api.java.en.Given)2 CommandSubscriber (de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)2 CommandSubscriber (de.nikos410.discordbot.framework.annotations.CommandSubscriber)2 CommandUtils (de.nikos410.discordbot.util.CommandUtils)2 FaultToleranceService (fish.payara.microprofile.faulttolerance.FaultToleranceService)2 Instant (java.time.Instant)2 ZonedDateTime (java.time.ZonedDateTime)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 ScheduledFuture (java.util.concurrent.ScheduledFuture)2