diff --git a/L2J_Mobius_1.0_Ertheia/.classpath b/L2J_Mobius_1.0_Ertheia/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_1.0_Ertheia/.classpath +++ b/L2J_Mobius_1.0_Ertheia/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_1.0_Ertheia/build.xml b/L2J_Mobius_1.0_Ertheia/build.xml index e65e75754f..d45b0d7777 100644 --- a/L2J_Mobius_1.0_Ertheia/build.xml +++ b/L2J_Mobius_1.0_Ertheia/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.50.Final.jar similarity index 52% rename from L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.38.Final.jar rename to L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.50.Final.jar index 1ec34bd6f3..f8b1557478 100644 Binary files a/L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.38.Final.jar and b/L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.30.jar similarity index 54% rename from L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.27.jar rename to L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.30.jar index f74802295a..29ac26fb8c 100644 Binary files a/L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.27.jar and b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.30.jar similarity index 79% rename from L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.27.jar rename to L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.30.jar index 17f96a8f1c..6debaa9dec 100644 Binary files a/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.27.jar and b/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_1.0_Ertheia/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_2.5_Underground/.classpath b/L2J_Mobius_2.5_Underground/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_2.5_Underground/.classpath +++ b/L2J_Mobius_2.5_Underground/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_2.5_Underground/build.xml b/L2J_Mobius_2.5_Underground/build.xml index 7327068adf..abe6b244b7 100644 --- a/L2J_Mobius_2.5_Underground/build.xml +++ b/L2J_Mobius_2.5_Underground/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_2.5_Underground/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_2.5_Underground/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_2.5_Underground/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_2.5_Underground/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.50.Final.jar similarity index 52% rename from L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.38.Final.jar rename to L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.50.Final.jar index 1ec34bd6f3..f8b1557478 100644 Binary files a/L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.38.Final.jar and b/L2J_Mobius_2.5_Underground/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.30.jar similarity index 54% rename from L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.27.jar rename to L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.30.jar index f74802295a..29ac26fb8c 100644 Binary files a/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.27.jar and b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.30.jar similarity index 79% rename from L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.27.jar rename to L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.30.jar index 17f96a8f1c..6debaa9dec 100644 Binary files a/L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.27.jar and b/L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_2.5_Underground/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_3.0_Helios/.classpath b/L2J_Mobius_3.0_Helios/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_3.0_Helios/.classpath +++ b/L2J_Mobius_3.0_Helios/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_3.0_Helios/build.xml b/L2J_Mobius_3.0_Helios/build.xml index 7744dbfab7..db4fbf42ad 100644 --- a/L2J_Mobius_3.0_Helios/build.xml +++ b/L2J_Mobius_3.0_Helios/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_3.0_Helios/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_3.0_Helios/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_3.0_Helios/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_3.0_Helios/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.50.Final.jar similarity index 52% rename from L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.38.Final.jar rename to L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.50.Final.jar index 1ec34bd6f3..f8b1557478 100644 Binary files a/L2J_Mobius_1.0_Ertheia/dist/libs/netty-all-4.1.38.Final.jar and b/L2J_Mobius_3.0_Helios/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.30.jar similarity index 54% rename from L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.27.jar rename to L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.30.jar index f74802295a..29ac26fb8c 100644 Binary files a/L2J_Mobius_2.5_Underground/dist/libs/slf4j-api-1.7.27.jar and b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.30.jar similarity index 79% rename from L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.27.jar rename to L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.30.jar index 17f96a8f1c..6debaa9dec 100644 Binary files a/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.27.jar and b/L2J_Mobius_3.0_Helios/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_3.0_Helios/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/.classpath b/L2J_Mobius_4.0_GrandCrusade/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_4.0_GrandCrusade/.classpath +++ b/L2J_Mobius_4.0_GrandCrusade/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_4.0_GrandCrusade/build.xml b/L2J_Mobius_4.0_GrandCrusade/build.xml index 8469f0866c..903a3db274 100644 --- a/L2J_Mobius_4.0_GrandCrusade/build.xml +++ b/L2J_Mobius_4.0_GrandCrusade/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.50.Final.jar similarity index 52% rename from L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.38.Final.jar rename to L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.50.Final.jar index 1ec34bd6f3..f8b1557478 100644 Binary files a/L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.38.Final.jar and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.30.jar similarity index 54% rename from L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.27.jar rename to L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.30.jar index f74802295a..29ac26fb8c 100644 Binary files a/L2J_Mobius_1.0_Ertheia/dist/libs/slf4j-api-1.7.27.jar and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.30.jar similarity index 79% rename from L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.27.jar rename to L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.30.jar index 17f96a8f1c..6debaa9dec 100644 Binary files a/L2J_Mobius_2.5_Underground/dist/libs/slf4j-simple-1.7.27.jar and b/L2J_Mobius_4.0_GrandCrusade/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java index 9078aa5dcb..462890bdc4 100644 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java +++ b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java @@ -27,7 +27,8 @@ import org.l2jmobius.gameserver.model.DailyMissionDataHolder; import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance; import org.l2jmobius.gameserver.network.OutgoingPackets; import org.l2jmobius.gameserver.network.serverpackets.IClientOutgoingPacket; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.Predictor; /** * @author Sdw diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_4.0_GrandCrusade/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_5.0_Salvation/.classpath b/L2J_Mobius_5.0_Salvation/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_5.0_Salvation/.classpath +++ b/L2J_Mobius_5.0_Salvation/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_5.0_Salvation/build.xml b/L2J_Mobius_5.0_Salvation/build.xml index 63bf9e5436..e4b167811f 100644 --- a/L2J_Mobius_5.0_Salvation/build.xml +++ b/L2J_Mobius_5.0_Salvation/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_5.0_Salvation/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_5.0_Salvation/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_5.0_Salvation/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_5.0_Salvation/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_5.0_Salvation/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_5.0_Salvation/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/.classpath b/L2J_Mobius_5.5_EtinasFate/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_5.5_EtinasFate/.classpath +++ b/L2J_Mobius_5.5_EtinasFate/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_5.5_EtinasFate/build.xml b/L2J_Mobius_5.5_EtinasFate/build.xml index 9b704e9512..ce6e602a70 100644 --- a/L2J_Mobius_5.5_EtinasFate/build.xml +++ b/L2J_Mobius_5.5_EtinasFate/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_5.5_EtinasFate/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_5.5_EtinasFate/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/.classpath b/L2J_Mobius_6.0_Fafurion/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_6.0_Fafurion/.classpath +++ b/L2J_Mobius_6.0_Fafurion/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_6.0_Fafurion/build.xml b/L2J_Mobius_6.0_Fafurion/build.xml index 20e506355a..97598b278c 100644 --- a/L2J_Mobius_6.0_Fafurion/build.xml +++ b/L2J_Mobius_6.0_Fafurion/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_6.0_Fafurion/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_6.0_Fafurion/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/.classpath b/L2J_Mobius_7.0_PreludeOfWar/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_7.0_PreludeOfWar/.classpath +++ b/L2J_Mobius_7.0_PreludeOfWar/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_7.0_PreludeOfWar/build.xml b/L2J_Mobius_7.0_PreludeOfWar/build.xml index 7c11632e3a..1854f4718f 100644 --- a/L2J_Mobius_7.0_PreludeOfWar/build.xml +++ b/L2J_Mobius_7.0_PreludeOfWar/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_7.0_PreludeOfWar/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index f34ee70995..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("Ο€", Math.PI); - vars.put("Ο†", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - count++; - break; - } - case Token.TOKEN_FUNCTION: - { - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - } - case Token.TOKEN_OPERATOR: - { - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 0726b1e9e1..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("Ο€"); - variableNames.add("e"); - variableNames.add("Ο†"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index 0d30a2a8da..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - } - case '-': - { - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - } - case '*': - { - return builtinOperators[INDEX_MUTLIPLICATION]; - } - case '/': - { - return builtinOperators[INDEX_DIVISION]; - } - case '^': - { - return builtinOperators[INDEX_POWER]; - } - case '%': - { - return builtinOperators[INDEX_MODULO]; - } - default: - { - return null; - } - } - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 84368a2106..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - { - output.add(token); - break; - } - case Token.TOKEN_FUNCTION: - { - stack.add(token); - break; - } - case Token.TOKEN_SEPARATOR: - { - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - } - case Token.TOKEN_OPERATOR: - { - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_OPEN: - { - stack.push(token); - break; - } - case Token.TOKEN_PARENTHESES_CLOSE: - { - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - } - default: - { - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_7.0_PreludeOfWar/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_C4_ScionsOfDestiny/.classpath b/L2J_Mobius_C4_ScionsOfDestiny/.classpath index 23008d1ee2..7776d4ad45 100644 --- a/L2J_Mobius_C4_ScionsOfDestiny/.classpath +++ b/L2J_Mobius_C4_ScionsOfDestiny/.classpath @@ -5,10 +5,10 @@ - - - - + + + + diff --git a/L2J_Mobius_C4_ScionsOfDestiny/build.xml b/L2J_Mobius_C4_ScionsOfDestiny/build.xml index 063efa9b4f..379713c9ec 100644 --- a/L2J_Mobius_C4_ScionsOfDestiny/build.xml +++ b/L2J_Mobius_C4_ScionsOfDestiny/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_C4_ScionsOfDestiny/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_C6_Interlude/.classpath b/L2J_Mobius_C6_Interlude/.classpath index 23008d1ee2..7776d4ad45 100644 --- a/L2J_Mobius_C6_Interlude/.classpath +++ b/L2J_Mobius_C6_Interlude/.classpath @@ -5,10 +5,10 @@ - - - - + + + + diff --git a/L2J_Mobius_C6_Interlude/build.xml b/L2J_Mobius_C6_Interlude/build.xml index bb04197d34..2016fa66bc 100644 --- a/L2J_Mobius_C6_Interlude/build.xml +++ b/L2J_Mobius_C6_Interlude/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_C6_Interlude/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/.classpath b/L2J_Mobius_CT_2.4_Epilogue/.classpath index ced70bc3b1..568d19f654 100644 --- a/L2J_Mobius_CT_2.4_Epilogue/.classpath +++ b/L2J_Mobius_CT_2.4_Epilogue/.classpath @@ -5,11 +5,11 @@ - - - - - + + + + + diff --git a/L2J_Mobius_CT_2.4_Epilogue/build.xml b/L2J_Mobius_CT_2.4_Epilogue/build.xml index 7778e3952f..25a8c48531 100644 --- a/L2J_Mobius_CT_2.4_Epilogue/build.xml +++ b/L2J_Mobius_CT_2.4_Epilogue/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_CT_2.4_Epilogue/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/.classpath b/L2J_Mobius_CT_2.6_HighFive/.classpath index ced70bc3b1..568d19f654 100644 --- a/L2J_Mobius_CT_2.6_HighFive/.classpath +++ b/L2J_Mobius_CT_2.6_HighFive/.classpath @@ -5,11 +5,11 @@ - - - - - + + + + + diff --git a/L2J_Mobius_CT_2.6_HighFive/build.xml b/L2J_Mobius_CT_2.6_HighFive/build.xml index 26063f12ba..9493d9c444 100644 --- a/L2J_Mobius_CT_2.6_HighFive/build.xml +++ b/L2J_Mobius_CT_2.6_HighFive/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_CT_2.6_HighFive/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/.classpath b/L2J_Mobius_Classic_2.0_Saviors/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_Classic_2.0_Saviors/.classpath +++ b/L2J_Mobius_Classic_2.0_Saviors/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_Classic_2.0_Saviors/build.xml b/L2J_Mobius_Classic_2.0_Saviors/build.xml index 95f0f4f8b6..34d564a468 100644 --- a/L2J_Mobius_Classic_2.0_Saviors/build.xml +++ b/L2J_Mobius_Classic_2.0_Saviors/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_Classic_2.0_Saviors/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index 6d2ca225e1..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("π", Math.PI); - vars.put("φ", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - count++; - break; - case Token.TOKEN_FUNCTION: - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - case Token.TOKEN_OPERATOR: - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 87c6470c7a..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("π"); - variableNames.add("e"); - variableNames.add("φ"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index e1755631c9..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - case '-': - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - case '*': - return builtinOperators[INDEX_MUTLIPLICATION]; - case '/': - return builtinOperators[INDEX_DIVISION]; - case '^': - return builtinOperators[INDEX_POWER]; - case '%': - return builtinOperators[INDEX_MODULO]; - default: - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 7c543e9ce9..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - output.add(token); - break; - case Token.TOKEN_FUNCTION: - stack.add(token); - break; - case Token.TOKEN_SEPARATOR: - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - case Token.TOKEN_OPERATOR: - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_OPEN: - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_CLOSE: - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - default: - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_Classic_2.0_Saviors/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/.classpath b/L2J_Mobius_Classic_2.1_Zaken/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_Classic_2.1_Zaken/.classpath +++ b/L2J_Mobius_Classic_2.1_Zaken/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_Classic_2.1_Zaken/build.xml b/L2J_Mobius_Classic_2.1_Zaken/build.xml index a39a44d883..4e1cc7666c 100644 --- a/L2J_Mobius_Classic_2.1_Zaken/build.xml +++ b/L2J_Mobius_Classic_2.1_Zaken/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_Classic_2.1_Zaken/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java index 9078aa5dcb..462890bdc4 100644 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java +++ b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java @@ -27,7 +27,8 @@ import org.l2jmobius.gameserver.model.DailyMissionDataHolder; import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance; import org.l2jmobius.gameserver.network.OutgoingPackets; import org.l2jmobius.gameserver.network.serverpackets.IClientOutgoingPacket; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.Predictor; /** * @author Sdw diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index 6d2ca225e1..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("π", Math.PI); - vars.put("φ", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - count++; - break; - case Token.TOKEN_FUNCTION: - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - case Token.TOKEN_OPERATOR: - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 87c6470c7a..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("π"); - variableNames.add("e"); - variableNames.add("φ"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index e1755631c9..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - case '-': - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - case '*': - return builtinOperators[INDEX_MUTLIPLICATION]; - case '/': - return builtinOperators[INDEX_DIVISION]; - case '^': - return builtinOperators[INDEX_POWER]; - case '%': - return builtinOperators[INDEX_MODULO]; - default: - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 7c543e9ce9..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - output.add(token); - break; - case Token.TOKEN_FUNCTION: - stack.add(token); - break; - case Token.TOKEN_SEPARATOR: - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - case Token.TOKEN_OPERATOR: - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_OPEN: - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_CLOSE: - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - default: - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_Classic_2.1_Zaken/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/.classpath b/L2J_Mobius_Classic_2.2_Antharas/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_Classic_2.2_Antharas/.classpath +++ b/L2J_Mobius_Classic_2.2_Antharas/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_Classic_2.2_Antharas/build.xml b/L2J_Mobius_Classic_2.2_Antharas/build.xml index 4144958c81..290aa80875 100644 --- a/L2J_Mobius_Classic_2.2_Antharas/build.xml +++ b/L2J_Mobius_Classic_2.2_Antharas/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_Classic_2.2_Antharas/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java index 9078aa5dcb..462890bdc4 100644 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java +++ b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java @@ -27,7 +27,8 @@ import org.l2jmobius.gameserver.model.DailyMissionDataHolder; import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance; import org.l2jmobius.gameserver.network.OutgoingPackets; import org.l2jmobius.gameserver.network.serverpackets.IClientOutgoingPacket; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.Predictor; /** * @author Sdw diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index 6d2ca225e1..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("π", Math.PI); - vars.put("φ", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - count++; - break; - case Token.TOKEN_FUNCTION: - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - case Token.TOKEN_OPERATOR: - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 87c6470c7a..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("π"); - variableNames.add("e"); - variableNames.add("φ"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index e1755631c9..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - case '-': - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - case '*': - return builtinOperators[INDEX_MUTLIPLICATION]; - case '/': - return builtinOperators[INDEX_DIVISION]; - case '^': - return builtinOperators[INDEX_POWER]; - case '%': - return builtinOperators[INDEX_MODULO]; - default: - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 7c543e9ce9..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - output.add(token); - break; - case Token.TOKEN_FUNCTION: - stack.add(token); - break; - case Token.TOKEN_SEPARATOR: - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - case Token.TOKEN_OPERATOR: - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_OPEN: - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_CLOSE: - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - default: - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_Classic_2.2_Antharas/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/.classpath b/L2J_Mobius_Classic_2.3_SevenSigns/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_Classic_2.3_SevenSigns/.classpath +++ b/L2J_Mobius_Classic_2.3_SevenSigns/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/build.xml b/L2J_Mobius_Classic_2.3_SevenSigns/build.xml index f2a7019180..3ce4a9e317 100644 --- a/L2J_Mobius_Classic_2.3_SevenSigns/build.xml +++ b/L2J_Mobius_Classic_2.3_SevenSigns/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_Classic_2.3_SevenSigns/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java index 9078aa5dcb..462890bdc4 100644 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java +++ b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java @@ -27,7 +27,8 @@ import org.l2jmobius.gameserver.model.DailyMissionDataHolder; import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance; import org.l2jmobius.gameserver.network.OutgoingPackets; import org.l2jmobius.gameserver.network.serverpackets.IClientOutgoingPacket; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.Predictor; /** * @author Sdw diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index 6d2ca225e1..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("π", Math.PI); - vars.put("φ", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - count++; - break; - case Token.TOKEN_FUNCTION: - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - case Token.TOKEN_OPERATOR: - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 87c6470c7a..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("π"); - variableNames.add("e"); - variableNames.add("φ"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index e1755631c9..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - case '-': - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - case '*': - return builtinOperators[INDEX_MUTLIPLICATION]; - case '/': - return builtinOperators[INDEX_DIVISION]; - case '^': - return builtinOperators[INDEX_POWER]; - case '%': - return builtinOperators[INDEX_MODULO]; - default: - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 7c543e9ce9..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - output.add(token); - break; - case Token.TOKEN_FUNCTION: - stack.add(token); - break; - case Token.TOKEN_SEPARATOR: - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - case Token.TOKEN_OPERATOR: - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_OPEN: - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_CLOSE: - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - default: - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_Classic_2.3_SevenSigns/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/.classpath b/L2J_Mobius_Classic_2.4_SecretOfEmpire/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/.classpath +++ b/L2J_Mobius_Classic_2.4_SecretOfEmpire/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/build.xml b/L2J_Mobius_Classic_2.4_SecretOfEmpire/build.xml index aa1f5dd04b..bb5d57d2fc 100644 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/build.xml +++ b/L2J_Mobius_Classic_2.4_SecretOfEmpire/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_Classic_2.4_SecretOfEmpire/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java index 6bd8ae2d94..fa70cd9b72 100644 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java +++ b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java @@ -27,7 +27,8 @@ import org.l2jmobius.gameserver.model.DailyMissionDataHolder; import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance; import org.l2jmobius.gameserver.network.OutgoingPackets; import org.l2jmobius.gameserver.network.serverpackets.IClientOutgoingPacket; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.Predictor; /** * @author Sdw diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index 6d2ca225e1..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("π", Math.PI); - vars.put("φ", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - count++; - break; - case Token.TOKEN_FUNCTION: - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - case Token.TOKEN_OPERATOR: - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 87c6470c7a..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("π"); - variableNames.add("e"); - variableNames.add("φ"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index e1755631c9..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - case '-': - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - case '*': - return builtinOperators[INDEX_MUTLIPLICATION]; - case '/': - return builtinOperators[INDEX_DIVISION]; - case '^': - return builtinOperators[INDEX_POWER]; - case '%': - return builtinOperators[INDEX_MODULO]; - default: - return null; - } - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 7c543e9ce9..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - output.add(token); - break; - case Token.TOKEN_FUNCTION: - stack.add(token); - break; - case Token.TOKEN_SEPARATOR: - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - case Token.TOKEN_OPERATOR: - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_OPEN: - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_CLOSE: - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - default: - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_Classic_2.4_SecretOfEmpire/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/.classpath b/L2J_Mobius_Classic_3.0_TheKamael/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_Classic_3.0_TheKamael/.classpath +++ b/L2J_Mobius_Classic_3.0_TheKamael/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_Classic_3.0_TheKamael/build.xml b/L2J_Mobius_Classic_3.0_TheKamael/build.xml index 827a5f9cbb..85238c76f9 100644 --- a/L2J_Mobius_Classic_3.0_TheKamael/build.xml +++ b/L2J_Mobius_Classic_3.0_TheKamael/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_Classic_3.0_TheKamael/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java index 6bd8ae2d94..fa70cd9b72 100644 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java +++ b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java @@ -27,7 +27,8 @@ import org.l2jmobius.gameserver.model.DailyMissionDataHolder; import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance; import org.l2jmobius.gameserver.network.OutgoingPackets; import org.l2jmobius.gameserver.network.serverpackets.IClientOutgoingPacket; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.Predictor; /** * @author Sdw diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index 6d2ca225e1..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("π", Math.PI); - vars.put("φ", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - count++; - break; - case Token.TOKEN_FUNCTION: - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - case Token.TOKEN_OPERATOR: - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 87c6470c7a..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("π"); - variableNames.add("e"); - variableNames.add("φ"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index e1755631c9..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - case '-': - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - case '*': - return builtinOperators[INDEX_MUTLIPLICATION]; - case '/': - return builtinOperators[INDEX_DIVISION]; - case '^': - return builtinOperators[INDEX_POWER]; - case '%': - return builtinOperators[INDEX_MODULO]; - default: - return null; - } - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 7c543e9ce9..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - output.add(token); - break; - case Token.TOKEN_FUNCTION: - stack.add(token); - break; - case Token.TOKEN_SEPARATOR: - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - case Token.TOKEN_OPERATOR: - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_OPEN: - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_CLOSE: - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - default: - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_Classic_3.0_TheKamael/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -} diff --git a/L2J_Mobius_Classic_Interlude/.classpath b/L2J_Mobius_Classic_Interlude/.classpath index ced70bc3b1..96404c8fee 100644 --- a/L2J_Mobius_Classic_Interlude/.classpath +++ b/L2J_Mobius_Classic_Interlude/.classpath @@ -5,11 +5,13 @@ - - - - - + + + + + + + diff --git a/L2J_Mobius_Classic_Interlude/build.xml b/L2J_Mobius_Classic_Interlude/build.xml index 46d1d401b8..93b12e6d04 100644 --- a/L2J_Mobius_Classic_Interlude/build.xml +++ b/L2J_Mobius_Classic_Interlude/build.xml @@ -30,6 +30,7 @@ + @@ -135,7 +136,7 @@ - + diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.3.1.jar b/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.3.1.jar deleted file mode 100644 index 476e0c0b7a..0000000000 Binary files a/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.3.1.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.4.5-sources.jar b/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.4.5-sources.jar new file mode 100644 index 0000000000..ea4b7b6a4a Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.4.5-sources.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.4.5.jar b/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.4.5.jar new file mode 100644 index 0000000000..95247be0c4 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/HikariCP-3.4.5.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/cron4j-2.2.5-sources.jar b/L2J_Mobius_Classic_Interlude/dist/libs/cron4j-2.2.5-sources.jar new file mode 100644 index 0000000000..6eab310e6e Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/cron4j-2.2.5-sources.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/cron4j-2.2.5.jar b/L2J_Mobius_Classic_Interlude/dist/libs/cron4j-2.2.5.jar new file mode 100644 index 0000000000..53ee2ccf49 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/cron4j-2.2.5.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/exp4j-0.4.8-sources.jar b/L2J_Mobius_Classic_Interlude/dist/libs/exp4j-0.4.8-sources.jar new file mode 100644 index 0000000000..f9074f4e4f Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/exp4j-0.4.8-sources.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/exp4j-0.4.8.jar b/L2J_Mobius_Classic_Interlude/dist/libs/exp4j-0.4.8.jar new file mode 100644 index 0000000000..dd26421402 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/exp4j-0.4.8.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.4.3.jar b/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.4.3.jar deleted file mode 100644 index cef4ab119e..0000000000 Binary files a/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.4.3.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.6.1-sources.jar b/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.6.1-sources.jar new file mode 100644 index 0000000000..727328c651 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.6.1-sources.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.6.1.jar b/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.6.1.jar new file mode 100644 index 0000000000..4fa347d1c4 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/mariadb-java-client-2.6.1.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.38.Final.jar b/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.38.Final.jar deleted file mode 100644 index 1ec34bd6f3..0000000000 Binary files a/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.38.Final.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.50.Final-sources.jar b/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.50.Final-sources.jar new file mode 100644 index 0000000000..d40b0f6ac9 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.50.Final-sources.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.50.Final.jar b/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.50.Final.jar new file mode 100644 index 0000000000..f8b1557478 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/netty-all-4.1.50.Final.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.27.jar b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.27.jar deleted file mode 100644 index f74802295a..0000000000 Binary files a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.30-sources.jar b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.30-sources.jar new file mode 100644 index 0000000000..a282ebb47a Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.30.jar b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.30.jar new file mode 100644 index 0000000000..29ac26fb8c Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-api-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.27.jar b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.27.jar deleted file mode 100644 index 17f96a8f1c..0000000000 Binary files a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.27.jar and /dev/null differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.30-sources.jar b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.30-sources.jar new file mode 100644 index 0000000000..74e77ba026 Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.30-sources.jar differ diff --git a/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.30.jar b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.30.jar new file mode 100644 index 0000000000..6debaa9dec Binary files /dev/null and b/L2J_Mobius_Classic_Interlude/dist/libs/slf4j-simple-1.7.30.jar differ diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java index 4b08765663..9d63a90863 100644 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java +++ b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/data/xml/impl/SkillData.java @@ -47,7 +47,8 @@ import org.l2jmobius.gameserver.model.skills.EffectScope; import org.l2jmobius.gameserver.model.skills.ISkillCondition; import org.l2jmobius.gameserver.model.skills.Skill; import org.l2jmobius.gameserver.model.skills.SkillConditionScope; -import org.l2jmobius.gameserver.util.exp4j.ExpressionBuilder; + +import net.objecthunter.exp4j.ExpressionBuilder; /** * Skill data parser. diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java index f599aee66e..f150ec3238 100644 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java +++ b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/model/eventengine/EventScheduler.java @@ -29,8 +29,9 @@ import java.util.logging.Logger; import org.l2jmobius.commons.concurrent.ThreadPool; import org.l2jmobius.commons.database.DatabaseFactory; import org.l2jmobius.gameserver.model.StatSet; -import org.l2jmobius.gameserver.util.cron4j.PastPredictor; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.PastPredictor; +import it.sauronsoftware.cron4j.Predictor; /** * @author UnAfraid diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java index 9078aa5dcb..462890bdc4 100644 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java +++ b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/network/serverpackets/dailymission/ExOneDayReceiveRewardList.java @@ -27,7 +27,8 @@ import org.l2jmobius.gameserver.model.DailyMissionDataHolder; import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance; import org.l2jmobius.gameserver.network.OutgoingPackets; import org.l2jmobius.gameserver.network.serverpackets.IClientOutgoingPacket; -import org.l2jmobius.gameserver.util.cron4j.Predictor; + +import it.sauronsoftware.cron4j.Predictor; /** * @author Sdw diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java deleted file mode 100644 index 0ca1d21f63..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/AlwaysTrueValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * This ValueMatcher always returns true! - * @author Carlo Pelliccia - */ -class AlwaysTrueValueMatcher implements ValueMatcher -{ - /** - * Always true! - */ - @Override - public boolean match(int value) - { - return true; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java deleted file mode 100644 index 3d2c436dcf..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/CronParser.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A parser for crontab-like formatted files and streams. - *

- *

- * If you want to schedule a list of tasks declared in a crontab-like file you don't need the CronParser, since you can do it by adding the file to the scheduler, with the {@link Scheduler#scheduleFile(File)} method. - *

- *

- * Consider to use the CronParser if the {@link Scheduler#scheduleFile(File)} method is not enough for you. In example, you may need to fetch the task list from a remote source which is not representable as a {@link File} object (a document on a remote server, a DBMS result set and so on). To solve - * the problem you can implement your own {@link TaskCollector}, getting the advantage of the CronParser to parse easily any crontab-like content. - *

- *

- * You can parse a whole file/stream, but you can also parse a single line. - *

- *

- * A line can be empty, can contain a comment or it can be a scheduling line. - *

- *

- * A line containing no characters or a line with only space characters is considered an empty line. - *

- *

- * A line whose first non-space character is a number sign (#) is considered a comment. - *

- *

- * Empty lines and comment lines are ignored by the parser. - *

- *

- * Any other kind of line is parsed as a scheduling line. - *

- *

- * A valid scheduling line respects the following structure: - *

- * - *
- * scheduling-pattern [options] command [args]
- * 
- *
    - *
  • scheduling-pattern is a valid scheduling pattern, according with the definition given by the {@link SchedulingPattern} class.
  • - *
  • options is a list of optional informations used by cron4j to prepare the task execution environment. See below for a more detailed description.
  • - *
  • command is a system valid command, such an executable call.
  • - *
  • args is a list of optional arguments for the command.
  • - *
- *

- * After the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks ("). - *

- *

- * Double quotation marks delimited items can take advantage of the following escape sequences: - *

- *
    - *
  • \" - quotation mark
  • - *
  • \\ - back slash
  • - *
  • \/ - slash
  • - *
  • \b - back space
  • - *
  • \f - form feed
  • - *
  • \n - new line
  • - *
  • \r - carriage return
  • - *
  • \t - horizontal tab
  • - *
  • \u005c\u0075four-hex-digits - the character at the given unicode index
  • - *
- *

- * The options token collection can include one or more of the following elements: - *

- *
    - *
  • IN:file-path - Redirects the command standard input channel to the specified file.
  • - *
  • OUT:file-path - Redirects the command standard output channel to the specified file.
  • - *
  • ERR:file-path - Redirects the command standard error channel to the specified file.
  • - *
  • ENV:name=value - Defines an environment variable in the scope of the command.
  • - *
  • DIR:directory-path - Sets the path of the working directory for the command. This feature is not supported if the executing JVM is less than 1.3.
  • - *
- *

- * It is also possible to schedule the invocation of a method of a Java class in the scope of the parser ClassLoader. The method has to be static and it must accept an array of strings as its sole argument. To invoke a method of this kind the syntax is: - *

- * - *
- * scheduling-pattern java:className#methodName [args]
- * 
- *

- * The #methodName part can be omitted: in this case the main(String[]) method will be assumed. - *

- *

- * Please note that static methods are invoked within the scheduler same JVM, without spawning any external process. Thus IN, OUT, ERR, ENV and DIR options can't be applied. - *

- *

- * Invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is printed in the application standard error channel. - *

- *

- * Valid examples: - *

- * - *
- * 0 5 * * * sol.exe
- * 0,30 * * * * OUT:C:\ping.txt ping 10.9.43.55
- * 0,30 4 * * * "OUT:C:\Documents and Settings\Carlo\ping.txt" ping 10.9.43.55
- * 0 3 * * * ENV:JAVA_HOME=C:\jdks\1.4.2_15 DIR:C:\myproject OUT:C:\myproject\build.log C:\myproject\build.bat "Nightly Build"
- * 0 4 * * * java:mypackage.MyClass#startApplication myOption1 myOption2
- * 
- * - * @author Carlo Pelliccia - * @since 2.0 - */ -public class CronParser -{ - /** - * Instantiation prohibited. - */ - private CronParser() - { - } - - /** - *

- * Builds a task list reading it from a file. - *

- *

- * The file is treated as UTF-8. If your source file is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source file are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param file The file. - * @return The task table parsed from the file. - * @throws IOException I/O error. - */ - public static TaskTable parse(File file) throws IOException - { - InputStream stream = null; - try - { - stream = new FileInputStream(file); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an URL. - *

- *

- * Contents fetched from the URL are treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the retrieved document are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param url The URL. - * @return The task table parsed from the contents fetched from the given URL. - * @throws IOException I/O error. - */ - public static TaskTable parse(URL url) throws IOException - { - InputStream stream = null; - try - { - stream = url.openStream(); - return parse(stream); - } - finally - { - if (stream != null) - { - try - { - stream.close(); - } - catch (Throwable t) - { - } - } - } - } - - /** - *

- * Builds a task list reading it from an input stream. - *

- *

- * The stream is treated as UTF-8. If your source is not UTF-8 encoded establish by yourself a {@link Reader} using the right charset and pass it to the {@link CronParser#parse(Reader)} method. - *

- *

- * Syntax and semantics errors in the source stream are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param stream The input stream. - * @return The task table parsed from the stream contents. - * @throws IOException I/O error. - */ - public static TaskTable parse(InputStream stream) throws IOException - { - return parse(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - - /** - *

- * Builds a task list reading it from a reader. - *

- *

- * Syntax and semantics errors in the source reader are not blocking. Invalid lines are discarded, and they cause just a stack trace to be printed in the standard error channel as a notification. - *

- * @param reader The reader. - * @return The task table parsed from the contents in the reader. - * @throws IOException I/O error. - */ - public static TaskTable parse(Reader reader) throws IOException - { - final TaskTable table = new TaskTable(); - final BufferedReader bufferedReader = new BufferedReader(reader); - try - { - String line; - while ((line = bufferedReader.readLine()) != null) - { - try - { - parseLine(table, line); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - } - finally - { - reader.close(); - } - return table; - } - - /** - * Parses a crontab-like line. - * @param table The table on which the parsed task will be stored, by side-effect. - * @param lineValue The crontab-like line. - * @throws Exception The supplied line doesn't represent a valid task line. - */ - public static void parseLine(TaskTable table, String lineValue) throws Exception - { - String line = lineValue.trim(); - if ((line.isEmpty()) || (line.charAt(0) == '#')) - { - return; - } - - // Detecting the pattern. - int size = line.length(); - String pattern = null; - for (int i = size; i >= 0; i--) - { - final String aux = line.substring(0, i); - if (SchedulingPattern.validate(aux)) - { - pattern = aux; - break; - } - } - if (pattern == null) - { - throw new Exception("Invalid cron line: " + line); - } - - line = line.substring(pattern.length()); - size = line.length(); - - // Splitting the line - final List splitted = new ArrayList<>(); - StringBuilder current = null; - boolean quotes = false; - for (int i = 0; i < size; i++) - { - final char c = line.charAt(i); - if (current == null) - { - if (c == '"') - { - current = new StringBuilder(); - quotes = true; - } - else if (c > ' ') - { - current = new StringBuilder(); - current.append(c); - quotes = false; - } - } - else - { - boolean closeCurrent; - if (quotes) - { - closeCurrent = (c == '"'); - } - else - { - closeCurrent = (c <= ' '); - } - if (closeCurrent) - { - if (current.length() > 0) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - } - current = null; - } - else - { - current.append(c); - } - } - } - - if ((current != null) && (current.length() > 0)) - { - String str = current.toString(); - if (quotes) - { - str = escape(str); - } - splitted.add(str); - current = null; - } - - // Analyzing - size = splitted.size(); - int status = 0; - // Status values: - // 0 -> fetching environment variables, working directory and channels - // 1 -> fetching the command and its arguments - String dirString = null; - File stdinFile = null; - File stdoutFile = null; - File stderrFile = null; - final List envsList = new ArrayList<>(); - String command = null; - final List argsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - { - final String tk = splitted.get(i); - - // Check the local status. - if (status == 0) - { - // Environment variables, working directory and channels - if (tk.startsWith("ENV:")) - { - envsList.add(tk.substring(4)); - continue; - } - else if (tk.startsWith("DIR:")) - { - dirString = tk.substring(4); - continue; - } - else if (tk.startsWith("IN:")) - { - stdinFile = new File(tk.substring(3)); - continue; - } - else if (tk.startsWith("OUT:")) - { - stdoutFile = new File(tk.substring(4)); - continue; - } - else if (tk.startsWith("ERR:")) - { - stderrFile = new File(tk.substring(4)); - continue; - } - else - { - status = 1; - } - } - if (status == 1) - { - // Command or argument? - if (command == null) - { - command = tk; - } - else - { - argsList.add(tk); - } - } - } - - // Task preparing. - Task task; - - // Command evaluation. - if (command == null) - { - // No command! - throw new Exception("Invalid cron line: " + line); - } - else if (command.startsWith("java:")) - { - // Java inner-process. - String className = command.substring(5); - if (className.isEmpty()) - { - throw new Exception("Invalid Java class name on line: " + line); - } - String methodName; - final int sep = className.indexOf('#'); - if (sep == -1) - { - methodName = "main"; - } - else - { - methodName = className.substring(sep + 1); - className = className.substring(0, sep); - if (methodName.isEmpty()) - { - throw new Exception("Invalid Java method name on line: " + line); - } - } - final String[] args = new String[argsList.size()]; - for (int i = 0; i < argsList.size(); i++) - { - args[i] = argsList.get(i); - } - task = new StaticMethodTask(className, methodName, args); - } - else - { - // External command. - final String[] cmdarray = new String[1 + argsList.size()]; - cmdarray[0] = command; - for (int i = 0; i < argsList.size(); i++) - { - cmdarray[i + 1] = argsList.get(i); - } - - // Environments. - String[] envs = null; - size = envsList.size(); - if (size > 0) - { - envs = new String[size]; - for (int i = 0; i < size; i++) - { - envs[i] = envsList.get(i); - } - } - - // Working directory. - File dir = null; - if (dirString != null) - { - dir = new File(dirString); - if (!dir.exists() || !dir.isDirectory()) - { - throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); - } - } - - // Builds the task. - final ProcessTask process = new ProcessTask(cmdarray, envs, dir); - - // Channels. - if (stdinFile != null) - { - process.setStdinFile(stdinFile); - } - if (stdoutFile != null) - { - process.setStdoutFile(stdoutFile); - } - if (stderrFile != null) - { - process.setStderrFile(stderrFile); - } - task = process; - } - - // End. - table.add(new SchedulingPattern(pattern), task); - } - - /** - * Escapes special chars occurrences. - * @param str The input stream. - * @return The decoded output stream. - */ - private static String escape(String str) - { - final int size = str.length(); - final StringBuilder b = new StringBuilder(); - for (int i = 0; i < size; i++) - { - int skip = 0; - final char c = str.charAt(i); - if ((c == '\\') && (i < (size - 1))) - { - final char d = str.charAt(i + 1); - if (d == '"') - { - b.append('"'); - skip = 2; - } - else if (d == '\\') - { - b.append('\\'); - skip = 2; - } - else if (d == '/') - { - b.append('/'); - skip = 2; - } - else if (d == 'b') - { - b.append('\b'); - skip = 2; - } - else if (d == 'f') - { - b.append('\f'); - skip = 2; - } - else if (d == 'n') - { - b.append('\n'); - skip = 2; - } - else if (d == 'r') - { - b.append('\r'); - skip = 2; - } - else if (d == 't') - { - b.append('\t'); - skip = 2; - } - else if (d == 'u') - { - if (i < (size - 5)) - { - final String hex = str.substring(i + 2, i + 6); - try - { - final int code = Integer.parseInt(hex, 16); - if (code >= 0) - { - b.append((char) code); - skip = 6; - } - } - catch (NumberFormatException e) - { - } - } - } - } - if (skip == 0) - { - b.append(c); - } - else - { - i += (skip - 1); - } - } - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java deleted file mode 100644 index 99250d9a1c..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/DayOfMonthValueMatcher.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, checks whether the last-day-of-month setting applies. - *

- * @author Paul Fernley - */ -class DayOfMonthValueMatcher extends IntArrayValueMatcher -{ - private static final int[] lastDays = - { - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - }; - - /** - * Builds the ValueMatcher. - * @param values An ArrayList of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list or the last-day-of-month setting applies. - */ - public DayOfMonthValueMatcher(List values) - { - super(values); - } - - /** - * Returns true if the given value is included in the matcher list or the last-day-of-month setting applies. - * @param value - * @param month - * @param isLeapYear - * @return - */ - public boolean match(int value, int month, boolean isLeapYear) - { - return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); - } - - public boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) - { - if (isLeapYear && (month == 2)) - { - return value == 29; - } - return value == lastDays[month - 1]; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java deleted file mode 100644 index 237b664827..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/FileTaskCollector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation, reading the task list from a group of files. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class FileTaskCollector implements TaskCollector -{ - /** - * File list. - */ - private final List files = new ArrayList<>(); - - /** - * Adds a file. - * @param file The file. - */ - public synchronized void addFile(File file) - { - files.add(file); - } - - /** - * Removes a file. - * @param file The file. - */ - public synchronized void removeFile(File file) - { - files.remove(file); - } - - /** - * Returns the file list. - * @return The file list. - */ - public synchronized File[] getFiles() - { - final int size = files.size(); - final File[] ret = new File[size]; - for (int i = 0; i < size; i++) - { - ret[i] = files.get(i); - } - return ret; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = files.size(); - for (int i = 0; i < size; i++) - { - final File f = files.get(i); - TaskTable aux = null; - try - { - aux = CronParser.parse(f); - } - catch (IOException e) - { - final Exception e1 = new Exception("Cannot parse cron file: " + f.getAbsolutePath(), e); - e1.printStackTrace(); - } - if (aux != null) - { - final int auxSize = aux.size(); - for (int j = 0; j < auxSize; j++) - { - ret.add(aux.getSchedulingPattern(j), aux.getTask(j)); - } - } - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java deleted file mode 100644 index f6292e5db6..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/GUIDGenerator.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.UnknownHostException; -import java.util.Enumeration; - -/** - * A GUID generator. - * @author Carlo Pelliccia - * @since 2.0 - */ -class GUIDGenerator -{ - /** - * The machine descriptor, which is used to identified the underlying hardware machine. - */ - private static String MACHINE_DESCRIPTOR = getMachineDescriptor(); - - /** - * Generates a GUID (48 chars). - * @return The generated GUID. - */ - public static String generate() - { - final StringBuilder id = new StringBuilder(); - encode(id, MACHINE_DESCRIPTOR); - encode(id, Runtime.getRuntime()); - encode(id, Thread.currentThread()); - encode(id, System.currentTimeMillis()); - encode(id, getRandomInt()); - return id.toString(); - } - - /** - * Calculates a machine id, as an integer value. - * @return The calculated machine id. - */ - private static String getMachineDescriptor() - { - final StringBuilder descriptor = new StringBuilder(); - descriptor.append(System.getProperty("os.name")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.arch")); - descriptor.append("::"); - descriptor.append(System.getProperty("os.version")); - descriptor.append("::"); - descriptor.append(System.getProperty("user.name")); - descriptor.append("::"); - final StringBuilder b = buildNetworkInterfaceDescriptor(); - if (b != null) - { - descriptor.append(b); - } - else - { - // plain old InetAddress... - InetAddress addr; - try - { - addr = InetAddress.getLocalHost(); - descriptor.append(addr.getHostAddress()); - } - catch (UnknownHostException e) - { - } - } - return descriptor.toString(); - } - - /** - * Builds a descriptor fragment using the {@link NetworkInterface} class, available since Java 1.4. - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder buildNetworkInterfaceDescriptor() - { - Enumeration e1; - try - { - e1 = NetworkInterface.getNetworkInterfaces(); - } - catch (Throwable t) - { - // not available - return null; - } - final StringBuilder b = new StringBuilder(); - while (e1.hasMoreElements()) - { - final NetworkInterface ni = (NetworkInterface) e1.nextElement(); - final StringBuilder b1 = getMACAddressDescriptor(ni); - final StringBuilder b2 = getInetAddressDescriptor(ni); - final StringBuilder b3 = new StringBuilder(); - if (b1 != null) - { - b3.append(b1); - } - if (b2 != null) - { - if (b3.length() > 0) - { - b3.append('='); - } - b3.append(b2); - } - if (b3.length() > 0) - { - if (b.length() > 0) - { - b.append(';'); - } - b.append(b3); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine MAC address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getMACAddressDescriptor(NetworkInterface ni) - { - byte[] haddr; - try - { - haddr = ni.getHardwareAddress(); - } - catch (Throwable t) - { - // not available. - haddr = null; - } - final StringBuilder b = new StringBuilder(); - if (haddr != null) - { - for (byte element : haddr) - { - if (b.length() > 0) - { - b.append("-"); - } - final String hex = Integer.toHexString(0xff & element); - if (hex.length() == 1) - { - b.append('0'); - } - b.append(hex); - } - } - return b; - } - - /** - * Builds a descriptor fragment using the machine inet address. - * @param ni NetworkInterface - * @return A descriptor fragment, or null if the method fails. - */ - private static StringBuilder getInetAddressDescriptor(NetworkInterface ni) - { - final StringBuilder b = new StringBuilder(); - final Enumeration e2 = ni.getInetAddresses(); - while (e2.hasMoreElements()) - { - final InetAddress addr = (InetAddress) e2.nextElement(); - if (b.length() > 0) - { - b.append(','); - } - b.append(addr.getHostAddress()); - } - return b; - } - - /** - * Returns a random integer value. - * @return A random integer value. - */ - private static int getRandomInt() - { - return (int) Math.round((Math.random() * Integer.MAX_VALUE)); - } - - /** - * Encodes an object and appends it to the buffer. - * @param b The buffer. - * @param obj The object. - */ - private static void encode(StringBuilder b, Object obj) - { - encode(b, obj.hashCode()); - } - - /** - * Encodes an integer value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, int value) - { - final String hex = Integer.toHexString(value); - final int hexSize = hex.length(); - for (int i = 8; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } - - /** - * Encodes a long value and appends it to the buffer. - * @param b The buffer. - * @param value The value. - */ - private static void encode(StringBuilder b, long value) - { - final String hex = Long.toHexString(value); - final int hexSize = hex.length(); - for (int i = 16; i > hexSize; i--) - { - b.append('0'); - } - b.append(hex); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java deleted file mode 100644 index 484b3ec5a6..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/IntArrayValueMatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.List; - -/** - *

- * A ValueMatcher whose rules are in a plain array of integer values. When asked to validate a value, this ValueMatcher checks if it is in the array. - *

- * @author Carlo Pelliccia - */ -class IntArrayValueMatcher implements ValueMatcher -{ - /** - * The accepted values. - */ - private final int[] values; - - /** - * Builds the ValueMatcher. - * @param integers An List of Integer elements, one for every value accepted by the matcher. The match() method will return true only if its parameter will be one of this list. - */ - public IntArrayValueMatcher(List integers) - { - final int size = integers.size(); - values = new int[size]; - for (int i = 0; i < size; i++) - { - try - { - values[i] = ((Integer) integers.get(i)).intValue(); - } - catch (Exception e) - { - throw new IllegalArgumentException(e.getMessage()); - } - } - } - - /** - * Returns true if the given value is included in the matcher list. - * @param value - * @return - */ - @Override - public boolean match(int value) - { - for (int value2 : values) - { - if (value2 == value) - { - return true; - } - } - return false; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java deleted file mode 100644 index 16c4e72ebc..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/InvalidPatternException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This kind of exception is thrown if an invalid scheduling pattern is encountered by the scheduler. - *

- * @author Carlo Pelliccia - */ -public class InvalidPatternException extends RuntimeException -{ - /** - * Package-reserved construction. - */ - InvalidPatternException() - { - } - - /** - * Package-reserved construction. - * @param message String - */ - InvalidPatternException(String message) - { - super(message); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java deleted file mode 100644 index 6f735db8a8..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/LauncherThread.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * LauncherThreads are used by {@link Scheduler} instances. A LauncherThread retrieves a list of task from a set of {@link TaskCollector}s. Then it launches, within a separate {@link TaskExecutor}, every retrieved task whose scheduling pattern matches the given reference time. - * @author Carlo Pelliccia - * @since 2.0 - */ -class LauncherThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private final Scheduler scheduler; - - /** - * Task collectors, used to retrieve registered tasks. - */ - private final TaskCollector[] collectors; - - /** - * A reference time for task launching. - */ - private final long referenceTimeInMillis; - - /** - * Builds the launcher. - * @param scheduler The owner scheduler. - * @param collectors Task collectors, used to retrieve registered tasks. - * @param referenceTimeInMillis A reference time for task launching. - */ - public LauncherThread(Scheduler scheduler, TaskCollector[] collectors, long referenceTimeInMillis) - { - this.scheduler = scheduler; - this.collectors = collectors; - this.referenceTimeInMillis = referenceTimeInMillis; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::launcher[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - outer: for (TaskCollector collector : collectors) - { - final TaskTable taskTable = collector.getTasks(); - final int size = taskTable.size(); - for (int j = 0; j < size; j++) - { - if (isInterrupted()) - { - break outer; - } - final SchedulingPattern pattern = taskTable.getSchedulingPattern(j); - if (pattern.match(scheduler.getTimeZone(), referenceTimeInMillis)) - { - final Task task = taskTable.getTask(j); - scheduler.spawnExecutor(task); - } - } - } - // Notifies completed. - scheduler.notifyLauncherCompleted(this); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java deleted file mode 100644 index 01d063045a..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/MemoryTaskCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A {@link TaskCollector} implementation managing a task list in memory. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class MemoryTaskCollector implements TaskCollector -{ - /** - * Size. - */ - private final int size = 0; - - /** - * The inner scheduling pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * The inner task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * IDs for task-pattern couples. - */ - private final List ids = new ArrayList<>(); - - /** - * Counts how many task are currently collected by this collector. - * @return The size of the currently collected task list. - */ - public synchronized int size() - { - return size; - } - - /** - * Adds a pattern and a task to the collector. - * @param pattern The scheduling pattern. - * @param task The task. - * @return An ID for the scheduled operation. - */ - public synchronized String add(SchedulingPattern pattern, Task task) - { - final String id = GUIDGenerator.generate(); - patterns.add(pattern); - tasks.add(task); - ids.add(id); - return id; - } - - /** - * Updates a scheduling pattern in the collector. - * @param id The ID of the scheduled couple. - * @param pattern SchedulingPattern - */ - public synchronized void update(String id, SchedulingPattern pattern) - { - final int index = ids.indexOf(id); - if (index > -1) - { - patterns.set(index, pattern); - } - } - - /** - * Removes a task and its scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @throws IndexOutOfBoundsException - */ - public synchronized void remove(String id) throws IndexOutOfBoundsException - { - final int index = ids.indexOf(id); - if (index > -1) - { - tasks.remove(index); - patterns.remove(index); - ids.remove(index); - } - } - - /** - * Retrieves a task from the collector. - * @param id The ID of the scheduled couple. - * @return The task with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized Task getTask(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return tasks.get(index); - } - return null; - } - - /** - * Retrieves a scheduling pattern from the collector. - * @param id The ID of the scheduled couple. - * @return The scheduling pattern with the specified assigned ID, or null if it doesn't exist. - */ - public synchronized SchedulingPattern getSchedulingPattern(String id) - { - final int index = ids.indexOf(id); - if (index > -1) - { - return patterns.get(index); - } - return null; - } - - /** - * Implements {@link TaskCollector#getTasks()}. - */ - @Override - public synchronized TaskTable getTasks() - { - final TaskTable ret = new TaskTable(); - final int size = tasks.size(); - for (int i = 0; i < size; i++) - { - final Task t = tasks.get(i); - final SchedulingPattern p = patterns.get(i); - ret.add(p, t); - } - return ret; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java deleted file mode 100644 index 7c8d594abe..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/PastPredictor.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * This file is part of the L2J Mobius project. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * @author UnAfraid - */ -public class PastPredictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern _schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long _time; - - /** - * The time zone for the prediction. - */ - private TimeZone _timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, long start) throws InvalidPatternException - { - _schedulingPattern = new SchedulingPattern(schedulingPattern); - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public PastPredictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, long start) - { - _schedulingPattern = schedulingPattern; - _time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public PastPredictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - _timeZone = timeZone; - } - - /** - * It returns the previous matching moment as a millis value. - * @return The previous matching moment as a millis value. - */ - public synchronized long prevMatchingTime() - { - // Go a minute back. - _time -= 60000; - // Is it matching? - if (_schedulingPattern.match(_time)) - { - return _time; - } - // Go through the matcher groups. - final int size = _schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(_time); - c.setTimeZone(_timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = _schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = _schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = _schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = _schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = _schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute--; - if (minute < 0) - { - minute = 59; - hour--; - } - } - if (hour < 0) - { - hour = 23; - dayOfMonth--; - } - if (hourMatcher.match(hour)) - { - break; - } - hour--; - minute = 59; - } - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - } - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth--; - hour = 23; - minute = 59; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month--; - dayOfMonth = 31; - hour = 23; - minute = 59; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - int oldDayOfMonth = dayOfMonth; - int oldMonth = month; - int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - do - { - dayOfMonth = oldDayOfMonth - 1; - month = oldMonth; - year = oldYear; - c = new GregorianCalendar(); - c.setTimeZone(_timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - oldDayOfMonth = dayOfMonth; - oldMonth = month; - oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - } - while ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)); - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth--; - hour = 23; - minute = 59; - if (dayOfMonth < 1) - { - dayOfMonth = 31; - month--; - if (month < Calendar.JANUARY) - { - month = Calendar.DECEMBER; - year--; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - _time = min; - // Here it is. - return _time; - } - - /** - * It returns the previous matching moment as a {@link Date} object. - * @return The previous matching moment as a {@link Date} object. - */ - public synchronized Date prevMatchingDate() - { - return new Date(prevMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java deleted file mode 100644 index 61f4f9aaa4..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Predictor.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - *

- * A predictor is able to predict when a scheduling pattern will be matched. - *

- *

- * Suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. You can predict the next n execution of the task using a Predictor instance: - *

- * - *
- * String pattern = "0 3 * jan-jun,sep-dec mon-fri";
- * Predictor p = new Predictor(pattern);
- * for (int i = 0; i < n; i++)
- * {
- * 	System.out.println(p.nextMatchingDate());
- * }
- * 
- * - * @author Carlo Pelliccia - * @since 1.1 - */ -public class Predictor -{ - /** - * The scheduling pattern on which the predictor works. - */ - private final SchedulingPattern schedulingPattern; - - /** - * The start time for the next prediction. - */ - private long time; - - /** - * The time zone for the prediction. - */ - private TimeZone timeZone = TimeZone.getDefault(); - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, long start) throws InvalidPatternException - { - this.schedulingPattern = new SchedulingPattern(schedulingPattern); - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern, Date start) throws InvalidPatternException - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @throws InvalidPatternException In the given scheduling pattern isn't valid. - */ - public Predictor(String schedulingPattern) throws InvalidPatternException - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, long start) - { - this.schedulingPattern = schedulingPattern; - time = (start / (1000 * 60)) * 1000 * 60; - } - - /** - * It builds a predictor with the given scheduling pattern and start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @param start The start time of the prediction. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern, Date start) - { - this(schedulingPattern, start.getTime()); - } - - /** - * It builds a predictor with the given scheduling pattern and the current system time as the prediction start time. - * @param schedulingPattern The pattern on which the prediction will be based. - * @since 2.0 - */ - public Predictor(SchedulingPattern schedulingPattern) - { - this(schedulingPattern, System.currentTimeMillis()); - } - - /** - * Sets the time zone for predictions. - * @param timeZone The time zone for predictions. - * @since 2.2.5 - */ - public void setTimeZone(TimeZone timeZone) - { - this.timeZone = timeZone; - } - - /** - * It returns the next matching moment as a millis value. - * @return The next matching moment as a millis value. - */ - public synchronized long nextMatchingTime() - { - // Go a minute ahead. - time += 60000; - // Is it matching? - if (schedulingPattern.match(time)) - { - return time; - } - // Go through the matcher groups. - final int size = schedulingPattern.matcherSize; - final long[] times = new long[size]; - for (int k = 0; k < size; k++) - { - // Ok, split the time! - GregorianCalendar c = new GregorianCalendar(); - c.setTimeInMillis(time); - c.setTimeZone(timeZone); - int minute = c.get(Calendar.MINUTE); - int hour = c.get(Calendar.HOUR_OF_DAY); - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - int month = c.get(Calendar.MONTH); - int year = c.get(Calendar.YEAR); - // Gets the matchers. - final ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); - final ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); - final ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); - final ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); - final ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); - for (;;) - { // day of week - for (;;) - { // month - for (;;) - { // day of month - for (;;) - { // hour - for (;;) - { // minutes - if (minuteMatcher.match(minute)) - { - break; - } - minute++; - if (minute > 59) - { - minute = 0; - hour++; - } - } - if (hour > 23) - { - hour = 0; - dayOfMonth++; - } - if (hourMatcher.match(hour)) - { - break; - } - hour++; - minute = 0; - } - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - } - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) - { - final DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; - if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - } - else if (dayOfMonthMatcher.match(dayOfMonth)) - { - break; - } - else - { - dayOfMonth++; - hour = 0; - minute = 0; - } - } - if (monthMatcher.match(month + 1)) - { - break; - } - month++; - dayOfMonth = 1; - hour = 0; - minute = 0; - } - // Is this ok? - c = new GregorianCalendar(); - c.setTimeZone(timeZone); - c.set(Calendar.MINUTE, minute); - c.set(Calendar.HOUR_OF_DAY, hour); - c.set(Calendar.DAY_OF_MONTH, dayOfMonth); - c.set(Calendar.MONTH, month); - c.set(Calendar.YEAR, year); - // Day-of-month/month/year compatibility check. - final int oldDayOfMonth = dayOfMonth; - final int oldMonth = month; - final int oldYear = year; - dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - month = c.get(Calendar.MONTH); - year = c.get(Calendar.YEAR); - if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) - { - // Take another spin! - continue; - } - // Day of week. - final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); - if (dayOfWeekMatcher.match(dayOfWeek - 1)) - { - break; - } - dayOfMonth++; - hour = 0; - minute = 0; - if (dayOfMonth > 31) - { - dayOfMonth = 1; - month++; - if (month > Calendar.DECEMBER) - { - month = Calendar.JANUARY; - year++; - } - } - } - // Seems it matches! - times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; - } - // Which one? - long min = Long.MAX_VALUE; - for (int k = 0; k < size; k++) - { - if (times[k] < min) - { - min = times[k]; - } - } - // Updates the object current time value. - time = min; - // Here it is. - return time; - } - - /** - * It returns the next matching moment as a {@link Date} object. - * @return The next matching moment as a {@link Date} object. - */ - public synchronized Date nextMatchingDate() - { - return new Date(nextMatchingTime()); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java deleted file mode 100644 index ffd8cbe9bf..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/ProcessTask.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

- * A built-in {@link Task} implementation which can be used to run an external process. - *

- * @author Carlo Pelliccia - * @since 2.1 - */ -public class ProcessTask extends Task -{ - /** - * The command to launch. - */ - private String[] command; - - /** - * Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - private String[] envs; - - /** - * Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - private File directory; - - /** - * Standard input file (optional). - */ - private File stdinFile = null; - - /** - * Standard output file (optional). - */ - private File stdoutFile = null; - - /** - * Standard error file (optional). - */ - private File stderrFile = null; - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - * @param directory Working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public ProcessTask(String[] command, String[] envs, File directory) - { - this.command = command; - this.envs = envs; - this.directory = directory; - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - * @param envs Environment variables for the spawned process, in the form name=value. If null the process will inherit the current JVM environment variables. - */ - public ProcessTask(String[] command, String[] envs) - { - this(command, envs, null); - } - - /** - * Creates the task. - * @param command The command to launch and its arguments. - */ - public ProcessTask(String[] command) - { - this(command, null, null); - } - - /** - * Creates the task. - * @param command The command to launch. - */ - public ProcessTask(String command) - { - this(new String[] - { - command - }, null, null); - } - - /** - * Returns true. - */ - @Override - public boolean canBeStopped() - { - return true; - } - - /** - * Returns the command executed by this task. - * @return The command executed by this task. - */ - public String[] getCommand() - { - return command; - } - - /** - * Sets the command executed by this task. - * @param command The command executed by this task. - */ - public void setCommand(String[] command) - { - this.command = command; - } - - /** - * Returns the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @return The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public String[] getEnvs() - { - return envs; - } - - /** - * Sets the environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - * @param envs The environment variables, in the name=value form, used by the task to run its process. If null the process will inherit the current JVM environment variables. - */ - public void setEnvs(String[] envs) - { - this.envs = envs; - } - - /** - * Resturns the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @return The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public File getDirectory() - { - return directory; - } - - /** - * Sets the working directory for the spawned process. If null the process will inherit the current JVM working directory. - * @param directory The working directory for the spawned process. If null the process will inherit the current JVM working directory. - */ - public void setDirectory(File directory) - { - this.directory = directory; - } - - /** - * Returns the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @return The standard input file (optional). - */ - public File getStdinFile() - { - return stdinFile; - } - - /** - * Sets the standard input file (optional). If supplied, the standard input channel of the spawned process will be read from the given file. - * @param stdinFile The standard input file (optional). - */ - public void setStdinFile(File stdinFile) - { - this.stdinFile = stdinFile; - } - - /** - * Sets the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @param stdoutFile The standard output file (optional). - */ - public void setStdoutFile(File stdoutFile) - { - this.stdoutFile = stdoutFile; - } - - /** - * Returns the standard output file (optional). If supplied, the standard output channel of the spawned process will be written in the given file. - * @return The standard output file (optional). - */ - public File getStdoutFile() - { - return stdoutFile; - } - - /** - * Sets the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @param stderrFile The standard error file (optional). - */ - public void setStderrFile(File stderrFile) - { - this.stderrFile = stderrFile; - } - - /** - * Returns the standard error file (optional). If supplied, the standard error channel of the spawned process will be written in the given file. - * @return The standard error file (optional). - */ - public File getStderrFile() - { - return stderrFile; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. Runs the given command as a separate process and waits for its end. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - Process p; - try - { - p = exec(); - } - catch (IOException e) - { - throw new RuntimeException(toString() + " cannot be started", e); - } - final InputStream in = buildInputStream(stdinFile); - final OutputStream out = buildOutputStream(stdoutFile); - final OutputStream err = buildOutputStream(stderrFile); - if (in != null) - { - final StreamBridge b = new StreamBridge(in, p.getOutputStream()); - b.start(); - } - if (out != null) - { - final StreamBridge b = new StreamBridge(p.getInputStream(), out); - b.start(); - } - if (err != null) - { - final StreamBridge b = new StreamBridge(p.getErrorStream(), err); - b.start(); - } - int r; - try - { - r = p.waitFor(); - } - catch (InterruptedException e) - { - throw new RuntimeException(toString() + " has been interrupted"); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (Throwable e) - { - } - } - if (out != null) - { - try - { - out.close(); - } - catch (Throwable e) - { - } - } - if (err != null) - { - try - { - err.close(); - } - catch (Throwable e) - { - } - } - p.destroy(); - } - if (r != 0) - { - throw new RuntimeException(toString() + " returns with error code " + r); - } - } - - /** - * Executes the command. - * @return The launched Process. - * @throws IOException If an I/O error occurs. - */ - private Process exec() throws IOException - { - final Runtime rt = Runtime.getRuntime(); - Process p; - try - { - // java 1.3+ - p = rt.exec(command, envs, directory); - } - catch (NoSuchMethodError e) - { - // java 1.2 - p = rt.exec(command, envs); - } - return p; - } - - /** - * Prepares an {@link InputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private InputStream buildInputStream(File file) - { - if (file != null) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prepares an {@link OutputStream} on a file and returns it. - * @param file The file. - * @return The stream, or null if the file is not found. - */ - private OutputStream buildOutputStream(File file) - { - if (file != null) - { - try - { - return new FileOutputStream(file); - } - catch (FileNotFoundException e) - { - e.printStackTrace(); - return null; - } - } - return null; - } - - /** - * Prints in the returned string the elements contained in the given string array. - * @param arr The array. - * @return A string representing the supplied array contents. - */ - private static String listStrings(String[] arr) - { - if (arr == null) - { - return "null"; - } - final StringBuilder b = new StringBuilder(); - b.append('['); - for (int i = 0; i < arr.length; i++) - { - if (i > 0) - { - b.append(", "); - } - b.append(arr[i]); - } - b.append(']'); - return b.toString(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("cmd="); - b.append(listStrings(command)); - b.append(", env="); - b.append(listStrings(envs)); - b.append(", "); - b.append("dir="); - b.append(directory); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java deleted file mode 100644 index 5e42a82c2b..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/RunnableTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A {@link Task} implementation acting as a wrapper around a {@link Runnable} object. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class RunnableTask extends Task -{ - /** - * The wrapped runnable object. - */ - private final Runnable runnable; - - /** - * Builds the task. - * @param runnable The wrapped Runnable object. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public RunnableTask(Runnable runnable) throws InvalidPatternException - { - this.runnable = runnable; - } - - /** - * Returns the wrapped Runnable object. - * @return The wrapped Runnable object. - */ - public Runnable getRunnable() - { - return runnable; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}, launching the {@link Runnable#run()} method on the wrapped object. - */ - @Override - public void execute(TaskExecutionContext context) - { - runnable.run(); - } - - /** - * Overrides {@link Object#toString()}. - */ - @Override - public String toString() - { - final StringBuilder b = new StringBuilder(); - b.append("Task["); - b.append("runnable="); - b.append(runnable); - b.append("]"); - return b.toString(); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java deleted file mode 100644 index efd112dbda..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Scheduler.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.TimeZone; - -/** - *

- * The cron4j scheduler. - *

- * @author Carlo Pelliccia - */ -public class Scheduler -{ - /** - * A GUID for this scheduler. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The time zone applied by the scheduler. - */ - private TimeZone timezone = null; - - /** - * The daemon flag. If true the scheduler and its spawned threads acts like daemons. - */ - private boolean daemon = false; - - /** - * The state flag. If true the scheduler is started and running, otherwise it is paused and no task is launched. - */ - private boolean started = false; - - /** - * Registered {@link TaskCollector}s list. - */ - private final List collectors = new ArrayList<>(); - - /** - * The {@link MemoryTaskCollector} used for memory stored tasks. Represented here for convenience, it is also the first element in the {@link Scheduler#collectors} list. - */ - private final MemoryTaskCollector memoryTaskCollector = new MemoryTaskCollector(); - - /** - * The {@link FileTaskCollector} used for reading tasks from files. Represented here for convenience, it is also the second element in the {@link Scheduler#collectors} list. - */ - private final FileTaskCollector fileTaskCollector = new FileTaskCollector(); - - /** - * Registered {@link SchedulerListener}s list. - */ - private final List listeners = new ArrayList<>(); - - /** - * The thread checking the clock and requesting the spawning of launcher threads. - */ - private TimerThread timer = null; - - /** - * Currently running {@link LauncherThread} instances. - */ - private List launchers = null; - - /** - * Currently running {@link TaskExecutor} instances. - */ - private List executors = null; - - /** - * Internal lock, used to synchronize status-aware operations. - */ - private final Object lock = new Object(); - - /** - * It builds and prepares a brand new Scheduler instance. - */ - public Scheduler() - { - collectors.add(memoryTaskCollector); - collectors.add(fileTaskCollector); - } - - /** - * It returns the GUID for this scheduler. - * @return The GUID for this scheduler. - */ - public Object getGuid() - { - return guid; - } - - /** - *

- * Sets the time zone applied by the scheduler. - *

- *

- * Current system time is adapted to the supplied time zone before comparing it with registered scheduling patterns. The result is that any supplied scheduling pattern is treated according to the specified time zone. In example, suppose: - *

- *
    - *
  • System time: 10:00
  • - *
  • System time zone: GMT+1
  • - *
  • Scheduler time zone: GMT+3
  • - *
- *

- * The scheduler, before comparing system time with patterns, translates 10:00 from GMT+1 to GMT+3. It means that 10:00 becomes 12:00. The resulted time is then used by the scheduler to activate tasks. So, in the given configuration at the given moment, any task scheduled as 0 12 * * * - * will be executed, while any 0 10 * * * will not. - *

- * @param timezone The time zone applied by the scheduler. - */ - public void setTimeZone(TimeZone timezone) - { - this.timezone = timezone; - } - - /** - * Returns the time zone applied by the scheduler. - * @return The time zone applied by the scheduler. - */ - public TimeZone getTimeZone() - { - return timezone != null ? timezone : TimeZone.getDefault(); - } - - /** - * Tests whether this scheduler is a daemon scheduler. - * @return true if this scheduler is a daemon scheduler; false otherwise. - */ - public boolean isDaemon() - { - return daemon; - } - - /** - * Marks this scheduler daemon flag. When a scheduler is marked as a daemon scheduler it spawns only daemon threads. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the scheduler is started. - * @param on If true, the scheduler will spawn only daemon threads. - * @throws IllegalStateException If the scheduler is started. - */ - public void setDaemon(boolean on) throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - daemon = on; - } - } - - /** - * Tests if this scheduler is started. - * @return true if the scheduler is started, false if it is stopped. - */ - public boolean isStarted() - { - synchronized (lock) - { - return started; - } - } - - /** - * Adds a {@link File} instance to the scheduler. Every minute the file will be parsed. The scheduler will execute any declared task whose scheduling pattern matches the current system time. See {@link CronParser} documentation for informations about the file contents syntax. - * @param file The {@link File} instance. - */ - public void scheduleFile(File file) - { - fileTaskCollector.addFile(file); - } - - /** - * Removes a {@link File} instance previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @param file The {@link File} instance. - */ - public void descheduleFile(File file) - { - fileTaskCollector.removeFile(file); - } - - /** - * Returns an array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - * @return An array containing any {@link File} previously scheduled with the {@link Scheduler#scheduleFile(File)} method. - */ - public File[] getScheduledFiles() - { - return fileTaskCollector.getFiles(); - } - - /** - * Adds a custom {@link TaskCollector} instance to the scheduler. The supplied object, once added to the scheduler, will be query every minute for its task list. The scheduler will execute any of the returned tasks whose scheduling pattern matches the current system time. - * @param collector The custom {@link TaskCollector} instance. - */ - public void addTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.add(collector); - } - } - - /** - * Removes a previously registered custom {@link TaskCollector} instance. - * @param collector The custom {@link TaskCollector} instance. - */ - public void removeTaskCollector(TaskCollector collector) - { - synchronized (collectors) - { - collectors.remove(collector); - } - } - - /** - * Returns an array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - * @return An array containing any custom {@link TaskCollector} instance previously registered in the scheduler with the {@link Scheduler#addTaskCollector(TaskCollector)} method. - */ - public TaskCollector[] getTaskCollectors() - { - synchronized (collectors) - { - // Discard the first 2 elements in the list. - final int size = collectors.size() - 2; - final TaskCollector[] ret = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - ret[i] = collectors.get(i + 2); - } - return ret; - } - } - - /** - * Adds a {@link SchedulerListener} to the scheduler. A {@link SchedulerListener} is notified every time a task is launching, has succeeded or has failed. - * @param listener The listener. - */ - public void addSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @param listener The listener. - */ - public void removeSchedulerListener(SchedulerListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - * @return An array containing any {@link SchedulerListener} previously registered with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method. - */ - public SchedulerListener[] getSchedulerListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final SchedulerListener[] ret = new SchedulerListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns an array containing any currently executing task, in the form of {@link TaskExecutor} objects. Each running task is executed by a different thread. A {@link TaskExecutor} object allows the control of the running task. The inner {@link Task} representation could be retrieved, the - * status of the task could be detected and the thread could be interrupted using any standard {@link Thread} method ( {@link Thread#interrupt()}, {@link Thread#isAlive() etc}. - * @return An array containing any currently executing task, in the form of {@link TaskExecutor} objects. - */ - public TaskExecutor[] getExecutingTasks() - { - synchronized (executors) - { - final int size = executors.size(); - final TaskExecutor[] ret = new TaskExecutor[size]; - for (int i = 0; i < size; i++) - { - ret[i] = executors.get(i); - } - return ret; - } - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public String schedule(String schedulingPattern, Runnable task) throws InvalidPatternException - { - return schedule(schedulingPattern, new RunnableTask(task)); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @since 2.0 - */ - public String schedule(String schedulingPattern, Task task) throws InvalidPatternException - { - return schedule(new SchedulingPattern(schedulingPattern), task); - } - - /** - * This method schedules a task execution. - * @param schedulingPattern The scheduling pattern for the task. - * @param task The task, as a plain Runnable object. - * @return The task auto-generated ID assigned by the scheduler. This ID can be used later to reschedule and deschedule the task, and also to retrieve informations about it. - * @since 2.0 - */ - public String schedule(SchedulingPattern schedulingPattern, Task task) - { - return memoryTaskCollector.add(schedulingPattern, task); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - * @deprecated Use {@link Scheduler#reschedule(String, String)}. - */ - @Deprecated - public void reschedule(Object id, String schedulingPattern) throws InvalidPatternException - { - reschedule((String) id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @throws InvalidPatternException If the supplied pattern is not valid. - */ - public void reschedule(String id, String schedulingPattern) throws InvalidPatternException - { - reschedule(id, new SchedulingPattern(schedulingPattern)); - } - - /** - * This method changes the scheduling pattern of a task. - * @param id The ID assigned to the previously scheduled task. - * @param schedulingPattern The new scheduling pattern for the task. - * @since 2.0 - */ - public void reschedule(String id, SchedulingPattern schedulingPattern) - { - memoryTaskCollector.update(id, schedulingPattern); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - * @deprecated Use {@link Scheduler#deschedule(String)}. - */ - @Deprecated - public void deschedule(Object id) - { - deschedule((String) id); - } - - /** - * This methods cancels the scheduling of a task. - * @param id The ID of the task. - */ - public void deschedule(String id) - { - memoryTaskCollector.remove(id); - } - - /** - * This method retrieves a previously scheduled task. - * @param id The task ID. - * @return The requested task, or null if the task was not found. - * @since 2.0 - */ - public Task getTask(String id) - { - return memoryTaskCollector.getTask(id); - } - - /** - * This method retrieves a previously scheduled task scheduling pattern. - * @param id The task ID. - * @return The requested scheduling pattern, or null if the task was not found. - * @since 2.0 - */ - public SchedulingPattern getSchedulingPattern(String id) - { - return memoryTaskCollector.getSchedulingPattern(id); - } - - /** - * This method retrieves the Runnable object of a previously scheduled task. - * @param id The task ID. - * @return The Runnable object of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getTask(String)}. - */ - @Deprecated - public Runnable getTaskRunnable(Object id) - { - final Task task = getTask((String) id); - if (task instanceof RunnableTask) - { - final RunnableTask rt = (RunnableTask) task; - return rt.getRunnable(); - } - return null; - } - - /** - * This method retrieves the scheduling pattern of a previously scheduled task. - * @param id The task ID. - * @return The scheduling pattern of the task, or null if the task was not found. - * @deprecated Use {@link Scheduler#getSchedulingPattern(String)}. - */ - @Deprecated - public String getTaskSchedulingPattern(Object id) - { - return getSchedulingPattern((String) id).toString(); - } - - /** - * Executes immediately a task, without scheduling it. - * @param task The task. - * @return The {@link TaskExecutor} executing the given task. - * @throws IllegalStateException If the scheduler is not started. - */ - public TaskExecutor launch(Task task) - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - return spawnExecutor(task); - } - } - - /** - * This method starts the scheduler. When the scheduled is started the supplied tasks are executed at the given moment. - * @throws IllegalStateException Thrown if this scheduler is already started. - */ - public void start() throws IllegalStateException - { - synchronized (lock) - { - if (started) - { - throw new IllegalStateException("Scheduler already started"); - } - // Initializes required lists. - launchers = new ArrayList<>(); - executors = new ArrayList<>(); - // Starts the timer thread. - timer = new TimerThread(this); - timer.setDaemon(daemon); - timer.start(); - // Change the state of the scheduler. - started = true; - } - } - - /** - * This method stops the scheduler execution. Before returning, it waits the end of all the running tasks previously launched. Once the scheduler has been stopped it can be started again with a start() call. - * @throws IllegalStateException Thrown if this scheduler is not started. - */ - public void stop() throws IllegalStateException - { - synchronized (lock) - { - if (!started) - { - throw new IllegalStateException("Scheduler not started"); - } - // Interrupts the timer and waits for its death. - timer.interrupt(); - tillThreadDies(timer); - timer = null; - // Interrupts any running launcher and waits for its death. - for (;;) - { - LauncherThread launcher = null; - synchronized (launchers) - { - if (launchers.size() == 0) - { - break; - } - launcher = launchers.remove(0); - } - launcher.interrupt(); - tillThreadDies(launcher); - } - launchers = null; - // Interrupts any running executor and waits for its death. - // Before exiting wait for all the active tasks end. - for (;;) - { - TaskExecutor executor = null; - synchronized (executors) - { - if (executors.size() == 0) - { - break; - } - executor = executors.remove(0); - } - if (executor.canBeStopped()) - { - executor.stop(); - } - tillExecutorDies(executor); - } - executors = null; - // Change the state of the object. - started = false; - } - } - - // -- PACKAGE RESERVED METHODS -------------------------------------------- - - /** - * Starts a launcher thread. - * @param referenceTimeInMillis Reference time in millis for the launcher. - * @return The spawned launcher. - */ - LauncherThread spawnLauncher(long referenceTimeInMillis) - { - TaskCollector[] nowCollectors; - synchronized (collectors) - { - final int size = collectors.size(); - nowCollectors = new TaskCollector[size]; - for (int i = 0; i < size; i++) - { - nowCollectors[i] = collectors.get(i); - } - } - final LauncherThread l = new LauncherThread(this, nowCollectors, referenceTimeInMillis); - synchronized (launchers) - { - launchers.add(l); - } - l.setDaemon(daemon); - l.start(); - return l; - } - - /** - * Starts the given task within a task executor. - * @param task The task. - * @return The spawned task executor. - */ - TaskExecutor spawnExecutor(Task task) - { - final TaskExecutor e = new TaskExecutor(this, task); - synchronized (executors) - { - executors.add(e); - } - e.start(daemon); - return e; - } - - /** - * This method is called by a launcher thread to notify that the execution is completed. - * @param launcher The launcher which has completed its task. - */ - void notifyLauncherCompleted(LauncherThread launcher) - { - synchronized (launchers) - { - launchers.remove(launcher); - } - } - - /** - * This method is called by a task executor to notify that the execution is completed. - * @param executor The executor which has completed its task. - */ - void notifyExecutorCompleted(TaskExecutor executor) - { - synchronized (executors) - { - executors.remove(executor); - } - } - - /** - * Notifies every registered listener that a task is going to be launched. - * @param executor The task executor. - */ - void notifyTaskLaunching(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskLaunching(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has successfully completed. - * @param executor The task executor. - */ - void notifyTaskSucceeded(TaskExecutor executor) - { - synchronized (listeners) - { - final int size = listeners.size(); - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskSucceeded(executor); - } - } - } - - /** - * Notifies every registered listener that a task execution has failed due to an uncaught exception. - * @param executor The task executor. - * @param exception The exception. - */ - void notifyTaskFailed(TaskExecutor executor, Throwable exception) - { - synchronized (listeners) - { - final int size = listeners.size(); - if (size > 0) - { - for (int i = 0; i < size; i++) - { - final SchedulerListener l = listeners.get(i); - l.taskFailed(executor, exception); - } - } - else - { - // Logs on console if no one has been notified about it. - exception.printStackTrace(); - } - } - } - - // -- PRIVATE METHODS ----------------------------------------------------- - - /** - * It waits until the given thread is dead. It is similar to {@link Thread#join()}, but this one avoids {@link InterruptedException} instances. - * @param thread The thread. - */ - private void tillThreadDies(Thread thread) - { - boolean dead = false; - do - { - try - { - thread.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } - - /** - * It waits until the given task executor is dead. It is similar to {@link TaskExecutor#join()}, but this one avoids {@link InterruptedException} instances. - * @param executor The task executor. - */ - private void tillExecutorDies(TaskExecutor executor) - { - boolean dead = false; - do - { - try - { - executor.join(); - dead = true; - } - catch (InterruptedException e) - { - } - } - while (!dead); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java deleted file mode 100644 index fdcb0d8f05..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulerListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Implement this interface and register your instance with the {@link Scheduler#addSchedulerListener(SchedulerListener)} method to receive notifications about scheduled task executions. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface SchedulerListener -{ - /** - * This one is called by the scheduler when a task execution is starting. - * @param executor The task executor. - */ - void taskLaunching(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has been successfully completed. - * @param executor The task executor. - */ - void taskSucceeded(TaskExecutor executor); - - /** - * This one is called by the scheduler to notify that a task execution has failed. - * @param executor The task executor. - * @param exception The exception representing the failure notification. - */ - void taskFailed(TaskExecutor executor, Throwable exception); -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java deleted file mode 100644 index 939b173821..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPattern.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.StringTokenizer; -import java.util.TimeZone; - -/** - *

- * A UNIX crontab-like pattern is a string split in five space separated parts. Each part is intented as: - *

- *
    - *
  1. Minutes sub-pattern. During which minutes of the hour should the task been launched? The values range is from 0 to 59.
  2. - *
  3. Hours sub-pattern. During which hours of the day should the task been launched? The values range is from 0 to 23.
  4. - *
  5. Days of month sub-pattern. During which days of the month should the task been launched? The values range is from 1 to 31. The special value L can be used to recognize the last day of month.
  6. - *
  7. Months sub-pattern. During which months of the year should the task been launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", - * "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
  8. - *
  9. Days of week sub-pattern. During which days of the week should the task been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", - * "fri" and "sat".
  10. - *
- *

- * The star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used. - *

- *

- * Once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time. - *

- *

- * Some examples: - *

- *

- * 5 * * * *
- * This pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.). - *

- *

- * * * * * *
- * This pattern causes a task to be launched every minute. - *

- *

- * * 12 * * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday. - *

- *

- * * 12 16 * Mon
- * This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month. - *

- *

- * Every sub-pattern can contain two or more comma separated values. - *

- *

- * 59 11 * * 1,2,3,4,5
- * This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. - *

- *

- * Values intervals are admitted and defined using the minus character. - *

- *

- * 59 11 * * 1-5
- * This pattern is equivalent to the previous one. - *

- *

- * The slash character can be used to identify step values within a range. It can be used both in the form */c and a-b/c. The subpattern is matched every c values of the range 0,maxvalue or a-b. - *

- *

- * */5 * * * *
- * This pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). - *

- *

- * 3-18/5 * * * *
- * This pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). - *

- *

- * */15 9-17 * * *
- * This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). - *

- *

- * All the fresh described syntax rules can be used together. - *

- *

- * * 12 10-16/2 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month. - *

- *

- * * 12 1-15,17,20-25 * *
- * This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th. - *

- *

- * Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: - *

- *

- * 0 5 * * *|8 10 * * *|22 17 * * *
- * This pattern causes a task to be launched every day at 05:00, 10:08 and 17:22. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class SchedulingPattern -{ - /** - * The parser for the minute values. - */ - private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); - - /** - * The parser for the hour values. - */ - private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); - - /** - * The parser for the day of month values. - */ - private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); - - /** - * The parser for the month values. - */ - private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); - - /** - * The parser for the day of week values. - */ - private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); - - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - */ - public static boolean validate(String schedulingPattern) - { - try - { - new SchedulingPattern(schedulingPattern); - } - catch (InvalidPatternException e) - { - return false; - } - return true; - } - - /** - * The pattern as a string. - */ - private final String asString; - - /** - * The ValueMatcher list for the "minute" field. - */ - protected List minuteMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "hour" field. - */ - protected List hourMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of month" field. - */ - protected List dayOfMonthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "month" field. - */ - protected List monthMatchers = new ArrayList<>(); - - /** - * The ValueMatcher list for the "day of week" field. - */ - protected List dayOfWeekMatchers = new ArrayList<>(); - - /** - * How many matcher groups in this pattern? - */ - protected int matcherSize = 0; - - /** - * Builds a SchedulingPattern parsing it from a string. - * @param pattern The pattern as a crontab-like string. - * @throws InvalidPatternException If the supplied string is not a valid pattern. - */ - public SchedulingPattern(String pattern) throws InvalidPatternException - { - asString = pattern; - final StringTokenizer st1 = new StringTokenizer(pattern, "|"); - if (st1.countTokens() < 1) - { - throw new InvalidPatternException("invalid pattern: \"" + pattern + "\""); - } - while (st1.hasMoreTokens()) - { - final String localPattern = st1.nextToken(); - final StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); - if (st2.countTokens() != 5) - { - throw new InvalidPatternException("invalid pattern: \"" + localPattern + "\""); - } - try - { - minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing minutes field: " + e.getMessage() + "."); - } - try - { - hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing hours field: " + e.getMessage() + "."); - } - try - { - dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of month field: " + e.getMessage() + "."); - } - try - { - monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing months field: " + e.getMessage() + "."); - } - try - { - dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); - } - catch (Exception e) - { - throw new InvalidPatternException("invalid pattern \"" + localPattern + "\". Error parsing days of week field: " + e.getMessage() + "."); - } - matcherSize++; - } - } - - /** - * A ValueMatcher utility builder. - * @param str The pattern part for the ValueMatcher creation. - * @param parser The parser used to parse the values. - * @return The requested ValueMatcher. - * @throws Exception If the supplied pattern part is not valid. - */ - private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception - { - if ((str.length() == 1) && str.equals("*")) - { - return new AlwaysTrueValueMatcher(); - } - final List values = new ArrayList<>(); - final StringTokenizer st = new StringTokenizer(str, ","); - while (st.hasMoreTokens()) - { - final String element = st.nextToken(); - List local; - try - { - local = parseListElement(element, parser); - } - catch (Exception e) - { - throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); - } - for (Integer integer : local) - { - final Object value = integer; - if (!values.contains(value)) - { - values.add(value); - } - } - } - if (values.isEmpty()) - { - throw new Exception("invalid field \"" + str + "\""); - } - if (parser == DAY_OF_MONTH_VALUE_PARSER) - { - return new DayOfMonthValueMatcher(values); - } - return new IntArrayValueMatcher(values); - } - - /** - * Parses an element of a list of values of the pattern. - * @param str The element string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseListElement(String str, ValueParser parser) throws Exception - { - final StringTokenizer st = new StringTokenizer(str, "/"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - List values; - try - { - values = parseRange(st.nextToken(), parser); - } - catch (Exception e) - { - throw new Exception("invalid range, " + e.getMessage()); - } - if (size == 2) - { - final String dStr = st.nextToken(); - int div; - try - { - div = Integer.parseInt(dStr); - } - catch (NumberFormatException e) - { - throw new Exception("invalid divisor \"" + dStr + "\""); - } - if (div < 1) - { - throw new Exception("non positive divisor \"" + div + "\""); - } - final List values2 = new ArrayList<>(); - for (int i = 0; i < values.size(); i += div) - { - values2.add(values.get(i)); - } - return values2; - } - return values; - } - - /** - * Parses a range of values. - * @param str The range string. - * @param parser The parser used to parse the values. - * @return A list of integers representing the allowed values. - * @throws Exception If the supplied pattern part is not valid. - */ - private List parseRange(String str, ValueParser parser) throws Exception - { - if (str.equals("*")) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - final List values = new ArrayList<>(); - for (int i = min; i <= max; i++) - { - values.add(i); - } - return values; - } - final StringTokenizer st = new StringTokenizer(str, "-"); - final int size = st.countTokens(); - if ((size < 1) || (size > 2)) - { - throw new Exception("syntax error"); - } - final String v1Str = st.nextToken(); - int v1; - try - { - v1 = parser.parse(v1Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v1Str + "\", " + e.getMessage()); - } - if (size == 1) - { - final List values = new ArrayList<>(); - values.add(v1); - return values; - } - final String v2Str = st.nextToken(); - int v2; - try - { - v2 = parser.parse(v2Str); - } - catch (Exception e) - { - throw new Exception("invalid value \"" + v2Str + "\", " + e.getMessage()); - } - final List values = new ArrayList<>(); - if (v1 < v2) - { - for (int i = v1; i <= v2; i++) - { - values.add(i); - } - } - else if (v1 > v2) - { - final int min = parser.getMinValue(); - final int max = parser.getMaxValue(); - for (int i = v1; i <= max; i++) - { - values.add(i); - } - for (int i = min; i <= v2; i++) - { - values.add(i); - } - } - else - { - // v1 == v2 - values.add(v1); - } - return values; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the given time zone. - * @param timezone A time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(TimeZone timezone, long millis) - { - final GregorianCalendar gc = new GregorianCalendar(); - gc.setTimeInMillis(millis); - gc.setTimeZone(timezone); - final int minute = gc.get(Calendar.MINUTE); - final int hour = gc.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); - final int month = gc.get(Calendar.MONTH) + 1; - final int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; - final int year = gc.get(Calendar.YEAR); - for (int i = 0; i < matcherSize; i++) - { - final ValueMatcher minuteMatcher = minuteMatchers.get(i); - final ValueMatcher hourMatcher = hourMatchers.get(i); - final ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); - final ValueMatcher monthMatcher = monthMatchers.get(i); - final ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); - final boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher).match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); - if (eval) - { - return true; - } - } - return false; - } - - /** - * This methods returns true if the given timestamp (expressed as a UNIX-era millis value) matches the pattern, according to the system default time zone. - * @param millis The timestamp, as a UNIX-era millis value. - * @return true if the given timestamp matches the pattern. - */ - public boolean match(long millis) - { - return match(TimeZone.getDefault(), millis); - } - - /** - * Returns the pattern as a string. - * @return The pattern as a string. - */ - @Override - public String toString() - { - return asString; - } - - /** - * This utility method changes an alias to an int value. - * @param value The value. - * @param aliases The aliases list. - * @param offset The offset appplied to the aliases list indices. - * @return The parsed value. - * @throws Exception If the expressed values doesn't match any alias. - */ - static int parseAlias(String value, String[] aliases, int offset) throws Exception - { - for (int i = 0; i < aliases.length; i++) - { - if (aliases[i].equalsIgnoreCase(value)) - { - return offset + i; - } - } - throw new Exception("invalid alias \"" + value + "\""); - } - - /** - * Definition for a value parser. - */ - private interface ValueParser - { - /** - * Attempts to parse a value. - * @param value The value. - * @return The parsed value. - * @throws Exception If the value can't be parsed. - */ - int parse(String value) throws Exception; - - /** - * Returns the minimum value accepred by the parser. - * @return The minimum value accepred by the parser. - */ - int getMinValue(); - - /** - * Returns the maximum value accepred by the parser. - * @return The maximum value accepred by the parser. - */ - int getMaxValue(); - } - - /** - * A simple value parser. - */ - private static class SimpleValueParser implements ValueParser - { - /** - * The minimum allowed value. - */ - protected int minValue; - - /** - * The maximum allowed value. - */ - protected int maxValue; - - /** - * Builds the value parser. - * @param minValue The minimum allowed value. - * @param maxValue The maximum allowed value. - */ - public SimpleValueParser(int minValue, int maxValue) - { - this.minValue = minValue; - this.maxValue = maxValue; - } - - @Override - public int parse(String value) throws Exception - { - int i; - try - { - i = Integer.parseInt(value); - } - catch (NumberFormatException e) - { - throw new Exception("invalid integer value"); - } - if ((i < minValue) || (i > maxValue)) - { - throw new Exception("value out of range"); - } - return i; - } - - @Override - public int getMinValue() - { - return minValue; - } - - @Override - public int getMaxValue() - { - return maxValue; - } - } - - /** - * The minutes value parser. - */ - private static class MinuteValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public MinuteValueParser() - { - super(0, 59); - } - } - - /** - * The hours value parser. - */ - private static class HourValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public HourValueParser() - { - super(0, 23); - } - } - - /** - * The days of month value parser. - */ - private static class DayOfMonthValueParser extends SimpleValueParser - { - /** - * Builds the value parser. - */ - public DayOfMonthValueParser() - { - super(1, 31); - } - - /** - * Added to support last-day-of-month. - * @param value The value to be parsed - * @return the integer day of the month or 32 for last day of the month - * @throws Exception if the input value is invalid - */ - @Override - public int parse(String value) throws Exception - { - if (value.equalsIgnoreCase("L")) - { - return 32; - } - return super.parse(value); - } - } - - /** - * The value parser for the months field. - */ - private static class MonthValueParser extends SimpleValueParser - { - /** - * Months aliases. - */ - private static String[] ALIASES = - { - "jan", - "feb", - "mar", - "apr", - "may", - "jun", - "jul", - "aug", - "sep", - "oct", - "nov", - "dec" - }; - - /** - * Builds the months value parser. - */ - public MonthValueParser() - { - super(1, 12); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value); - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 1); - } - } - } - - /** - * The value parser for the months field. - */ - private static class DayOfWeekValueParser extends SimpleValueParser - { - /** - * Days of week aliases. - */ - private static String[] ALIASES = - { - "sun", - "mon", - "tue", - "wed", - "thu", - "fri", - "sat" - }; - - /** - * Builds the months value parser. - */ - public DayOfWeekValueParser() - { - super(0, 7); - } - - @Override - public int parse(String value) throws Exception - { - try - { - // try as a simple value - return super.parse(value) % 7; - } - catch (Exception e) - { - // try as an alias - return parseAlias(value, ALIASES, 0); - } - } - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java deleted file mode 100644 index 2be31f16f8..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/SchedulingPatternValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A scheduling patterns validator. - *

- *

- * The class lets you validate a scheduling pattern before/without using it with a {@link Scheduler} instance. Simply call: - *

- * - *
- * boolean valid = SchedulingPatternValidator.validate(thePattern);
- * 
- *

- * It is useful in validating user-entered patterns. - *

- * @author Carlo Pelliccia - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ -@Deprecated -public class SchedulingPatternValidator -{ - /** - * Validates a string as a scheduling pattern. - * @param schedulingPattern The pattern to validate. - * @return true if the given string represents a valid scheduling pattern; false otherwise. - * @deprecated Use {@link SchedulingPattern#validate(String)}. - */ - @Deprecated - public static boolean validate(String schedulingPattern) - { - return SchedulingPattern.validate(schedulingPattern); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java deleted file mode 100644 index 6bef3eb536..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/StaticMethodTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * This kind of task can be used to invoke a static method of a Java class. The specified method must accept an array of strings as its sole argument. - * @author Carlo Pelliccia - * @since 2.2 - */ -class StaticMethodTask extends Task -{ - /** - * The Java class name. - */ - private final String className; - - /** - * The name of the static method of the class that has to be launched. - */ - private final String methodName; - - /** - * Arguments for the static method. The array can be empty, but it can't be null. - */ - private final String[] args; - - /** - * Builds the task. - * @param className The Java class name. - * @param methodName The name of the static method of the class that has to be launched. - * @param args Arguments for the static method. The array can be empty, but it can't be null. - */ - public StaticMethodTask(String className, String methodName, String[] args) - { - this.className = className; - this.methodName = methodName; - this.args = args; - } - - /** - * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java reflection to load the given class and call the given static method with the supplied arguments. - */ - @Override - public void execute(TaskExecutionContext context) throws RuntimeException - { - // Loads the class. - Class classObject; - try - { - classObject = Class.forName(className); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load class " + className, e); - } - // Finds the method. - Method methodObject; - try - { - final Class[] argTypes = new Class[] - { - String[].class - }; - methodObject = classObject.getMethod(methodName, argTypes); - } - catch (NoSuchMethodException e) - { - throw new RuntimeException("Cannot find a " + methodName + "(String[]) method in class " + className, e); - } - final int modifiers = methodObject.getModifiers(); - if (!Modifier.isStatic(modifiers)) - { - throw new RuntimeException("The method " + methodName + "(String[]) of the class " + className + " is not static"); - } - // Invokes the method. - try - { - methodObject.invoke(null, new Object[] - { - args - }); - } - catch (Exception e) - { - throw new RuntimeException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className); - } - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java deleted file mode 100644 index aa8f381807..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/StreamBridge.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A package-reserved utility class. It spawns a secondary thread in which the supplied {@link InputStream} instance is read, and the incoming contents are written in the supplied {@link OutputStream}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class StreamBridge -{ - /** - * Used to trace alive instances. - */ - static List traced = new ArrayList<>(); - - /** - * A self-referece, for inner classes. - */ - final StreamBridge myself = this; - - /** - * The thread executing the job. - */ - private final Thread thread; - - /** - * The stream from which the data is read. - */ - final InputStream in; - - /** - * The stream in which the data is written. - */ - final OutputStream out; - - /** - * Builds the instance. - * @param in The stream from which the data is read. - * @param out The stream in which the data is written. - */ - public StreamBridge(InputStream in, OutputStream out) - { - this.in = in; - this.out = out; - thread = new Thread(new Runner()); - synchronized (traced) - { - traced.add(this); - } - } - - /** - * Starts the bridge job. - */ - public void start() - { - thread.start(); - } - - /** - * Aborts the ongoing job. - */ - public void abort() - { - thread.interrupt(); - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - } - - /** - * Waits for this job to die. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - thread.join(); - } - - /** - * Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. - * @param millis the time to wait in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis) throws InterruptedException - { - thread.join(millis); - } - - /** - * @param millis the time to wait in milliseconds. - * @param nanos 0-999999 additional nanoseconds to wait. - * @throws IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join(long millis, int nanos) throws IllegalArgumentException, InterruptedException - { - thread.join(millis, nanos); - } - - /** - * Tests if this bridge is alive. A job is alive if it has been started and has not yet completed. - * @return true if this thread is alive; false otherwise. - */ - public boolean isAlive() - { - return thread.isAlive(); - } - - /** - * Contains the routine doing the job in the secondary thread. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - @Override - public void run() - { - boolean skipout = false; - for (;;) - { - int b; - try - { - b = in.read(); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - break; - } - if (b == -1) - { - break; - } - if (!skipout) - { - try - { - out.write(b); - } - catch (IOException e) - { - if (!Thread.interrupted()) - { - e.printStackTrace(); - } - skipout = true; - } - } - } - try - { - out.close(); - } - catch (Throwable t) - { - } - try - { - in.close(); - } - catch (Throwable t) - { - } - synchronized (traced) - { - traced.remove(myself); - } - } - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Task.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Task.java deleted file mode 100644 index 90348a6907..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/Task.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * Abstract base representation of a cron4j task. - *

- *

- * Developers can extends this abstract class to build their own tasks. - *

- *

- * Extending Task means, above all, implementing the {@link Task#execute(TaskExecutionContext)} method. Within this method the task must perform its operation. If the execute() method returns regularly then the execution is considered to be successfully completed. If execute() dies - * throwing a {@link RuntimeException} then the task execution is considered to be failed. The supplied parameter, which is a {@link TaskExecutionContext} instance, helps the developer in integrating his task with the scheduler executor. Through the context the developer can check if the execution - * has been paused or stopped, and he can also push back some status informations by calling {@link TaskExecutionContext#setCompleteness(double)} and {@link TaskExecutionContext#setStatusMessage(String)}. - *

- *

- * If the custom task supports pausing, stopping and/or tracking, that should be notified by overriding {@link Task#canBePaused()}, {@link Task#canBeStopped()}, {@link Task#supportsCompletenessTracking()} and/or {@link Task#supportsStatusTracking()}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public abstract class Task -{ - /** - * The ID for this task. Also used as an instance synchronization lock. - */ - private final Object id = GUIDGenerator.generate(); - - /** - * Empty constructor, does nothing. - */ - public Task() - { - } - - /** - * It returns the ID for this task. - * @return The ID for this task. - */ - Object getId() - { - return id; - } - - /** - *

- * Checks whether this task supports pause requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that pause requests are really handled. This can be done calling regularly the - * {@link TaskExecutionContext#pauseIfRequested()} method during the task execution. - *

- * @return true if this task can be paused; false otherwise. - */ - public boolean canBePaused() - { - return false; - } - - /** - *

- * Checks whether this task supports stop requests. - *

- *

- * Default implementation returns false. - *

- *

- * Task developers can override this method to let it return a true value, and at the same time they have to implement the {@link Task#execute(TaskExecutionContext)} method, so that stop requests are really handled. This can be done checking regularly the - * {@link TaskExecutionContext#isStopped()} method during the task execution. - *

- * @return true if this task can be stopped; false otherwise. - */ - public boolean canBeStopped() - { - return false; - } - - /** - *

- * Tests whether this task supports status tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setStatusMessage(String)} method during the task execution. - *

- * @return true if this task, during its execution, provides status message regularly. - */ - public boolean supportsStatusTracking() - { - return false; - } - - /** - *

- * Tests whether this task supports completeness tracking. - *

- *

- * Default implementation returns false. - *

- *

- * The task developer can override this method and returns true, having care to regularly calling the {@link TaskExecutionContext#setCompleteness(double)} method during the task execution. - *

- * @return true if this task, during its execution, provides a completeness value regularly. - */ - public boolean supportsCompletenessTracking() - { - return false; - } - - /** - *

- * This method is called to require a task execution, and should contain the core routine of any scheduled task. - *

- *

- * If the execute() method ends regularly the scheduler will consider the execution successfully completed, and this will be communicated to any {@link SchedulerListener} interested in it. If the execute() method dies throwing a {@link RuntimeException} the scheduler will - * consider it as a failure notification. Any {@link SchedulerListener} will be notified about the occurred exception. - *

- * @param context The execution context. - * @throws RuntimeException Task execution has somehow failed. - */ - public abstract void execute(TaskExecutionContext context) throws RuntimeException; -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java deleted file mode 100644 index 6ae61174cf..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskCollector.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes a task collector. Task collectors can be registered in a {@link Scheduler} instance with the {@link Scheduler#addTaskCollector(TaskCollector)} method. Any registered task collector is queried by the scheduler once a minute. The developer has to implement the - * {@link TaskCollector#getTasks()} method, returning a {@link TaskTable} whose elements has been collected with a custom logic. In example the list can be extracted from a database. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskCollector -{ - /** - * Once the instance has been registered on a {@link Scheduler} instance, with the {@link Scheduler#addTaskCollector(TaskCollector)} method, this method will be queried once a minute. It should return a custom {@link TaskTable} object. The scheduler instance will automatically iterate over the - * returned table elements, executing any task whose scheduling pattern is matching the current system time. - * @return The task table that will be automatically injected in the scheduler. - */ - TaskTable getTasks(); -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java deleted file mode 100644 index 91008df61d..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutionContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * A TaskExecutionContext object provides support methods for the execution of a task. An instance of this class is always passed to the task when its {@link Task#execute(TaskExecutionContext)} method is called. The task, while executing, can use the received context to exchange informations with - * its own executor. If the task declares to supports pausing, stopping, completeness tracking and/or status tracking, it has to use its context methods to perform any declared operation (checks pause and stop requests, sends back tracking informations). - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutionContext -{ - /** - * Returns the scheduler. - * @return The scheduler. - */ - Scheduler getScheduler(); - - /** - * Returns the task executor. - * @return The task executor. - */ - TaskExecutor getTaskExecutor(); - - /** - * Sets the current status tracking message, that has to be something about what the task is doing at the moment. - * @param message A message representing the current execution status. Null messages will be blanked. - */ - void setStatusMessage(String message); - - /** - * Sets the completeness tracking value, that has to be between 0 and 1. - * @param completeness A completeness value, between 0 and 1. Values out of range will be ignored. - */ - void setCompleteness(double completeness); - - /** - * If the task execution has been paused, stops until the operation is resumed. It can also returns because of a stop operation without any previous resuming. Due to this the task developer should always check the {@link TaskExecutionContext#isStopped()} value after any - * pauseIfRequested() call. Note that a task execution can be paused only if the task {@link Task#canBePaused()} method returns true. - */ - void pauseIfRequested(); - - /** - * Checks whether the task execution has been demanded to be stopped. If the returned value is true, the task developer must shut down gracefully its task execution, as soon as possible. Note that a task execution can be stopped only if the task {@link Task#canBePaused()} method returns - * true. - * @return true if the current task execution has been demanded to be stopped; false otherwise. - */ - boolean isStopped(); -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java deleted file mode 100644 index 83929df78a..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutor.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * Represents a task executor, which is something similar to threads. - *

- *

- * Each time a task is launched, a new executor is spawned, executing and watching the task - *

- *

- * Alive task executors can be retrieved with the {@link Scheduler#getExecutingTasks()} method, and they expose method to control the ongoing execution. - *

- * @see Scheduler#getExecutingTasks() - * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskExecutor -{ - /** - * The scheduler whose this executor belongs to. - */ - final Scheduler scheduler; - - /** - * The executed task. - */ - final Task task; - - /** - * A task execution context. - */ - final MyContext context; - - /** - * A unique ID for this executor (used also as a lock object). - */ - private final String guid = GUIDGenerator.generate(); - - /** - * An alternative to this (inner classes need it). - */ - final TaskExecutor myself = this; - - /** - * A list of {@link TaskExecutorListener} instances. - */ - private final List listeners = new ArrayList<>(); - - /** - * A time stamp reporting the start time of this thread. - */ - long startTime = -1; - - /** - * The thread actually executing the task. - */ - private Thread thread; - - /** - * Is this executor paused now? - */ - boolean paused = false; - - /** - * Has been this executor stopped? - */ - boolean stopped = false; - - /** - * A lock object, for synchronization purposes. - */ - final Object lock = new Object(); - - /** - * Builds the executor. - * @param scheduler The scheduler whose this executor belongs to. - * @param task The task that has to be executed. - */ - TaskExecutor(Scheduler scheduler, Task task) - { - this.scheduler = scheduler; - this.task = task; - context = new MyContext(); - } - - /** - * Adds a listener to the executor. - * @param listener The listener. - */ - public void addTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.add(listener); - } - } - - /** - * Removes a listener from the executor. - * @param listener The listener. - */ - public void removeTaskExecutorListener(TaskExecutorListener listener) - { - synchronized (listeners) - { - listeners.remove(listener); - } - } - - /** - * Returns an array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @return An array containing any {@link TaskExecutorListener} previously registered with the {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - */ - public TaskExecutorListener[] getTaskExecutorListeners() - { - synchronized (listeners) - { - final int size = listeners.size(); - final TaskExecutorListener[] ret = new TaskExecutorListener[size]; - for (int i = 0; i < size; i++) - { - ret[i] = listeners.get(i); - } - return ret; - } - } - - /** - * Returns a GUID for this executor. - * @return A GUID for this executor. - */ - public String getGuid() - { - return guid; - } - - /** - * Returns the {@link Scheduler} instance whose this executor belongs to. - * @return The scheduler. - */ - public Scheduler getScheduler() - { - return scheduler; - } - - /** - * Returns the representation of the executed task. - * @return The executing/executed task. - */ - public Task getTask() - { - return task; - } - - /** - * Returns a time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - * @return A time stamp reporting the start time of this executor, or a value less than 0 if this executor has not been yet started. - */ - public long getStartTime() - { - return startTime; - } - - /** - * Checks whether this executor supports pausing. - * @return true if this executor supports pausing. - */ - public boolean canBePaused() - { - return task.canBePaused(); - } - - /** - * Checks whether this executor supports stopping. - * @return true if this executor supports stopping. - */ - public boolean canBeStopped() - { - return task.canBeStopped(); - } - - /** - * Checks whether this executor provides completeness tracking informations. - * @return true if this executor provides completeness tracking informations. - */ - public boolean supportsCompletenessTracking() - { - return task.supportsCompletenessTracking(); - } - - /** - * Checks whether this executor provides status tracking messages. - * @return true if this executor provides status tracking messages. - */ - public boolean supportsStatusTracking() - { - return task.supportsStatusTracking(); - } - - /** - * Starts executing the task (spawns a secondary thread). - * @param daemon true to spawn a daemon thread; false otherwise. - */ - void start(boolean daemon) - { - synchronized (lock) - { - startTime = System.currentTimeMillis(); - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::executor[" + guid + "]"; - thread = new Thread(new Runner()); - thread.setDaemon(daemon); - thread.setName(name); - thread.start(); - } - } - - /** - * Pauses the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBePaused()} returns false. - */ - public void pause() throws UnsupportedOperationException - { - if (!task.canBePaused()) - { - throw new UnsupportedOperationException("Pause not supported"); - } - synchronized (lock) - { - if ((thread != null) && !paused) - { - notifyExecutionPausing(); - paused = true; - } - } - } - - /** - * Resumes the execution after it has been paused. - */ - private void resume() - { - synchronized (lock) - { - if ((thread != null) && paused) - { - notifyExecutionResuming(); - paused = false; - lock.notifyAll(); - } - } - } - - /** - * Stops the ongoing execution. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#canBeStopped()} returns false. - */ - public void stop() throws UnsupportedOperationException - { - if (!task.canBeStopped()) - { - throw new UnsupportedOperationException("Stop not supported"); - } - boolean joinit = false; - synchronized (lock) - { - if ((thread != null) && !stopped) - { - stopped = true; - if (paused) - { - resume(); - } - notifyExecutionStopping(); - thread.interrupt(); - joinit = true; - } - } - if (joinit) - { - do - { - try - { - thread.join(); - break; - } - catch (InterruptedException e) - { - } - } - while (true); - thread = null; - } - } - - /** - * Waits for this executor to die. - * @throws InterruptedException If any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - */ - public void join() throws InterruptedException - { - if (thread != null) - { - thread.join(); - } - } - - /** - * Tests if this executor is alive. An executor is alive if it has been started and has not yet died. - * @return true if this executor is alive; false otherwise. - */ - public boolean isAlive() - { - if (thread != null) - { - return thread.isAlive(); - } - return false; - } - - /** - * Returns the current status message. - * @return The current status message. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsStatusTracking()} returns false. - */ - public String getStatusMessage() throws UnsupportedOperationException - { - if (!task.supportsStatusTracking()) - { - throw new UnsupportedOperationException("Status tracking not supported"); - } - return context.getStatusMessage(); - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - * @throws UnsupportedOperationException The operation is not supported if {@link TaskExecutor#supportsCompletenessTracking()} returns false. - */ - public double getCompleteness() throws UnsupportedOperationException - { - if (!task.supportsCompletenessTracking()) - { - throw new UnsupportedOperationException("Completeness tracking not supported"); - } - return context.getCompleteness(); - } - - /** - * Tests whether this executor has been paused. - * @return true if this executor is paused; false otherwise. - */ - public boolean isPaused() - { - return paused; - } - - /** - * Tests whether this executor has been stopped. - * @return true if this executor is stopped; false otherwise. - */ - public boolean isStopped() - { - return stopped; - } - - /** - * Notify registered listeners the execution has been paused. - */ - private void notifyExecutionPausing() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionPausing(this); - } - } - } - - /** - * Notify registered listeners the execution has been resumed. - */ - private void notifyExecutionResuming() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionResuming(this); - } - } - } - - /** - * Notify registered listeners the executor is stopping. - */ - private void notifyExecutionStopping() - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionStopping(this); - } - } - } - - /** - * Notify registered listeners the execution has been terminated. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void notifyExecutionTerminated(Throwable exception) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.executionTerminated(this, exception); - } - } - } - - /** - * Notify registered listeners the execution status message has changed. - * @param statusMessage The new status message. - */ - void notifyStatusMessageChanged(String statusMessage) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.statusMessageChanged(this, statusMessage); - } - } - } - - /** - * Notify registered listeners the execution completeness value has changed. - * @param completenessValue The new completeness value. - */ - void notifyCompletenessValueChanged(double completenessValue) - { - synchronized (listeners) - { - for (TaskExecutorListener taskExecutorListener : listeners) - { - final TaskExecutorListener l = taskExecutorListener; - l.completenessValueChanged(this, completenessValue); - } - } - } - - /** - * Inner Runnable class. - */ - private class Runner implements Runnable - { - public Runner() - { - } - - /** - * It implements {@link Thread#run()}, executing the wrapped task. - */ - @Override - public void run() - { - Throwable error = null; - startTime = System.currentTimeMillis(); - try - { - // Notify. - scheduler.notifyTaskLaunching(myself); - // Task execution. - task.execute(context); - // Succeeded. - scheduler.notifyTaskSucceeded(myself); - } - catch (Throwable exception) - { - // Failed. - error = exception; - scheduler.notifyTaskFailed(myself, exception); - } - finally - { - // Notify. - notifyExecutionTerminated(error); - scheduler.notifyExecutorCompleted(myself); - } - } - } - - /** - * Inner TaskExecutionHelper implementation. - */ - private class MyContext implements TaskExecutionContext - { - /** - * Status message. - */ - private String message = ""; - - /** - * Completeness value. - */ - private double completeness = 0D; - - public MyContext() - { - } - - @Override - public Scheduler getScheduler() - { - return scheduler; - } - - @Override - public TaskExecutor getTaskExecutor() - { - return myself; - } - - @Override - public boolean isStopped() - { - return stopped; - } - - @Override - public void pauseIfRequested() - { - synchronized (lock) - { - if (paused) - { - try - { - lock.wait(); - } - catch (InterruptedException e) - { - } - } - } - } - - @Override - public void setCompleteness(double completeness) - { - if ((completeness >= 0D) && (completeness <= 1D)) - { - this.completeness = completeness; - notifyCompletenessValueChanged(completeness); - } - } - - @Override - public void setStatusMessage(String message) - { - this.message = message != null ? message : ""; - notifyStatusMessageChanged(message); - } - - /** - * Returns the current status message. - * @return The current status message. - */ - public String getStatusMessage() - { - return message; - } - - /** - * Returns the current completeness value, which is a value between 0 and 1. - * @return The current completeness value, which is a value between 0 and 1. - */ - public double getCompleteness() - { - return completeness; - } - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java deleted file mode 100644 index 5b987c4326..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskExecutorListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - * A TaskExecutorListener is notified with events from a {@link TaskExecutor}. You can add listeners to a TaskExecutor by calling its {@link TaskExecutor#addTaskExecutorListener(TaskExecutorListener)} method. - * @see TaskExecutor - * @author Carlo Pelliccia - * @since 2.0 - */ -public interface TaskExecutorListener -{ - /** - * Called when the execution has been requested to be paused. - * @param executor The source executor. - */ - void executionPausing(TaskExecutor executor); - - /** - * Called when the execution has been requested to be resumed. - * @param executor The source executor. - */ - void executionResuming(TaskExecutor executor); - - /** - * Called when the executor has been requested to be stopped. - * @param executor The source executor. - */ - void executionStopping(TaskExecutor executor); - - /** - * Called at execution end. If the execution has failed due to an error, the encountered exception is reported. - * @param executor The source executor. - * @param exception If the execution has been terminated due to an error, this is the encountered exception; otherwise the parameter is null. - */ - void executionTerminated(TaskExecutor executor, Throwable exception); - - /** - * Called every time the execution status message changes. - * @param executor The source executor. - * @param statusMessage The new status message. - */ - void statusMessageChanged(TaskExecutor executor, String statusMessage); - - /** - * Called every time the execution completeness value changes. - * @param executor The source executor. - * @param completenessValue The new completeness value. - */ - void completenessValueChanged(TaskExecutor executor, double completenessValue); -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java deleted file mode 100644 index ce97a2244b..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TaskTable.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -import java.util.ArrayList; -import java.util.List; - -/** - *

- * A table coupling tasks with scheduling patterns. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -public class TaskTable -{ - /** - * Table size. - */ - private int size = 0; - - /** - * Pattern list. - */ - private final List patterns = new ArrayList<>(); - - /** - * Task list. - */ - private final List tasks = new ArrayList<>(); - - /** - * Adds a task and an associated scheduling pattern to the table. - * @param pattern The associated scheduling pattern. - * @param task The task. - */ - public void add(SchedulingPattern pattern, Task task) - { - patterns.add(pattern); - tasks.add(task); - size++; - } - - /** - * Returns the size of the table, representing the number of the elements stored in it. - * @return The table size. - */ - public int size() - { - return size; - } - - /** - * Returns the task at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The task at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public Task getTask(int index) throws IndexOutOfBoundsException - { - return tasks.get(index); - } - - /** - * Returns the scheduling pattern at the specified position. Valid positions are between 0 to {@link TaskTable#size()} - 1. - * @param index The index. - * @return The scheduling pattern at the specified position. - * @throws IndexOutOfBoundsException If the supplied index is out of range. - */ - public SchedulingPattern getSchedulingPattern(int index) throws IndexOutOfBoundsException - { - return patterns.get(index); - } - - /** - * Remove a task from the table. - * @param index The index of the task to remove. - * @throws IndexOutOfBoundsException If the supplied index is not valid. - * @since 2.1 - */ - public void remove(int index) throws IndexOutOfBoundsException - { - tasks.remove(index); - patterns.remove(index); - size--; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java deleted file mode 100644 index bab370ac85..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/TimerThread.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * TimeThreads are used by {@link Scheduler} instances. A TimerThread spends most of the time sleeping. It wakes up every minute and it requests to the scheduler the spawning of a {@link LauncherThread}. - *

- * @author Carlo Pelliccia - * @since 2.0 - */ -class TimerThread extends Thread -{ - /** - * A GUID for this object. - */ - private final String guid = GUIDGenerator.generate(); - - /** - * The owner scheduler. - */ - private Scheduler scheduler; - - /** - * Builds the timer thread. - * @param scheduler The owner scheduler. - */ - public TimerThread(Scheduler scheduler) - { - this.scheduler = scheduler; - // Thread name. - final String name = "cron4j::scheduler[" + scheduler.getGuid() + "]::timer[" + guid + "]"; - setName(name); - } - - /** - * Returns the GUID for this object. - * @return The GUID for this object. - */ - public Object getGuid() - { - return guid; - } - - /** - * It has been reported that the {@link Thread#sleep(long)} method sometimes exits before the requested time has passed. This one offers an alternative that sometimes could sleep a few millis more than requested, but never less. - * @param millis The length of time to sleep in milliseconds. - * @throws InterruptedException If another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. - * @see Thread#sleep(long) - */ - private void safeSleep(long millis) throws InterruptedException - { - long done = 0; - do - { - final long before = System.currentTimeMillis(); - sleep(millis - done); - final long after = System.currentTimeMillis(); - done += (after - before); - } - while (done < millis); - } - - /** - * Overrides {@link Thread#run()}. - */ - @Override - public void run() - { - // What time is it? - long millis = System.currentTimeMillis(); - // Calculating next minute. - long nextMinute = ((millis / 60000) + 1) * 60000; - // Work until the scheduler is started. - for (;;) - { - // Coffee break 'till next minute comes! - final long sleepTime = (nextMinute - System.currentTimeMillis()); - if (sleepTime > 0) - { - try - { - safeSleep(sleepTime); - } - catch (InterruptedException e) - { - // Must exit! - break; - } - } - // What time is it? - millis = System.currentTimeMillis(); - // Launching the launching thread! - scheduler.spawnLauncher(millis); - // Calculating next minute. - nextMinute = ((millis / 60000) + 1) * 60000; - } - // Discard scheduler reference. - scheduler = null; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java deleted file mode 100644 index 84c4e18689..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/cron4j/ValueMatcher.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cron4j - A pure Java cron-like scheduler - * - * Copyright (C) 2007-2010 Carlo Pelliccia (www.sauronsoftware.it) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version - * 2.1, as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License 2.1 for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License version 2.1 along with this program. - * If not, see . - */ -package org.l2jmobius.gameserver.util.cron4j; - -/** - *

- * This interface describes the ValueMatcher behavior. A ValueMatcher is an object that validate an integer value against a set of rules. - *

- * @author Carlo Pelliccia - */ -interface ValueMatcher -{ - /** - * Validate the given integer value against a set of rules. - * @param value The value. - * @return true if the given value matches the rules of the ValueMatcher, false otherwise. - */ - boolean match(int value); -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java deleted file mode 100644 index bf91e2d7ed..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ArgumentSeparatorToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an argument separator in functions i.e: ',' - */ -class ArgumentSeparatorToken extends Token -{ - /** - * Create a new instance - */ - ArgumentSeparatorToken() - { - super(Token.TOKEN_SEPARATOR); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java deleted file mode 100644 index 2437453c39..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ArrayStack.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2015 Federico Vera - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.EmptyStackException; - -/** - * Simple double stack using a double array as data storage - * @author Federico Vera (dktcoding [at] gmail) - */ -class ArrayStack -{ - private double[] data; - - private int idx; - - ArrayStack() - { - this(5); - } - - ArrayStack(int initialCapacity) - { - if (initialCapacity <= 0) - { - throw new IllegalArgumentException("Stack's capacity must be positive"); - } - - data = new double[initialCapacity]; - idx = -1; - } - - void push(double value) - { - if ((idx + 1) == data.length) - { - final double[] temp = new double[(int) (data.length * 1.2) + 1]; - System.arraycopy(data, 0, temp, 0, data.length); - data = temp; - } - - data[++idx] = value; - } - - double peek() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx]; - } - - double pop() - { - if (idx == -1) - { - throw new EmptyStackException(); - } - return data[idx--]; - } - - boolean isEmpty() - { - return idx == -1; - } - - int size() - { - return idx + 1; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java deleted file mode 100644 index 0e42d6e0e4..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/CloseParenthesesToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents closed parentheses - */ -class CloseParenthesesToken extends Token -{ - /** - * Creare a new instance - */ - CloseParenthesesToken() - { - super(Token.TOKEN_PARENTHESES_CLOSE); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Expression.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Expression.java deleted file mode 100644 index 6d2ca225e1..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Expression.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class Expression -{ - private final Token[] tokens; - - private final Map variables; - - private final Set userFunctionNames; - - private static Map createDefaultVariables() - { - final Map vars = new HashMap<>(4); - vars.put("pi", Math.PI); - vars.put("π", Math.PI); - vars.put("φ", 1.61803398874d); - vars.put("e", Math.E); - return vars; - } - - /** - * Creates a new expression that is a copy of the existing one. - * @param existing the expression to copy - */ - public Expression(Expression existing) - { - tokens = Arrays.copyOf(existing.tokens, existing.tokens.length); - variables = new HashMap<>(); - variables.putAll(existing.variables); - userFunctionNames = new HashSet<>(existing.userFunctionNames); - } - - Expression(Token[] tokens) - { - this.tokens = tokens; - variables = createDefaultVariables(); - userFunctionNames = Collections. emptySet(); - } - - Expression(Token[] tokens, Set userFunctionNames) - { - this.tokens = tokens; - variables = createDefaultVariables(); - this.userFunctionNames = userFunctionNames; - } - - public Expression setVariable(String name, double value) - { - checkVariableName(name); - variables.put(name, value); - return this; - } - - private void checkVariableName(String name) - { - if (userFunctionNames.contains(name) || (Functions.getBuiltinFunction(name) != null)) - { - throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name"); - } - } - - public Expression setVariables(Map variables) - { - for (Map.Entry v : variables.entrySet()) - { - setVariable(v.getKey(), v.getValue()); - } - return this; - } - - public Set getVariableNames() - { - final Set variables = new HashSet<>(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - variables.add(((VariableToken) t).getName()); - } - } - return variables; - } - - public ValidationResult validate(boolean checkVariablesSet) - { - final List errors = new ArrayList<>(0); - if (checkVariablesSet) - { - /* check that all vars have a value set */ - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_VARIABLE) - { - final String var = ((VariableToken) t).getName(); - if (!variables.containsKey(var)) - { - errors.add("The setVariable '" + var + "' has not been set"); - } - } - } - } - - /* - * Check if the number of operands, functions and operators match. The idea is to increment a counter for operands and decrease it for operators. When a function occurs the number of available arguments has to be greater than or equals to the function's expected number of arguments. The - * count has to be larger than 1 at all times and exactly 1 after all tokens have been processed - */ - int count = 0; - for (Token tok : tokens) - { - switch (tok.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - count++; - break; - case Token.TOKEN_FUNCTION: - final Function func = ((FunctionToken) tok).getFunction(); - final int argsNum = func.getNumArguments(); - if (argsNum > count) - { - errors.add("Not enough arguments for '" + func.getName() + "'"); - } - if (argsNum > 1) - { - count -= argsNum - 1; - } - else if (argsNum == 0) - { - // see https://github.com/fasseg/exp4j/issues/59 - count++; - } - break; - case Token.TOKEN_OPERATOR: - final Operator op = ((OperatorToken) tok).getOperator(); - if (op.getNumOperands() == 2) - { - count--; - } - break; - } - if (count < 1) - { - errors.add("Too many operators"); - return new ValidationResult(false, errors); - } - } - if (count > 1) - { - errors.add("Too many operands"); - } - return errors.isEmpty() ? ValidationResult.SUCCESS : new ValidationResult(false, errors); - } - - public ValidationResult validate() - { - return validate(true); - } - - public Future evaluateAsync(ExecutorService executor) - { - return executor.submit(this::evaluate); - } - - public double evaluate() - { - final ArrayStack output = new ArrayStack(); - for (Token t : tokens) - { - if (t.getType() == Token.TOKEN_NUMBER) - { - output.push(((NumberToken) t).getValue()); - } - else if (t.getType() == Token.TOKEN_VARIABLE) - { - final String name = ((VariableToken) t).getName(); - final Double value = variables.get(name); - if (value == null) - { - throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'."); - } - output.push(value); - } - else if (t.getType() == Token.TOKEN_OPERATOR) - { - final OperatorToken op = (OperatorToken) t; - if (output.size() < op.getOperator().getNumOperands()) - { - throw new IllegalArgumentException("Invalid number of operands available for '" + op.getOperator().getSymbol() + "' operator"); - } - if (op.getOperator().getNumOperands() == 2) - { - /* pop the operands and push the result of the operation */ - final double rightArg = output.pop(); - final double leftArg = output.pop(); - output.push(op.getOperator().apply(leftArg, rightArg)); - } - else if (op.getOperator().getNumOperands() == 1) - { - /* pop the operand and push the result of the operation */ - final double arg = output.pop(); - output.push(op.getOperator().apply(arg)); - } - } - else if (t.getType() == Token.TOKEN_FUNCTION) - { - final FunctionToken func = (FunctionToken) t; - final int numArguments = func.getFunction().getNumArguments(); - if (output.size() < numArguments) - { - throw new IllegalArgumentException("Invalid number of arguments available for '" + func.getFunction().getName() + "' function"); - } - /* collect the arguments from the stack */ - final double[] args = new double[numArguments]; - for (int j = numArguments - 1; j >= 0; j--) - { - args[j] = output.pop(); - } - output.push(func.getFunction().apply(args)); - } - } - if (output.size() > 1) - { - throw new IllegalArgumentException("Invalid number of items on the output queue. Might be caused by an invalid number of arguments for a function."); - } - return output.pop(); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java deleted file mode 100644 index 87c6470c7a..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory class for {@link Expression} instances. This class is the main API entrypoint. Users should create new {@link Expression} instances using this factory class. - */ -public class ExpressionBuilder -{ - private final String expression; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private boolean implicitMultiplication = true; - - /** - * Create a new ExpressionBuilder instance and initialize it with a given expression string. - * @param expression the expression to be parsed - */ - public ExpressionBuilder(String expression) - { - if ((expression == null) || (expression.trim().isEmpty())) - { - throw new IllegalArgumentException("Expression can not be empty"); - } - this.expression = expression; - userOperators = new HashMap<>(4); - userFunctions = new HashMap<>(4); - variableNames = new HashSet<>(4); - } - - /** - * Add a {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation available for use in the expression - * @param function the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementation that should be available for use in the expression. - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder function(Function function) - { - userFunctions.put(function.getName(), function); - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions the custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(Function... functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations available for use in the expression - * @param functions A {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Function} implementations - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder functions(List functions) - { - for (Function f : functions) - { - userFunctions.put(f.getName(), f); - } - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(Set variableNames) - { - this.variableNames.addAll(variableNames); - return this; - } - - /** - * Declare variable names used in the expression - * @param variableNames the variables used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variables(String... variableNames) - { - Collections.addAll(this.variableNames, variableNames); - return this; - } - - /** - * Declare a variable used in the expression - * @param variableName the variable used in the expression - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder variable(String variableName) - { - variableNames.add(variableName); - return this; - } - - public ExpressionBuilder implicitMultiplication(boolean enabled) - { - implicitMultiplication = enabled; - return this; - } - - /** - * Add an {@link org.l2jmobius.gameserver.util.exp4j.Operator} which should be available for use in the expression - * @param operator the custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator operator) - { - checkOperatorSymbol(operator); - userOperators.put(operator.getSymbol(), operator); - return this; - } - - private void checkOperatorSymbol(Operator op) - { - final String name = op.getSymbol(); - for (char ch : name.toCharArray()) - { - if (!Operator.isAllowedOperatorChar(ch)) - { - throw new IllegalArgumentException("The operator symbol '" + name + "' is invalid"); - } - } - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the set of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(Operator... operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Add multiple {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations which should be available for use in the expression - * @param operators the {@link java.util.List} of custom {@link org.l2jmobius.gameserver.util.exp4j.Operator} implementations to add - * @return the ExpressionBuilder instance - */ - public ExpressionBuilder operator(List operators) - { - for (Operator o : operators) - { - operator(o); - } - return this; - } - - /** - * Build the {@link Expression} instance using the custom operators and functions set. - * @return an {@link Expression} instance which can be used to evaluate the result of the expression - */ - public Expression build() - { - if (expression.isEmpty()) - { - throw new IllegalArgumentException("The expression can not be empty"); - } - /* set the contants' varibale names */ - variableNames.add("pi"); - variableNames.add("π"); - variableNames.add("e"); - variableNames.add("φ"); - /* Check if there are duplicate vars/functions */ - for (String var : variableNames) - { - if ((Functions.getBuiltinFunction(var) != null) || userFunctions.containsKey(var)) - { - throw new IllegalArgumentException("A variable can not have the same name as a function [" + var + "]"); - } - } - return new Expression(ShuntingYard.convertToRPN(expression, userFunctions, userOperators, variableNames, implicitMultiplication), userFunctions.keySet()); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Function.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Function.java deleted file mode 100644 index 03314d4384..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Function.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.l2jmobius.gameserver.util.exp4j; - -/** - * A class representing a Function which can be used in an expression - */ -public abstract class Function -{ - protected final String name; - - protected final int numArguments; - - /** - * Create a new Function with a given name and number of arguments - * @param name the name of the Function - * @param numArguments the number of arguments the function takes - */ - public Function(String name, int numArguments) - { - if (numArguments < 0) - { - throw new IllegalArgumentException("The number of function arguments can not be less than 0 for '" + name + "'"); - } - if (!isValidFunctionName(name)) - { - throw new IllegalArgumentException("The function name '" + name + "' is invalid"); - } - this.name = name; - this.numArguments = numArguments; - } - - /** - * Create a new Function with a given name that takes a single argument - * @param name the name of the Function - */ - public Function(String name) - { - this(name, 1); - } - - /** - * Get the name of the Function - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Get the number of arguments for this function - * @return the number of arguments - */ - public int getNumArguments() - { - return numArguments; - } - - /** - * Method that does the actual calculation of the function value given the arguments - * @param args the set of arguments used for calculating the function - * @return the result of the function evaluation - */ - public abstract double apply(double... args); - - /** - * Get the set of characters which are allowed for use in Function names. - * @return the set of characters allowed - * @deprecated since 0.4.5 All unicode letters are allowed to be used in function names since 0.4.3. This API Function can be safely ignored. Checks for function name validity can be done using Character.isLetter() et al. - */ - @Deprecated - public static char[] getAllowedFunctionCharacters() - { - final char[] chars = new char[53]; - int count = 0; - for (int i = 65; i < 91; i++) - { - chars[count++] = (char) i; - } - for (int i = 97; i < 123; i++) - { - chars[count++] = (char) i; - } - chars[count] = '_'; - return chars; - } - - public static boolean isValidFunctionName(String name) - { - if (name == null) - { - return false; - } - - final int size = name.length(); - if (size == 0) - { - return false; - } - - for (int i = 0; i < size; i++) - { - final char c = name.charAt(i); - if (Character.isLetter(c) || (c == '_')) - { - continue; - } - else if (Character.isDigit(c) && (i > 0)) - { - continue; - } - return false; - } - return true; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java deleted file mode 100644 index 51eef1ef72..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/FunctionToken.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -public class FunctionToken extends Token -{ - private final Function function; - - public FunctionToken(Function function) - { - super(Token.TOKEN_FUNCTION); - this.function = function; - } - - public Function getFunction() - { - return function; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Functions.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Functions.java deleted file mode 100644 index a14b50622e..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Functions.java +++ /dev/null @@ -1,356 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing the builtin functions available for use in expressions - */ -public class Functions -{ - private static final int INDEX_SIN = 0; - private static final int INDEX_COS = 1; - private static final int INDEX_TAN = 2; - private static final int INDEX_COT = 3; - private static final int INDEX_LOG = 4; - private static final int INDEX_LOG1P = 5; - private static final int INDEX_ABS = 6; - private static final int INDEX_ACOS = 7; - private static final int INDEX_ASIN = 8; - private static final int INDEX_ATAN = 9; - private static final int INDEX_CBRT = 10; - private static final int INDEX_CEIL = 11; - private static final int INDEX_FLOOR = 12; - private static final int INDEX_SINH = 13; - private static final int INDEX_SQRT = 14; - private static final int INDEX_TANH = 15; - private static final int INDEX_COSH = 16; - private static final int INDEX_POW = 17; - private static final int INDEX_EXP = 18; - private static final int INDEX_EXPM1 = 19; - private static final int INDEX_LOG10 = 20; - private static final int INDEX_LOG2 = 21; - private static final int INDEX_SGN = 22; - - private static final Function[] builtinFunctions = new Function[23]; - static - { - builtinFunctions[INDEX_SIN] = new Function("sin") - { - @Override - public double apply(double... args) - { - return Math.sin(args[0]); - } - }; - builtinFunctions[INDEX_COS] = new Function("cos") - { - @Override - public double apply(double... args) - { - return Math.cos(args[0]); - } - }; - builtinFunctions[INDEX_TAN] = new Function("tan") - { - @Override - public double apply(double... args) - { - return Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_COT] = new Function("cot") - { - @Override - public double apply(double... args) - { - final double tan = Math.tan(args[0]); - if (tan == 0d) - { - throw new ArithmeticException("Division by zero in cotangent!"); - } - return 1d / Math.tan(args[0]); - } - }; - builtinFunctions[INDEX_LOG] = new Function("log") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]); - } - }; - builtinFunctions[INDEX_LOG2] = new Function("log2") - { - @Override - public double apply(double... args) - { - return Math.log(args[0]) / Math.log(2d); - } - }; - builtinFunctions[INDEX_LOG10] = new Function("log10") - { - @Override - public double apply(double... args) - { - return Math.log10(args[0]); - } - }; - builtinFunctions[INDEX_LOG1P] = new Function("log1p") - { - @Override - public double apply(double... args) - { - return Math.log1p(args[0]); - } - }; - builtinFunctions[INDEX_ABS] = new Function("abs") - { - @Override - public double apply(double... args) - { - return Math.abs(args[0]); - } - }; - builtinFunctions[INDEX_ACOS] = new Function("acos") - { - @Override - public double apply(double... args) - { - return Math.acos(args[0]); - } - }; - builtinFunctions[INDEX_ASIN] = new Function("asin") - { - @Override - public double apply(double... args) - { - return Math.asin(args[0]); - } - }; - builtinFunctions[INDEX_ATAN] = new Function("atan") - { - @Override - public double apply(double... args) - { - return Math.atan(args[0]); - } - }; - builtinFunctions[INDEX_CBRT] = new Function("cbrt") - { - @Override - public double apply(double... args) - { - return Math.cbrt(args[0]); - } - }; - builtinFunctions[INDEX_FLOOR] = new Function("floor") - { - @Override - public double apply(double... args) - { - return Math.floor(args[0]); - } - }; - builtinFunctions[INDEX_SINH] = new Function("sinh") - { - @Override - public double apply(double... args) - { - return Math.sinh(args[0]); - } - }; - builtinFunctions[INDEX_SQRT] = new Function("sqrt") - { - @Override - public double apply(double... args) - { - return Math.sqrt(args[0]); - } - }; - builtinFunctions[INDEX_TANH] = new Function("tanh") - { - @Override - public double apply(double... args) - { - return Math.tanh(args[0]); - } - }; - builtinFunctions[INDEX_COSH] = new Function("cosh") - { - @Override - public double apply(double... args) - { - return Math.cosh(args[0]); - } - }; - builtinFunctions[INDEX_CEIL] = new Function("ceil") - { - @Override - public double apply(double... args) - { - return Math.ceil(args[0]); - } - }; - builtinFunctions[INDEX_POW] = new Function("pow", 2) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinFunctions[INDEX_EXP] = new Function("exp", 1) - { - @Override - public double apply(double... args) - { - return Math.exp(args[0]); - } - }; - builtinFunctions[INDEX_EXPM1] = new Function("expm1", 1) - { - @Override - public double apply(double... args) - { - return Math.expm1(args[0]); - } - }; - builtinFunctions[INDEX_SGN] = new Function("signum", 1) - { - @Override - public double apply(double... args) - { - if (args[0] > 0) - { - return 1; - } - else if (args[0] < 0) - { - return -1; - } - else - { - return 0; - } - } - }; - } - - /** - * Get the builtin function for a given name - * @param name te name of the function - * @return a Function instance - */ - public static Function getBuiltinFunction(String name) - { - if (name.equals("sin")) - { - return builtinFunctions[INDEX_SIN]; - } - else if (name.equals("cos")) - { - return builtinFunctions[INDEX_COS]; - } - else if (name.equals("tan")) - { - return builtinFunctions[INDEX_TAN]; - } - else if (name.equals("cot")) - { - return builtinFunctions[INDEX_COT]; - } - else if (name.equals("asin")) - { - return builtinFunctions[INDEX_ASIN]; - } - else if (name.equals("acos")) - { - return builtinFunctions[INDEX_ACOS]; - } - else if (name.equals("atan")) - { - return builtinFunctions[INDEX_ATAN]; - } - else if (name.equals("sinh")) - { - return builtinFunctions[INDEX_SINH]; - } - else if (name.equals("cosh")) - { - return builtinFunctions[INDEX_COSH]; - } - else if (name.equals("tanh")) - { - return builtinFunctions[INDEX_TANH]; - } - else if (name.equals("abs")) - { - return builtinFunctions[INDEX_ABS]; - } - else if (name.equals("log")) - { - return builtinFunctions[INDEX_LOG]; - } - else if (name.equals("log10")) - { - return builtinFunctions[INDEX_LOG10]; - } - else if (name.equals("log2")) - { - return builtinFunctions[INDEX_LOG2]; - } - else if (name.equals("log1p")) - { - return builtinFunctions[INDEX_LOG1P]; - } - else if (name.equals("ceil")) - { - return builtinFunctions[INDEX_CEIL]; - } - else if (name.equals("floor")) - { - return builtinFunctions[INDEX_FLOOR]; - } - else if (name.equals("sqrt")) - { - return builtinFunctions[INDEX_SQRT]; - } - else if (name.equals("cbrt")) - { - return builtinFunctions[INDEX_CBRT]; - } - else if (name.equals("pow")) - { - return builtinFunctions[INDEX_POW]; - } - else if (name.equals("exp")) - { - return builtinFunctions[INDEX_EXP]; - } - else if (name.equals("expm1")) - { - return builtinFunctions[INDEX_EXPM1]; - } - else if (name.equals("signum")) - { - return builtinFunctions[INDEX_SGN]; - } - else - { - return null; - } - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java deleted file mode 100644 index 14787a21df..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/NumberToken.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents a number in the expression - */ -public class NumberToken extends Token -{ - private final double value; - - /** - * Create a new instance - * @param value the value of the number - */ - public NumberToken(double value) - { - super(TOKEN_NUMBER); - this.value = value; - } - - NumberToken(char[] expression, int offset, int len) - { - this(Double.parseDouble(String.valueOf(expression, offset, len))); - } - - /** - * Get the value of the number - * @return the value - */ - public double getValue() - { - return value; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java deleted file mode 100644 index c0a0dd66f6..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/OpenParenthesesToken.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -class OpenParenthesesToken extends Token -{ - OpenParenthesesToken() - { - super(TOKEN_PARENTHESES_OPEN); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Operator.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Operator.java deleted file mode 100644 index 79df70b2dd..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Operator.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Class representing operators that can be used in an expression - */ -public abstract class Operator -{ - /** - * The precedence value for the addition operation - */ - public static final int PRECEDENCE_ADDITION = 500; - /** - * The precedence value for the subtraction operation - */ - public static final int PRECEDENCE_SUBTRACTION = PRECEDENCE_ADDITION; - /** - * The precedence value for the multiplication operation - */ - public static final int PRECEDENCE_MULTIPLICATION = 1000; - /** - * The precedence value for the division operation - */ - public static final int PRECEDENCE_DIVISION = PRECEDENCE_MULTIPLICATION; - /** - * The precedence value for the modulo operation - */ - public static final int PRECEDENCE_MODULO = PRECEDENCE_DIVISION; - /** - * The precedence value for the power operation - */ - public static final int PRECEDENCE_POWER = 10000; - /** - * The precedence value for the unary minus operation - */ - public static final int PRECEDENCE_UNARY_MINUS = 5000; - /** - * The precedence value for the unary plus operation - */ - public static final int PRECEDENCE_UNARY_PLUS = PRECEDENCE_UNARY_MINUS; - - /** - * The set of allowed operator chars - */ - public static final char[] ALLOWED_OPERATOR_CHARS = - { - '+', - '-', - '*', - '/', - '%', - '^', - '!', - '#', - '§', - '$', - '&', - ';', - ':', - '~', - '<', - '>', - '|', - '=' - }; - - protected final int numOperands; - protected final boolean leftAssociative; - protected final String symbol; - protected final int precedence; - - /** - * Create a new operator for use in expressions - * @param symbol the symbol of the operator - * @param numberOfOperands the number of operands the operator takes (1 or 2) - * @param leftAssociative set to true if the operator is left associative, false if it is right associative - * @param precedence the precedence value of the operator - */ - public Operator(String symbol, int numberOfOperands, boolean leftAssociative, int precedence) - { - super(); - numOperands = numberOfOperands; - this.leftAssociative = leftAssociative; - this.symbol = symbol; - this.precedence = precedence; - } - - /** - * Check if a character is an allowed operator char - * @param ch the char to check - * @return true if the char is allowed an an operator symbol, false otherwise - */ - public static boolean isAllowedOperatorChar(char ch) - { - for (char allowed : ALLOWED_OPERATOR_CHARS) - { - if (ch == allowed) - { - return true; - } - } - return false; - } - - /** - * Check if the operator is left associative - * @return true os the operator is left associative, false otherwise - */ - public boolean isLeftAssociative() - { - return leftAssociative; - } - - /** - * Check the precedence value for the operator - * @return the precedence value - */ - public int getPrecedence() - { - return precedence; - } - - /** - * Apply the operation on the given operands - * @param args the operands for the operation - * @return the calculated result of the operation - */ - public abstract double apply(double... args); - - /** - * Get the operator symbol - * @return the symbol - */ - public String getSymbol() - { - return symbol; - } - - /** - * Get the number of operands - * @return the number of operands - */ - public int getNumOperands() - { - return numOperands; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java deleted file mode 100644 index 3e64f08b29..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/OperatorToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Represents an operator used in expressions - */ -public class OperatorToken extends Token -{ - private final Operator operator; - - /** - * Create a new instance - * @param op the operator - */ - public OperatorToken(Operator op) - { - super(Token.TOKEN_OPERATOR); - if (op == null) - { - throw new IllegalArgumentException("Operator is unknown for token."); - } - operator = op; - } - - /** - * Get the operator for that token - * @return the operator - */ - public Operator getOperator() - { - return operator; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Operators.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Operators.java deleted file mode 100644 index e1755631c9..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Operators.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -public abstract class Operators -{ - private static final int INDEX_ADDITION = 0; - private static final int INDEX_SUBTRACTION = 1; - private static final int INDEX_MUTLIPLICATION = 2; - private static final int INDEX_DIVISION = 3; - private static final int INDEX_POWER = 4; - private static final int INDEX_MODULO = 5; - private static final int INDEX_UNARYMINUS = 6; - private static final int INDEX_UNARYPLUS = 7; - - private static final Operator[] builtinOperators = new Operator[8]; - - static - { - builtinOperators[INDEX_ADDITION] = new Operator("+", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] + args[1]; - } - }; - builtinOperators[INDEX_SUBTRACTION] = new Operator("-", 2, true, Operator.PRECEDENCE_ADDITION) - { - @Override - public double apply(double... args) - { - return args[0] - args[1]; - } - }; - builtinOperators[INDEX_UNARYMINUS] = new Operator("-", 1, false, Operator.PRECEDENCE_UNARY_MINUS) - { - @Override - public double apply(double... args) - { - return -args[0]; - } - }; - builtinOperators[INDEX_UNARYPLUS] = new Operator("+", 1, false, Operator.PRECEDENCE_UNARY_PLUS) - { - @Override - public double apply(double... args) - { - return args[0]; - } - }; - builtinOperators[INDEX_MUTLIPLICATION] = new Operator("*", 2, true, Operator.PRECEDENCE_MULTIPLICATION) - { - @Override - public double apply(double... args) - { - return args[0] * args[1]; - } - }; - builtinOperators[INDEX_DIVISION] = new Operator("/", 2, true, Operator.PRECEDENCE_DIVISION) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] / args[1]; - } - }; - builtinOperators[INDEX_POWER] = new Operator("^", 2, false, Operator.PRECEDENCE_POWER) - { - @Override - public double apply(double... args) - { - return Math.pow(args[0], args[1]); - } - }; - builtinOperators[INDEX_MODULO] = new Operator("%", 2, true, Operator.PRECEDENCE_MODULO) - { - @Override - public double apply(double... args) - { - if (args[1] == 0d) - { - throw new ArithmeticException("Division by zero!"); - } - return args[0] % args[1]; - } - }; - } - - public static Operator getBuiltinOperator(char symbol, int numArguments) - { - switch (symbol) - { - case '+': - if (numArguments != 1) - { - return builtinOperators[INDEX_ADDITION]; - } - return builtinOperators[INDEX_UNARYPLUS]; - case '-': - if (numArguments != 1) - { - return builtinOperators[INDEX_SUBTRACTION]; - } - return builtinOperators[INDEX_UNARYMINUS]; - case '*': - return builtinOperators[INDEX_MUTLIPLICATION]; - case '/': - return builtinOperators[INDEX_DIVISION]; - case '^': - return builtinOperators[INDEX_POWER]; - case '%': - return builtinOperators[INDEX_MODULO]; - default: - return null; - } - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java deleted file mode 100644 index 7c543e9ce9..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ShuntingYard.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Shunting yard implementation to convert infix to reverse polish notation - */ -public class ShuntingYard -{ - /** - * Convert a Set of tokens from infix to reverse polish notation - * @param expression the expression to convert - * @param userFunctions the custom functions used - * @param userOperators the custom operators used - * @param variableNames the variable names used in the expression - * @param implicitMultiplication set to fasle to turn off implicit multiplication - * @return a {@link org.l2jmobius.gameserver.util.exp4j.Token} array containing the result - */ - public static Token[] convertToRPN(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - final Stack stack = new Stack<>(); - final List output = new ArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(expression, userFunctions, userOperators, variableNames, implicitMultiplication); - while (tokenizer.hasNext()) - { - final Token token = tokenizer.nextToken(); - switch (token.getType()) - { - case Token.TOKEN_NUMBER: - case Token.TOKEN_VARIABLE: - output.add(token); - break; - case Token.TOKEN_FUNCTION: - stack.add(token); - break; - case Token.TOKEN_SEPARATOR: - while (!stack.empty() && (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - output.add(stack.pop()); - } - if (stack.empty() || (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Misplaced function separator ',' or mismatched parentheses"); - } - break; - case Token.TOKEN_OPERATOR: - while (!stack.empty() && (stack.peek().getType() == Token.TOKEN_OPERATOR)) - { - final OperatorToken o1 = (OperatorToken) token; - final OperatorToken o2 = (OperatorToken) stack.peek(); - if ((o1.getOperator().getNumOperands() == 1) && (o2.getOperator().getNumOperands() == 2)) - { - break; - } - else if ((o1.getOperator().isLeftAssociative() && (o1.getOperator().getPrecedence() <= o2.getOperator().getPrecedence())) || (o1.getOperator().getPrecedence() < o2.getOperator().getPrecedence())) - { - output.add(stack.pop()); - } - else - { - break; - } - } - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_OPEN: - stack.push(token); - break; - case Token.TOKEN_PARENTHESES_CLOSE: - while (stack.peek().getType() != Token.TOKEN_PARENTHESES_OPEN) - { - output.add(stack.pop()); - } - stack.pop(); - if (!stack.isEmpty() && (stack.peek().getType() == Token.TOKEN_FUNCTION)) - { - output.add(stack.pop()); - } - break; - default: - throw new IllegalArgumentException("Unknown Token type encountered. This should not happen"); - } - } - while (!stack.empty()) - { - final Token t = stack.pop(); - if ((t.getType() == Token.TOKEN_PARENTHESES_CLOSE) || (t.getType() == Token.TOKEN_PARENTHESES_OPEN)) - { - throw new IllegalArgumentException("Mismatched parentheses detected. Please check the expression"); - } - output.add(t); - } - return output.toArray(new Token[output.size()]); - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Token.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Token.java deleted file mode 100644 index 1f75fda2eb..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Token.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * Abstract class for tokens used by exp4j to tokenize expressions - */ -public abstract class Token -{ - public static final short TOKEN_NUMBER = 1; - public static final short TOKEN_OPERATOR = 2; - public static final short TOKEN_FUNCTION = 3; - public static final short TOKEN_PARENTHESES_OPEN = 4; - public static final short TOKEN_PARENTHESES_CLOSE = 5; - public static final short TOKEN_VARIABLE = 6; - public static final short TOKEN_SEPARATOR = 7; - - private final int type; - - Token(int type) - { - this.type = type; - } - - public int getType() - { - return type; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java deleted file mode 100644 index a32caa4954..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/Tokenizer.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.Map; -import java.util.Set; - -public class Tokenizer -{ - private final char[] expression; - - private final int expressionLength; - - private final Map userFunctions; - - private final Map userOperators; - - private final Set variableNames; - - private final boolean implicitMultiplication; - - private int pos = 0; - - private Token lastToken; - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames, boolean implicitMultiplication) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - this.implicitMultiplication = implicitMultiplication; - } - - public Tokenizer(String expression, Map userFunctions, Map userOperators, Set variableNames) - { - this.expression = expression.trim().toCharArray(); - expressionLength = this.expression.length; - this.userFunctions = userFunctions; - this.userOperators = userOperators; - this.variableNames = variableNames; - implicitMultiplication = true; - } - - public boolean hasNext() - { - return expression.length > pos; - } - - public Token nextToken() - { - char ch = expression[pos]; - while (Character.isWhitespace(ch)) - { - ch = expression[++pos]; - } - if (Character.isDigit(ch) || (ch == '.')) - { - if (lastToken != null) - { - if (lastToken.getType() == Token.TOKEN_NUMBER) - { - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - else if (implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - } - return parseNumberToken(ch); - } - else if (isArgumentSeparator(ch)) - { - return parseArgumentSeparatorToken(ch); - } - else if (isOpenParentheses(ch)) - { - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseParentheses(true); - } - else if (isCloseParentheses(ch)) - { - return parseParentheses(false); - } - else if (Operator.isAllowedOperatorChar(ch)) - { - return parseOperatorToken(ch); - } - else if (isAlphabetic(ch) || (ch == '_')) - { - // parse the name which can be a setVariable or a function - if ((lastToken != null) && implicitMultiplication && ((lastToken.getType() != Token.TOKEN_OPERATOR) && (lastToken.getType() != Token.TOKEN_PARENTHESES_OPEN) && (lastToken.getType() != Token.TOKEN_FUNCTION) && (lastToken.getType() != Token.TOKEN_SEPARATOR))) - { - // insert an implicit multiplication token - lastToken = new OperatorToken(Operators.getBuiltinOperator('*', 2)); - return lastToken; - } - return parseFunctionOrVariable(); - } - throw new IllegalArgumentException("Unable to parse char '" + ch + "' (Code:" + (int) ch + ") at [" + pos + "]"); - } - - private Token parseArgumentSeparatorToken(char ch) - { - pos++; - lastToken = new ArgumentSeparatorToken(); - return lastToken; - } - - private boolean isArgumentSeparator(char ch) - { - return ch == ','; - } - - private Token parseParentheses(boolean open) - { - if (open) - { - lastToken = new OpenParenthesesToken(); - } - else - { - lastToken = new CloseParenthesesToken(); - } - pos++; - return lastToken; - } - - private boolean isOpenParentheses(char ch) - { - return (ch == '(') || (ch == '{') || (ch == '['); - } - - private boolean isCloseParentheses(char ch) - { - return (ch == ')') || (ch == '}') || (ch == ']'); - } - - private Token parseFunctionOrVariable() - { - final int offset = pos; - int testPos; - int lastValidLen = 1; - Token lastValidToken = null; - int len = 1; - if (isEndOfExpression(offset)) - { - pos++; - } - testPos = (offset + len) - 1; - while (!isEndOfExpression(testPos) && isVariableOrFunctionCharacter(expression[testPos])) - { - final String name = new String(expression, offset, len); - if ((variableNames != null) && variableNames.contains(name)) - { - lastValidLen = len; - lastValidToken = new VariableToken(name); - } - else - { - final Function f = getFunction(name); - if (f != null) - { - lastValidLen = len; - lastValidToken = new FunctionToken(f); - } - } - len++; - testPos = (offset + len) - 1; - } - if (lastValidToken == null) - { - throw new UnknownFunctionOrVariableException(new String(expression), pos, len); - } - pos += lastValidLen; - lastToken = lastValidToken; - return lastToken; - } - - private Function getFunction(String name) - { - Function f = null; - if (userFunctions != null) - { - f = userFunctions.get(name); - } - if (f == null) - { - f = Functions.getBuiltinFunction(name); - } - return f; - } - - private Token parseOperatorToken(char firstChar) - { - final int offset = pos; - int len = 1; - final StringBuilder symbol = new StringBuilder(); - Operator lastValid = null; - symbol.append(firstChar); - - while (!isEndOfExpression(offset + len) && Operator.isAllowedOperatorChar(expression[offset + len])) - { - symbol.append(expression[offset + len++]); - } - - while (symbol.length() > 0) - { - final Operator op = getOperator(symbol.toString()); - if (op == null) - { - symbol.setLength(symbol.length() - 1); - } - else - { - lastValid = op; - break; - } - } - - pos += symbol.length(); - lastToken = new OperatorToken(lastValid); - return lastToken; - } - - private Operator getOperator(String symbol) - { - Operator op = null; - if (userOperators != null) - { - op = userOperators.get(symbol); - } - if ((op == null) && (symbol.length() == 1)) - { - int argc = 2; - if (lastToken == null) - { - argc = 1; - } - else - { - final int lastTokenType = lastToken.getType(); - if ((lastTokenType == Token.TOKEN_PARENTHESES_OPEN) || (lastTokenType == Token.TOKEN_SEPARATOR)) - { - argc = 1; - } - else if (lastTokenType == Token.TOKEN_OPERATOR) - { - final Operator lastOp = ((OperatorToken) lastToken).getOperator(); - if ((lastOp.getNumOperands() == 2) || ((lastOp.getNumOperands() == 1) && !lastOp.isLeftAssociative())) - { - argc = 1; - } - } - } - op = Operators.getBuiltinOperator(symbol.charAt(0), argc); - } - return op; - } - - private Token parseNumberToken(char firstChar) - { - final int offset = pos; - int len = 1; - pos++; - if (isEndOfExpression(offset + len)) - { - lastToken = new NumberToken(Double.parseDouble(String.valueOf(firstChar))); - return lastToken; - } - while (!isEndOfExpression(offset + len) && isNumeric(expression[offset + len], (expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E'))) - { - len++; - pos++; - } - // check if the e is at the end - if ((expression[(offset + len) - 1] == 'e') || (expression[(offset + len) - 1] == 'E')) - { - // since the e is at the end it's not part of the number and a rollback is necessary - len--; - pos--; - } - lastToken = new NumberToken(expression, offset, len); - return lastToken; - } - - private static boolean isNumeric(char ch, boolean lastCharE) - { - return Character.isDigit(ch) || (ch == '.') || (ch == 'e') || (ch == 'E') || (lastCharE && ((ch == '-') || (ch == '+'))); - } - - private static boolean isAlphabetic(int codePoint) - { - return Character.isLetter(codePoint); - } - - private static boolean isVariableOrFunctionCharacter(int codePoint) - { - return isAlphabetic(codePoint) || Character.isDigit(codePoint) || (codePoint == '_') || (codePoint == '.'); - } - - private boolean isEndOfExpression(int offset) - { - return expressionLength <= offset; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java deleted file mode 100644 index 1f30b5e3e9..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/UnknownFunctionOrVariableException.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * This exception is being thrown whenever {@link Tokenizer} finds unknown function or variable. - * @author Bartosz Firyn (sarxos) - */ -public class UnknownFunctionOrVariableException extends IllegalArgumentException -{ - private final String message; - private final String expression; - private final String token; - private final int position; - - public UnknownFunctionOrVariableException(String expression, int position, int length) - { - this.expression = expression; - token = token(expression, position, length); - this.position = position; - message = "Unknown function or variable '" + token + "' at pos " + position + " in expression '" + expression + "'"; - } - - private static String token(String expression, int position, int length) - { - final int len = expression.length(); - int end = (position + length) - 1; - if (len < end) - { - end = len; - } - return expression.substring(position, end); - } - - @Override - public String getMessage() - { - return message; - } - - /** - * @return Expression which contains unknown function or variable - */ - public String getExpression() - { - return expression; - } - - /** - * @return The name of unknown function or variable - */ - public String getToken() - { - return token; - } - - /** - * @return The position of unknown function or variable - */ - public int getPosition() - { - return position; - } -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java deleted file mode 100644 index b72c236744..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/ValidationResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright 2014 Frank Asseg -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.l2jmobius.gameserver.util.exp4j; - -import java.util.List; - -/** - * Contains the validation result for a given {@link Expression} - */ -public class ValidationResult -{ - private final boolean valid; - private final List errors; - - /** - * Create a new instance - * @param valid Whether the validation of the expression was successful - * @param errors The list of errors returned if the validation was unsuccessful - */ - public ValidationResult(boolean valid, List errors) - { - this.valid = valid; - this.errors = errors; - } - - /** - * Check if an expression has been validated successfully - * @return true if the validation was successful, false otherwise - */ - public boolean isValid() - { - return valid; - } - - /** - * Get the list of errors describing the issues while validating the expression - * @return The List of errors - */ - public List getErrors() - { - return errors; - } - - /** - * A static class representing a successful validation result - */ - public static final ValidationResult SUCCESS = new ValidationResult(true, null); -} diff --git a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java b/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java deleted file mode 100644 index 457659b1ec..0000000000 --- a/L2J_Mobius_Classic_Interlude/java/org/l2jmobius/gameserver/util/exp4j/VariableToken.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Frank Asseg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.l2jmobius.gameserver.util.exp4j; - -/** - * represents a setVariable used in an expression - */ -public class VariableToken extends Token -{ - private final String name; - - /** - * Get the name of the setVariable - * @return the name - */ - public String getName() - { - return name; - } - - /** - * Create a new instance - * @param name the name of the setVariable - */ - public VariableToken(String name) - { - super(TOKEN_VARIABLE); - this.name = name; - } -}