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);
}
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"));
}
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());
}
}
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) {
}
}
}
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();
}
}
Aggregations