/.settings/
/.project
/.classpath
-target/
+/target/
+/.idea/
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>eu.svjatoslav</groupId>
- <artifactId>svjatoslavcommons</artifactId>
- <version>1.5-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>Svjatoslav Commons</name>
- <description>Collection many small but commonly useful functionalities</description>
- <url>http://www2.svjatoslav.eu/gitbrowse/svjatoslav_commons/doc/index.html</url>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>eu.svjatoslav</groupId>
+ <artifactId>svjatoslavcommons</artifactId>
+ <version>1.5-SNAPSHOT</version>
+ <packaging>jar</packaging>
+ <name>Svjatoslav Commons</name>
+ <description>Collection many small but commonly useful functionalities</description>
+ <url>http://www2.svjatoslav.eu/gitbrowse/svjatoslav_commons/doc/index.html</url>
- <licenses>
- <license>
- <name>version 3 of the GNU Lesser General Public License or later</name>
- <url>https://www.gnu.org/licenses/lgpl.html</url>
- <distribution>repo</distribution>
- </license>
- </licenses>
+ <licenses>
+ <license>
+ <name>version 3 of the GNU Lesser General Public License or later</name>
+ <url>https://www.gnu.org/licenses/lgpl.html</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- </properties>
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ </properties>
- <reporting>
- <plugins>
- <plugin>
- <!-- Compile JUnit test coverage report -->
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- <version>2.6</version>
- <configuration>
- <formats>
- <format>html</format>
- <format>xml</format>
- </formats>
- </configuration>
- </plugin>
- <plugin>
- <!-- Attempt to discover bugs by doing static code analysis -->
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- <version>2.5.3</version>
- </plugin>
- </plugins>
- </reporting>
+ <reporting>
+ <plugins>
+ <plugin>
+ <!-- Compile JUnit test coverage report -->
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ <version>2.6</version>
+ <configuration>
+ <formats>
+ <format>html</format>
+ <format>xml</format>
+ </formats>
+ </configuration>
+ </plugin>
+ <plugin>
+ <!-- Attempt to discover bugs by doing static code analysis -->
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <version>2.5.3</version>
+ </plugin>
+ </plugins>
+ </reporting>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.3.2</version>
- <configuration>
- <source>1.6</source>
- <target>1.6</target>
- <encoding>UTF-8</encoding>
- </configuration>
- </plugin>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ <encoding>UTF-8</encoding>
+ </configuration>
+ </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <version>2.2.1</version>
- <executions>
- <execution>
- <id>attach-sources</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <version>2.2.1</version>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.9</version>
- <executions>
- <execution>
- <id>attach-javadocs</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.9</version>
+ <executions>
+ <execution>
+ <id>attach-javadocs</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
- <plugin>
- <!-- Compile JUnit test coverage report -->
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- <version>2.6</version>
- <configuration>
- <check>
- <branchRate>85</branchRate>
- <lineRate>85</lineRate>
- <haltOnFailure>false</haltOnFailure>
- <totalBranchRate>85</totalBranchRate>
- <totalLineRate>85</totalLineRate>
- <packageLineRate>85</packageLineRate>
- <packageBranchRate>85</packageBranchRate>
- </check>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>clean</goal>
- <!-- <goal>check</goal> -->
- </goals>
- </execution>
- </executions>
- </plugin>
+ </plugins>
- </plugins>
+ <extensions>
+ <extension>
+ <groupId>org.apache.maven.wagon</groupId>
+ <artifactId>wagon-ssh-external</artifactId>
+ <version>2.6</version>
+ </extension>
+ </extensions>
+ </build>
- <extensions>
- <extension>
- <groupId>org.apache.maven.wagon</groupId>
- <artifactId>wagon-ssh-external</artifactId>
- <version>2.6</version>
- </extension>
- </extensions>
- </build>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.8.1</version>
+ <scope>test</scope>
+ </dependency>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.8.1</version>
- <scope>test</scope>
- </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- <scope>provided</scope>
- </dependency>
- </dependencies>
+ <distributionManagement>
+ <snapshotRepository>
+ <id>svjatoslav.eu</id>
+ <name>svjatoslav.eu</name>
+ <url>scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven</url>
+ </snapshotRepository>
+ <repository>
+ <id>svjatoslav.eu</id>
+ <name>svjatoslav.eu</name>
+ <url>scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven</url>
+ </repository>
+ </distributionManagement>
- <distributionManagement>
- <snapshotRepository>
- <id>svjatoslav.eu</id>
- <name>svjatoslav.eu</name>
- <url>scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven</url>
- </snapshotRepository>
- <repository>
- <id>svjatoslav.eu</id>
- <name>svjatoslav.eu</name>
- <url>scpexe://svjatoslav.eu/var/www/svjatoslav.eu/maven</url>
- </repository>
- </distributionManagement>
-
- <scm>
- <connection>scm:git:ssh://git@svjatoslav.eu/home/git/repositories/svjatoslav_commons.git</connection>
- <developerConnection>scm:git:ssh://git@svjatoslav.eu/home/git/repositories/svjatoslav_commons.git</developerConnection>
- </scm>
+ <scm>
+ <connection>scm:git:ssh://git@svjatoslav.eu/home/git/repositories/svjatoslav_commons.git</connection>
+ <developerConnection>scm:git:ssh://git@svjatoslav.eu/home/git/repositories/svjatoslav_commons.git
+ </developerConnection>
+ </scm>
</project>
*/
public class CLIHelper {
- /**
- * Ask boolean value from user on command-line.
- *
- * @param prompt
- * to show to the user
- * @return <code>true</code> is user answered affirmative.
- */
- public static boolean askBoolean(final String prompt) {
-
- final BufferedReader br = new BufferedReader(new InputStreamReader(
- System.in));
-
- while (true)
- try {
- System.out.print(prompt);
-
- final String userInput = br.readLine().toLowerCase();
-
- if ("y".equals(userInput) || "yes".equals(userInput)
- || "true".equals(userInput))
- return true;
-
- if ("n".equals(userInput) || "no".equals(userInput)
- || "false".equals(userInput))
- return false;
-
- System.out
- .println("Invalid input. You shall enter y/yes/true or n/no/false.");
- } catch (final IOException ioe) {
- ioe.printStackTrace();
- }
- }
-
- /**
- * Ask numerical long value from user on command-line.
- *
- * @param prompt
- * to show to the user
- * @return value given by user
- */
- public static long askLong(final String prompt) {
-
- final BufferedReader br = new BufferedReader(new InputStreamReader(
- System.in));
-
- while (true) {
- System.out.print(prompt);
-
- try {
- final String userInput = br.readLine();
-
- try {
- final long result = Long.parseLong(userInput);
- return result;
- } catch (final NumberFormatException e) {
- System.out.println("\nError: You shall enter an integer.");
- }
- } catch (final IOException ioe) {
- ioe.printStackTrace();
- }
-
- }
- }
-
- /**
- * Ask string value from user on command-line.
- *
- * @param prompt
- * to show to the user
- * @return value given by the user
- */
- public static String askString(final String prompt) {
-
- final BufferedReader br = new BufferedReader(new InputStreamReader(
- System.in));
-
- while (true) {
- System.out.print(prompt);
-
- try {
- final String userInput = br.readLine();
-
- return userInput;
- } catch (final IOException ioe) {
- ioe.printStackTrace();
- }
-
- }
- }
+ /**
+ * Ask boolean value from user on command-line.
+ *
+ * @param prompt to show to the user
+ * @return <code>true</code> is user answered affirmative.
+ */
+ public static boolean askBoolean(final String prompt) {
+
+ final BufferedReader br = new BufferedReader(new InputStreamReader(
+ System.in));
+
+ while (true)
+ try {
+ System.out.print(prompt);
+
+ String line = br.readLine();
+ if (line != null) {
+ final String userInput = line.toLowerCase();
+
+ if ("y".equals(userInput) || "yes".equals(userInput)
+ || "true".equals(userInput))
+ return true;
+
+ if ("n".equals(userInput) || "no".equals(userInput)
+ || "false".equals(userInput))
+ return false;
+ }
+ System.out
+ .println("Invalid input. You shall enter y/yes/true or n/no/false.");
+ } catch (final IOException ioe) {
+ ioe.printStackTrace();
+ }
+ }
+
+ /**
+ * Ask numerical long value from user on command-line.
+ *
+ * @param prompt to show to the user
+ * @return value given by user
+ */
+ public static long askLong(final String prompt) {
+
+ final BufferedReader br = new BufferedReader(new InputStreamReader(
+ System.in));
+
+ while (true) {
+ System.out.print(prompt);
+
+ try {
+ final String userInput = br.readLine();
+
+ try {
+ return Long.parseLong(userInput);
+ } catch (final NumberFormatException e) {
+ System.out.println("\nError: You shall enter an integer.");
+ }
+ } catch (final IOException ioe) {
+ ioe.printStackTrace();
+ }
+
+ }
+ }
+
+ /**
+ * Ask string value from user on command-line.
+ *
+ * @param prompt to show to the user
+ * @return value given by the user
+ */
+ public static String askString(final String prompt) {
+
+ final BufferedReader br = new BufferedReader(new InputStreamReader(
+ System.in));
+
+ while (true) {
+ System.out.print(prompt);
+
+ try {
+ final String userInput = br.readLine();
+
+ return userInput;
+ } catch (final IOException ioe) {
+ ioe.printStackTrace();
+ }
+
+ }
+ }
}
public enum ArgumentCount {
- NONE, // parameter has no arguments
- SINGLE, // parameter has one argument
- MULTI // parameter can have multiple arguments
+ NONE, // parameter has no arguments
+ SINGLE, // parameter has one argument
+ MULTI // parameter can have multiple arguments
}
package eu.svjatoslav.commons.commandline.parameterparser;
import java.util.ArrayList;
+import java.util.Collections;
public abstract class Parameter<T> {
- /**
- * Indicates that at least one argument is mandatory for this parameter.
- */
- protected boolean mandatory;
+ public final String description;
+ public final ArrayList<String> arguments = new ArrayList<>();
+ final ArgumentCount argumentCount;
+ private final ArrayList<String> aliases = new ArrayList<>();
+ /**
+ * Indicates that at least one argument is mandatory for this parameter.
+ */
+ protected boolean mandatory;
+ /**
+ * If this parameter was present in the commandline, then this boolean will
+ * be set to <code>true</code>.
+ */
+ private boolean parameterSpecified;
+
+ public Parameter(final boolean mandatory,
+ final ArgumentCount argumentCount, final String description,
+ final String... aliases2) {
- private final ArrayList<String> aliases = new ArrayList<String>();
+ this.mandatory = mandatory;
+ this.description = description;
+ this.argumentCount = argumentCount;
- public final String description;
-
- public final ArrayList<String> arguments = new ArrayList<String>();
-
- final ArgumentCount argumentCount;
-
- /**
- * If this parameter was present in the commandline, then this boolean will
- * be set to <code>true</code>.
- */
- private boolean parameterSpecified;
-
- public Parameter(final boolean mandatory,
- final ArgumentCount argumentCount, final String description,
- final String... aliases2) {
-
- this.mandatory = mandatory;
- this.description = description;
- this.argumentCount = argumentCount;
-
- // save aliases
- for (final String alias : aliases2)
- aliases.add(alias);
-
- };
-
- public Parameter(final String description, final ArgumentCount argumentCount) {
- this.description = description;
- this.argumentCount = argumentCount;
- }
-
- @SuppressWarnings("unchecked")
- public T addAliases(final String... aliasArray) {
-
- // save aliases
- for (final String alias : aliasArray)
- aliases.add(alias);
-
- return (T) this;
- }
-
- /**
- * @param argumentString
- * argument to add
- * @return <code>true</code> if no errors were found. <code>false</code>
- * otherwise.
- */
- public boolean addArgument(final String argumentString) {
- // check if arguments are allowed for this parameter
- if (argumentCount.equals(ArgumentCount.NONE)) {
- System.out
- .println("Error! No arguments are allowed for parameters: "
- + getAliases());
- return false;
- }
-
- // check if multiple arguments are allowed
- if ((arguments.size() > 0)
- && (argumentCount.equals(ArgumentCount.SINGLE))) {
- System.out
- .println("Error! Only single argument is allowed for parameters: "
- + getAliases());
- return false;
- }
-
- if (!validate(argumentString)) {
-
- System.out.println("Error! Invalid argument \"" + argumentString
- + "\". It shall be " + describeFormat() + ".");
- return false;
-
- }
-
- arguments.add(argumentString);
-
- return true;
- }
-
- /**
- * @return Single line argument type description.
- */
- public abstract String describeFormat();
-
- public String getAliases() {
- final StringBuffer buffer = new StringBuffer();
-
- for (final String alias : aliases) {
-
- if (buffer.length() > 0)
- buffer.append(", ");
-
- buffer.append(alias);
- }
-
- return buffer.toString();
- }
-
- public String getHelp() {
- final StringBuffer buffer = new StringBuffer();
-
- // first line
- buffer.append(getAliases());
- if (!argumentCount.equals(ArgumentCount.NONE)) {
- buffer.append(" (" + describeFormat() + ")");
-
- if (argumentCount.equals(ArgumentCount.MULTI))
- buffer.append("...");
- }
- buffer.append("\n");
-
- // second line
- buffer.append(" " + description + "\n");
-
- return buffer.toString();
- }
-
- public abstract Object getValue();
-
- public boolean isMandatory() {
- return mandatory;
- }
-
- /**
- * @return the parameterSpecified
- */
- public boolean isParameterSpecified() {
- return parameterSpecified;
- }
-
- /**
- * @param alias
- * alias to check against
- * @return <code>true</code> if given alias is registered for this
- * parameter.
- */
- public boolean matchesAlias(final String alias) {
- if (aliases.contains(alias))
- return true;
-
- return false;
- }
-
- /**
- * Notifies this parameter that no more arguments will follow. This gives
- * parameter chance to verify if this is ok.
- *
- * @return <code>true</code> if no errors were found. <code>false</code>
- * otherwise.
- */
- public boolean noMoreArguments() {
-
- if ((!argumentCount.equals(ArgumentCount.NONE))
- && (arguments.isEmpty())) {
-
- System.out.println("Error! " + getAliases()
- + " require at least one following argument.");
-
- return false;
- }
- return true;
- }
-
- @SuppressWarnings("unchecked")
- public T setMandatory() {
- mandatory = true;
- return (T) this;
- }
-
- /**
- * @param parameterSpecified
- * the parameterSpecified to set
- */
- public void setParameterSpecified(final boolean parameterSpecified) {
- this.parameterSpecified = parameterSpecified;
- }
-
- /**
- * @param value
- * value to validate
- * @return <code>true</code> if value is correct, <code>false</code>
- * otherwise.
- */
- public abstract boolean validate(String value);
+ // save aliases
+ Collections.addAll(aliases, aliases2);
+
+ }
+
+ public Parameter(final String description, final ArgumentCount argumentCount) {
+ this.description = description;
+ this.argumentCount = argumentCount;
+ }
+
+ @SuppressWarnings("unchecked")
+ public T addAliases(final String... aliasArray) {
+
+ // save aliases
+ Collections.addAll(aliases, aliasArray);
+
+ return (T) this;
+ }
+
+ /**
+ * @param argumentString argument to add
+ * @return <code>true</code> if no errors were found. <code>false</code>
+ * otherwise.
+ */
+ public boolean addArgument(final String argumentString) {
+ // check if arguments are allowed for this parameter
+ if (argumentCount.equals(ArgumentCount.NONE)) {
+ System.out
+ .println("Error! No arguments are allowed for parameters: "
+ + getAliases());
+ return false;
+ }
+
+ // check if multiple arguments are allowed
+ if ((arguments.size() > 0)
+ && (argumentCount.equals(ArgumentCount.SINGLE))) {
+ System.out
+ .println("Error! Only single argument is allowed for parameters: "
+ + getAliases());
+ return false;
+ }
+
+ if (!validate(argumentString)) {
+
+ System.out.println("Error! Invalid argument \"" + argumentString
+ + "\". It shall be " + describeFormat() + ".");
+ return false;
+
+ }
+
+ arguments.add(argumentString);
+
+ return true;
+ }
+
+ /**
+ * @return Single line argument type description.
+ */
+ public abstract String describeFormat();
+
+ public String getAliases() {
+ final StringBuilder buffer = new StringBuilder();
+
+ for (final String alias : aliases) {
+
+ if (buffer.length() > 0)
+ buffer.append(", ");
+
+ buffer.append(alias);
+ }
+
+ return buffer.toString();
+ }
+
+ public String getHelp() {
+ final StringBuilder buffer = new StringBuilder();
+
+ // first line
+ buffer.append(getAliases());
+ if (!argumentCount.equals(ArgumentCount.NONE)) {
+ buffer.append(" (" + describeFormat() + ")");
+
+ if (argumentCount.equals(ArgumentCount.MULTI))
+ buffer.append("...");
+ }
+ buffer.append("\n");
+
+ // second line
+ buffer.append(" " + description + "\n");
+
+ return buffer.toString();
+ }
+
+ public abstract Object getValue();
+
+ public boolean isMandatory() {
+ return mandatory;
+ }
+
+ /**
+ * @return the parameterSpecified
+ */
+ public boolean isParameterSpecified() {
+ return parameterSpecified;
+ }
+
+ /**
+ * @param parameterSpecified the parameterSpecified to set
+ */
+ public void setParameterSpecified(final boolean parameterSpecified) {
+ this.parameterSpecified = parameterSpecified;
+ }
+
+ /**
+ * @param alias alias to check against
+ * @return <code>true</code> if given alias is registered for this
+ * parameter.
+ */
+ public boolean matchesAlias(final String alias) {
+ return aliases.contains(alias);
+
+ }
+
+ /**
+ * Notifies this parameter that no more arguments will follow. This gives
+ * parameter chance to verify if this is ok.
+ *
+ * @return <code>true</code> if no errors were found. <code>false</code>
+ * otherwise.
+ */
+ public boolean noMoreArguments() {
+
+ if ((!argumentCount.equals(ArgumentCount.NONE))
+ && (arguments.isEmpty())) {
+
+ System.out.println("Error! " + getAliases()
+ + " require at least one following argument.");
+
+ return false;
+ }
+ return true;
+ }
+
+ @SuppressWarnings("unchecked")
+ public T setMandatory() {
+ mandatory = true;
+ return (T) this;
+ }
+
+ /**
+ * @param value value to validate
+ * @return <code>true</code> if value is correct, <code>false</code>
+ * otherwise.
+ */
+ public abstract boolean validate(String value);
}
*/
public class Parser {
- private final ArrayList<Parameter<?>> parameters = new ArrayList<Parameter<?>>();
-
- public <E extends Parameter<?>> E add(final E parameter) {
- parameters.add(parameter);
- return parameter;
- }
-
- /**
- * @return <code>true</code> if no errors were found. <code>false</code>
- * otherwise.
- */
- private boolean checkMandatoryArgumentsPresent() {
-
- for (final Parameter<?> parameter : parameters)
- if (parameter.isMandatory() && (!parameter.isParameterSpecified())) {
- System.out.println("Error! Mandatory parameter ("
- + parameter.getAliases() + ") is not specified.");
- return false;
- }
-
- return true;
- }
-
- /**
- * Return parameter by given alias or <code>null</code> if no parameter
- * exists for given alias.
- *
- * @param alias
- * parameter alias
- * @return found parameter or <code>null</code> if parameter was not found.
- */
- public Parameter<?> findParameterByAlias(final String alias) {
-
- for (final Parameter<?> parameter : parameters)
- if (parameter.matchesAlias(alias))
- return parameter;
-
- return null;
- }
-
- /**
- * @param args
- * commandline arguments
- * @return <code>true</code> if no errors were found. <code>false</code>
- * otherwise.
- */
- public boolean parse(final String[] args) {
-
- Parameter<?> currentParameter = null;
-
- for (final String argument : args) {
-
- final Parameter<?> parameterForAlias = findParameterByAlias(argument);
- if (parameterForAlias == null) {
- if (currentParameter == null) {
- System.out.println("Unknown commandline parameter: "
- + argument);
- return false;
- }
-
- if (!currentParameter.addArgument(argument))
- return false;
-
- } else {
- if (currentParameter != null)
- if (!currentParameter.noMoreArguments())
- return false;
-
- parameterForAlias.setParameterSpecified(true);
- currentParameter = parameterForAlias;
- }
-
- }
-
- return checkMandatoryArgumentsPresent();
- }
-
- public void showHelp() {
- for (final Parameter<?> parameter : parameters)
- System.out.println(parameter.getHelp());
- }
+ private final ArrayList<Parameter<?>> parameters = new ArrayList<>();
+
+ public <E extends Parameter<?>> E add(final E parameter) {
+ parameters.add(parameter);
+ return parameter;
+ }
+
+ /**
+ * @return <code>true</code> if no errors were found. <code>false</code>
+ * otherwise.
+ */
+ private boolean checkMandatoryArgumentsPresent() {
+
+ for (final Parameter<?> parameter : parameters)
+ if (parameter.isMandatory() && (!parameter.isParameterSpecified())) {
+ System.out.println("Error! Mandatory parameter ("
+ + parameter.getAliases() + ") is not specified.");
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Return parameter by given alias or <code>null</code> if no parameter
+ * exists for given alias.
+ *
+ * @param alias parameter alias
+ * @return found parameter or <code>null</code> if parameter was not found.
+ */
+ public Parameter<?> findParameterByAlias(final String alias) {
+
+ for (final Parameter<?> parameter : parameters)
+ if (parameter.matchesAlias(alias))
+ return parameter;
+
+ return null;
+ }
+
+ /**
+ * @param args commandline arguments
+ * @return <code>true</code> if no errors were found. <code>false</code>
+ * otherwise.
+ */
+ public boolean parse(final String[] args) {
+
+ Parameter<?> currentParameter = null;
+
+ for (final String argument : args) {
+
+ final Parameter<?> parameterForAlias = findParameterByAlias(argument);
+ if (parameterForAlias == null) {
+ if (currentParameter == null) {
+ System.out.println("Unknown commandline parameter: "
+ + argument);
+ return false;
+ }
+
+ if (!currentParameter.addArgument(argument))
+ return false;
+
+ } else {
+ if (currentParameter != null)
+ if (!currentParameter.noMoreArguments())
+ return false;
+
+ parameterForAlias.setParameterSpecified(true);
+ currentParameter = parameterForAlias;
+ }
+
+ }
+
+ return checkMandatoryArgumentsPresent();
+ }
+
+ public void showHelp() {
+ for (final Parameter<?> parameter : parameters)
+ System.out.println(parameter.getHelp());
+ }
}
package eu.svjatoslav.commons.commandline.parameterparser.parameter;
-import java.io.File;
-
import eu.svjatoslav.commons.commandline.parameterparser.ArgumentCount;
import eu.svjatoslav.commons.commandline.parameterparser.Parameter;
+import java.io.File;
+
public class DirectoryParameter extends Parameter<DirectoryParameter> {
- private ExistanceType existanceType = ExistanceType.DOES_NOT_MATTER;
+ private ExistenceType existenceType = ExistenceType.DOES_NOT_MATTER;
- public DirectoryParameter(final String description) {
- super(description, ArgumentCount.SINGLE);
- }
+ public DirectoryParameter(final String description) {
+ super(description, ArgumentCount.SINGLE);
+ }
- @Override
- public java.lang.String describeFormat() {
- return existanceType.description + "directory";
- }
+ @Override
+ public java.lang.String describeFormat() {
+ return existenceType.description + "directory";
+ }
- @Override
- public File getValue() {
+ @Override
+ public File getValue() {
- if (arguments.size() != 1)
- throw new RuntimeException("Parameter " + description
- + " shall have exactly 1 argument.");
+ if (arguments.size() != 1)
+ throw new RuntimeException("Parameter " + description
+ + " shall have exactly 1 argument.");
- return new File(arguments.get(0));
- }
+ return new File(arguments.get(0));
+ }
- public DirectoryParameter mustExist() {
- existanceType = ExistanceType.MUST_EXIST;
- return this;
- }
+ public DirectoryParameter mustExist() {
+ existenceType = ExistenceType.MUST_EXIST;
+ return this;
+ }
- public DirectoryParameter mustNotExist() {
- existanceType = ExistanceType.MUST_NOT_EXIST;
- return this;
- }
+ public DirectoryParameter mustNotExist() {
+ existenceType = ExistenceType.MUST_NOT_EXIST;
+ return this;
+ }
- @Override
- public boolean validate(final java.lang.String value) {
- final File file = new File(value);
+ @Override
+ public boolean validate(final java.lang.String value) {
+ final File file = new File(value);
- if (existanceType == ExistanceType.MUST_EXIST) {
- if (file.exists() && file.isDirectory())
- return true;
- return false;
- }
+ if (existenceType == ExistenceType.MUST_EXIST) {
+ return file.exists() && file.isDirectory();
+ }
- if (existanceType == ExistanceType.MUST_NOT_EXIST) {
- if (file.exists())
- return false;
- return true;
- }
+ if (existenceType == ExistenceType.MUST_NOT_EXIST) {
+ return !file.exists();
+ }
- if (existanceType == ExistanceType.DOES_NOT_MATTER) {
- if (file.exists())
- if (file.isFile())
- return false;
+ if (existenceType == ExistenceType.DOES_NOT_MATTER) {
+ if (file.exists())
+ if (file.isFile())
+ return false;
- return true;
- }
+ return true;
+ }
- return false;
- }
+ return false;
+ }
}
+++ /dev/null
-/*
- * Svjatoslav Commons - shared library of common functionality.
- * Copyright ©2012-2014, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of version 3 of the GNU Lesser General Public License
- * or later as published by the Free Software Foundation.
- */
-
-package eu.svjatoslav.commons.commandline.parameterparser.parameter;
-
-public enum ExistanceType {
-
- MUST_EXIST("existing"), MUST_NOT_EXIST("not existing"), DOES_NOT_MATTER("");
-
- public final String description;
-
- ExistanceType(final String description) {
- this.description = description;
- }
-
-}
--- /dev/null
+/*
+ * Svjatoslav Commons - shared library of common functionality.
+ * Copyright ©2012-2014, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of version 3 of the GNU Lesser General Public License
+ * or later as published by the Free Software Foundation.
+ */
+
+package eu.svjatoslav.commons.commandline.parameterparser.parameter;
+
+public enum ExistenceType {
+
+ MUST_EXIST("existing"), MUST_NOT_EXIST("not existing"), DOES_NOT_MATTER("");
+
+ public final String description;
+
+ ExistenceType(final String description) {
+ this.description = description;
+ }
+
+}
package eu.svjatoslav.commons.commandline.parameterparser.parameter;
-import java.io.File;
-
import eu.svjatoslav.commons.commandline.parameterparser.ArgumentCount;
import eu.svjatoslav.commons.commandline.parameterparser.Parameter;
+import java.io.File;
+
public class FileParameter extends Parameter<FileParameter> {
- private ExistanceType existanceType = ExistanceType.DOES_NOT_MATTER;
+ private ExistenceType existenceType = ExistenceType.DOES_NOT_MATTER;
- public FileParameter(final String description) {
- super(description, ArgumentCount.SINGLE);
- }
+ public FileParameter(final String description) {
+ super(description, ArgumentCount.SINGLE);
+ }
- @Override
- public java.lang.String describeFormat() {
- return existanceType.description + " file";
- }
+ @Override
+ public java.lang.String describeFormat() {
+ return existenceType.description + " file";
+ }
- @Override
- public File getValue() {
+ @Override
+ public File getValue() {
- if (arguments.size() != 1)
- throw new RuntimeException("Parameter " + description
- + " shall have exactly 1 argument.");
+ if (arguments.size() != 1)
+ throw new RuntimeException("Parameter " + description
+ + " shall have exactly 1 argument.");
- return new File(arguments.get(0));
- }
+ return new File(arguments.get(0));
+ }
- public FileParameter mustExist() {
- existanceType = ExistanceType.MUST_EXIST;
- return this;
- }
+ public FileParameter mustExist() {
+ existenceType = ExistenceType.MUST_EXIST;
+ return this;
+ }
- public FileParameter mustNotExist() {
- existanceType = ExistanceType.MUST_NOT_EXIST;
- return this;
- }
+ public FileParameter mustNotExist() {
+ existenceType = ExistenceType.MUST_NOT_EXIST;
+ return this;
+ }
- @Override
- public boolean validate(final java.lang.String value) {
- final File file = new File(value);
+ @Override
+ public boolean validate(final java.lang.String value) {
+ final File file = new File(value);
- if (existanceType == ExistanceType.MUST_EXIST) {
- if (file.exists() && file.isFile())
- return true;
- return false;
- }
+ if (existenceType == ExistenceType.MUST_EXIST) {
+ return file.exists() && file.isFile();
+ }
- if (existanceType == ExistanceType.MUST_NOT_EXIST) {
- if (file.exists())
- return false;
- return true;
- }
+ if (existenceType == ExistenceType.MUST_NOT_EXIST) {
+ return !file.exists();
+ }
- if (existanceType == ExistanceType.DOES_NOT_MATTER) {
- if (file.exists())
- if (file.isDirectory())
- return false;
+ if (existenceType == ExistenceType.DOES_NOT_MATTER) {
+ if (file.exists())
+ if (file.isDirectory())
+ return false;
- return true;
- }
+ return true;
+ }
- return false;
- }
+ return false;
+ }
}
public class IntegerParameter extends Parameter<IntegerParameter> {
- public IntegerParameter(final String description) {
- super(description, ArgumentCount.SINGLE);
- }
+ public IntegerParameter(final String description) {
+ super(description, ArgumentCount.SINGLE);
+ }
- @Override
- public java.lang.String describeFormat() {
- return "integer";
- }
+ @Override
+ public java.lang.String describeFormat() {
+ return "integer";
+ }
- @Override
- public Integer getValue() {
- if (arguments.size() != 1)
- throw new RuntimeException("Parameter " + description
- + " shall have exactly 1 argument.");
- return Integer.parseInt(arguments.get(0));
- }
+ @Override
+ public Integer getValue() {
+ if (arguments.size() != 1)
+ throw new RuntimeException("Parameter " + description
+ + " shall have exactly 1 argument.");
+ return Integer.parseInt(arguments.get(0));
+ }
- @Override
- public boolean validate(final java.lang.String value) {
- try {
- java.lang.Integer.valueOf(value);
- return true;
- } catch (final NumberFormatException e) {
- return false;
- }
- }
+ @Override
+ public boolean validate(final java.lang.String value) {
+ try {
+ java.lang.Integer.valueOf(value);
+ return true;
+ } catch (final NumberFormatException e) {
+ return false;
+ }
+ }
}
public class NullParameter extends Parameter<NullParameter> {
- public NullParameter(final String description) {
- super(description, ArgumentCount.NONE);
- }
-
- @Override
- public java.lang.String describeFormat() {
- return "<none>";
- }
-
- @Override
- public Boolean getValue() {
- return isParameterSpecified();
- }
-
- @Override
- public boolean validate(final java.lang.String value) {
- return true;
- }
+ public NullParameter(final String description) {
+ super(description, ArgumentCount.NONE);
+ }
+
+ @Override
+ public java.lang.String describeFormat() {
+ return "<none>";
+ }
+
+ @Override
+ public Boolean getValue() {
+ return isParameterSpecified();
+ }
+
+ @Override
+ public boolean validate(final java.lang.String value) {
+ return true;
+ }
}
public class StringParameter extends Parameter<StringParameter> {
- public StringParameter(final String description) {
- super(description, ArgumentCount.SINGLE);
- }
+ public StringParameter(final String description) {
+ super(description, ArgumentCount.SINGLE);
+ }
- @Override
- public java.lang.String describeFormat() {
- return "string";
- }
+ @Override
+ public java.lang.String describeFormat() {
+ return "string";
+ }
- @Override
- public String getValue() {
+ @Override
+ public String getValue() {
- if (arguments.size() != 1)
- throw new RuntimeException("Parameter " + description
- + " shall have exactly 1 argument.");
+ if (arguments.size() != 1)
+ throw new RuntimeException("Parameter " + description
+ + " shall have exactly 1 argument.");
- return arguments.get(0);
- }
+ return arguments.get(0);
+ }
- @Override
- public boolean validate(final java.lang.String value) {
- return true;
- }
+ @Override
+ public boolean validate(final java.lang.String value) {
+ return true;
+ }
}
package eu.svjatoslav.commons.commandline.parameterparser.parameter;
-import java.util.List;
-
import eu.svjatoslav.commons.commandline.parameterparser.ArgumentCount;
import eu.svjatoslav.commons.commandline.parameterparser.Parameter;
+import java.util.List;
+
public class StringParameters extends Parameter<StringParameters> {
- public StringParameters(final String description) {
- super(description, ArgumentCount.MULTI);
- }
+ public StringParameters(final String description) {
+ super(description, ArgumentCount.MULTI);
+ }
- @Override
- public java.lang.String describeFormat() {
- return "one to many strings";
- }
+ @Override
+ public java.lang.String describeFormat() {
+ return "one to many strings";
+ }
- @Override
- public List<String> getValue() {
- return arguments;
- }
+ @Override
+ public List<String> getValue() {
+ return arguments;
+ }
- @Override
- public boolean validate(final java.lang.String value) {
- return true;
- }
+ @Override
+ public boolean validate(final java.lang.String value) {
+ return true;
+ }
}
public class BitInputStream {
- int currentByte;
- int currentBytePointer = -1;
+ private final InputStream inputStream;
+ private int currentByte;
+ private int currentBytePointer = -1;
- InputStream inputStream;
+ public BitInputStream(final InputStream inputStream) {
+ this.inputStream = inputStream;
+ }
- public BitInputStream(final InputStream inputStream) {
- this.inputStream = inputStream;
- }
+ public int readBits(final int bitCount) throws IOException {
- public int readBits(final int bitCount) throws IOException {
+ int readableByte = 0;
+ for (int i = 0; i < bitCount; i++) {
- int readableByte = 0;
- for (int i = 0; i < bitCount; i++) {
+ readableByte = readableByte << 1;
- readableByte = readableByte << 1;
+ if (currentBytePointer == -1) {
+ currentBytePointer = 7;
+ currentByte = inputStream.read();
+ }
- if (currentBytePointer == -1) {
- currentBytePointer = 7;
- currentByte = inputStream.read();
- }
+ int mask = 1;
+ mask = mask << currentBytePointer;
- int mask = 1;
- mask = mask << currentBytePointer;
+ final int currentBit = currentByte & mask;
- final int currentBit = currentByte & mask;
+ if (currentBit != 0)
+ readableByte = readableByte | 1;
- if (currentBit != 0)
- readableByte = readableByte | 1;
-
- currentBytePointer--;
- }
- return readableByte;
- }
+ currentBytePointer--;
+ }
+ return readableByte;
+ }
}
public class BitOutputStream {
- int currentByte;
- int currentBytePointer;
-
- OutputStream outputStream;
-
- public BitOutputStream(final OutputStream outputStream) {
- currentByte = 0;
- currentBytePointer = 0;
- this.outputStream = outputStream;
- };
-
- public void finishByte() throws IOException {
- if (currentBytePointer != 0) {
- outputStream.write(currentByte);
- currentBytePointer = 0;
- }
- }
-
- public void storeBits(final int data, final int bitCount)
- throws IOException {
- for (int i = bitCount - 1; i >= 0; i--) {
-
- int mask = 1;
- mask = mask << i;
-
- final int currentBit = data & mask;
- currentByte = currentByte << 1;
-
- if (currentBit != 0)
- currentByte = currentByte | 1;
- currentBytePointer++;
-
- if (currentBytePointer == 8) {
- currentBytePointer = 0;
- outputStream.write(currentByte);
- currentByte = 0;
- }
- }
- }
+ private final OutputStream outputStream;
+ private int currentByte;
+ private int currentBytePointer;
+
+ public BitOutputStream(final OutputStream outputStream) {
+ currentByte = 0;
+ currentBytePointer = 0;
+ this.outputStream = outputStream;
+ }
+
+ public void finishByte() throws IOException {
+ if (currentBytePointer != 0) {
+ outputStream.write(currentByte);
+ currentBytePointer = 0;
+ }
+ }
+
+ public void storeBits(final int data, final int bitCount)
+ throws IOException {
+ for (int i = bitCount - 1; i >= 0; i--) {
+
+ int mask = 1;
+ mask = mask << i;
+
+ final int currentBit = data & mask;
+ currentByte = currentByte << 1;
+
+ if (currentBit != 0)
+ currentByte = currentByte | 1;
+ currentBytePointer++;
+
+ if (currentBytePointer == 8) {
+ currentBytePointer = 0;
+ outputStream.write(currentByte);
+ currentByte = 0;
+ }
+ }
+ }
}
public class EnhancedDataInputStream extends DataInputStream {
- public EnhancedDataInputStream(final InputStream in) {
- super(in);
- }
+ public EnhancedDataInputStream(final InputStream in) {
+ super(in);
+ }
- public List<Integer> readIntegerList() throws IOException {
- final int length = readInt();
+ public List<Integer> readIntegerList() throws IOException {
+ final int length = readInt();
- final List<Integer> result = new ArrayList<Integer>();
+ final List<Integer> result = new ArrayList<>();
- for (int i = 0; i < length; i++)
- result.add(readInt());
+ for (int i = 0; i < length; i++)
+ result.add(readInt());
- return result;
- }
+ return result;
+ }
- public String readString() throws IOException {
+ public String readString() throws IOException {
- final int length = readInt();
- if (length == -1)
- return null;
+ final int length = readInt();
+ if (length == -1)
+ return null;
- final byte[] bytes = new byte[length];
- readFully(bytes);
+ final byte[] bytes = new byte[length];
+ readFully(bytes);
- return new String(bytes, "UTF-8");
- }
+ return new String(bytes, "UTF-8");
+ }
}
public class EnhancedDataOutputStream extends DataOutputStream {
- public EnhancedDataOutputStream(final OutputStream out) {
- super(out);
- }
+ public EnhancedDataOutputStream(final OutputStream out) {
+ super(out);
+ }
- public void writeIntegerList(final List<Integer> list) throws IOException {
- writeInt(list.size());
+ public void writeIntegerList(final List<Integer> list) throws IOException {
+ writeInt(list.size());
- for (final Integer integer : list)
- writeInt(integer);
- }
+ for (final Integer integer : list)
+ writeInt(integer);
+ }
- public void writeString(final String string) throws IOException {
- if (string == null) {
- writeInt(-1);
- return;
- }
+ public void writeString(final String string) throws IOException {
+ if (string == null) {
+ writeInt(-1);
+ return;
+ }
- final byte[] bytes = string.getBytes("UTF-8");
+ final byte[] bytes = string.getBytes("UTF-8");
- writeInt(bytes.length);
- write(bytes);
- }
+ writeInt(bytes.length);
+ write(bytes);
+ }
}
public class HexConverter {
- static final String hexCharacters = "0123456789ABCDEF";
+ static final String hexCharacters = "0123456789ABCDEF";
- public static String byteArrayToHex(final byte[] bytes) {
+ public static String byteArrayToHex(final byte[] bytes) {
- if (bytes == null)
- return null;
+ if (bytes == null)
+ return null;
- final StringBuilder result = new StringBuilder(2 * bytes.length);
+ final StringBuilder result = new StringBuilder(2 * bytes.length);
- for (final byte b : bytes)
- result.append(hexCharacters.charAt((b & 0xF0) >> 4)).append(
- hexCharacters.charAt((b & 0x0F)));
+ for (final byte b : bytes)
+ result.append(hexCharacters.charAt((b & 0xF0) >> 4)).append(
+ hexCharacters.charAt((b & 0x0F)));
- return result.toString();
- }
+ return result.toString();
+ }
}
public class CommonPathResolver {
- public static File desktopFile;
-
- static final String[] desktopNames = new String[] { "Tafelblad", "المكتب",
- "Masa Üstü", "Сталец", "Десктоп", "ডেস্কটপ", "Desktop",
- "Escriptori", "Prostředí pracovní plochy", "Penbwrdd",
- "Skrivebord", "Επιφάνεια εργασίας", "Escritorio", "Töölaud",
- "Mahaigaina", "Työpöytä", "Bureau", "Deasc", "ડૅસ્કટોપ",
- "डेस्कटॉप", "Radna površina", "Munkaasztal", "デスクトップ", "დესკტოპი",
- "데스크탑", "Darbastalis", "Дэлгэц", "Skrivebord", "Teseke", "ਵਿਹੜਾ",
- "Pulpit", "Ambiente de Trabalho", "Área de Trabalho",
- "Рабочий стол", "Pracovná plocha", "Hapësira e Punës",
- "Радна површ", "Radna površ", "Skrivbord", "கணிமேசை", "Мизи корӣ",
- "พื้นโต๊ะ", "Masaüstü", "Стільниця", "桌面", "Isiga-nyezi" };
-
- /**
- * This method tries to guess user desktop directory. Implementation is
- * pretty lousy. Need to improve it some day.
- *
- * @return file that points to user desktop directory.
- * @throws RuntimeException
- * if user desktop directory is not found.
- */
- public static File getDesktopDirectory() {
-
- if (desktopFile != null)
- return desktopFile;
-
- final String userHomePath = System.getProperty("user.home");
-
- for (final String desktopName : desktopNames) {
-
- final String desktopPath = userHomePath + "/" + desktopName;
-
- final File possibleDesktopFile = new File(desktopPath);
- if (possibleDesktopFile.exists()) {
- desktopFile = possibleDesktopFile;
- return desktopFile;
- }
- }
-
- throw new RuntimeException("Cannot autodetect user desktop directory.");
- }
-
- public static File getHomeDirectory() {
- return new File(System.getProperty("user.home"));
- }
+ private static final String[] desktopNames = new String[]{"Tafelblad", "المكتب",
+ "Masa Üstü", "Сталец", "Десктоп", "ডেস্কটপ", "Desktop",
+ "Escriptori", "Prostředí pracovní plochy", "Penbwrdd",
+ "Skrivebord", "Επιφάνεια εργασίας", "Escritorio", "Töölaud",
+ "Mahaigaina", "Työpöytä", "Bureau", "Deasc", "ડૅસ્કટોપ",
+ "डेस्कटॉप", "Radna površina", "Munkaasztal", "デスクトップ", "დესკტოპი",
+ "데스크탑", "Darbastalis", "Дэлгэц", "Skrivebord", "Teseke", "ਵਿਹੜਾ",
+ "Pulpit", "Ambiente de Trabalho", "Área de Trabalho",
+ "Рабочий стол", "Pracovná plocha", "Hapësira e Punës",
+ "Радна површ", "Radna površ", "Skrivbord", "கணிமேசை", "Мизи корӣ",
+ "พื้นโต๊ะ", "Masaüstü", "Стільниця", "桌面", "Isiga-nyezi"};
+
+ private static File desktopFile;
+
+ /**
+ * This method tries to guess user desktop directory. Implementation is
+ * pretty lousy. Need to improve it some day.
+ *
+ * @return file that points to user desktop directory.
+ * @throws RuntimeException if user desktop directory is not found.
+ */
+ public static File getDesktopDirectory() {
+
+ if (desktopFile != null)
+ return desktopFile;
+
+ final String userHomePath = System.getProperty("user.home");
+
+ for (final String desktopName : desktopNames) {
+
+ final String desktopPath = userHomePath + "/" + desktopName;
+
+ final File possibleDesktopFile = new File(desktopPath);
+ if (possibleDesktopFile.exists()) {
+ desktopFile = possibleDesktopFile;
+ return desktopFile;
+ }
+ }
+
+ throw new RuntimeException("Cannot autodetect user desktop directory.");
+ }
+
+ public static File getHomeDirectory() {
+ return new File(System.getProperty("user.home"));
+ }
}
public class FilePathParser {
- public static String getFileExtension(final File file) {
- final String fullFileName = file.getName();
+ public static String getFileExtension(final File file) {
+ final String fullFileName = file.getName();
- return getFileExtension(fullFileName);
- }
+ return getFileExtension(fullFileName);
+ }
- public static String getFileExtension(final String fullFileName) {
- final int dot = fullFileName.lastIndexOf('.');
- String fileExtension;
- if (dot == -1)
- fileExtension = "";
- else {
- fileExtension = fullFileName.substring(dot + 1);
- fileExtension = fileExtension.toLowerCase();
- }
+ public static String getFileExtension(final String fullFileName) {
+ final int dot = fullFileName.lastIndexOf('.');
+ String fileExtension;
+ if (dot == -1)
+ fileExtension = "";
+ else {
+ fileExtension = fullFileName.substring(dot + 1);
+ fileExtension = fileExtension.toLowerCase();
+ }
- return fileExtension;
- }
+ return fileExtension;
+ }
- public static String getFileNameWithoutExtension(final File file) {
- final String fullFileName = file.getName();
- return getFileNameWithoutExtension(fullFileName);
- }
+ public static String getFileNameWithoutExtension(final File file) {
+ final String fullFileName = file.getName();
+ return getFileNameWithoutExtension(fullFileName);
+ }
- public static String getFileNameWithoutExtension(final String fullFileName) {
- final int dot = fullFileName.lastIndexOf('.');
- String fileName;
- if (dot == -1)
- fileName = fullFileName;
- else
- fileName = fullFileName.substring(0, dot);
+ public static String getFileNameWithoutExtension(final String fullFileName) {
+ final int dot = fullFileName.lastIndexOf('.');
+ String fileName;
+ if (dot == -1)
+ fileName = fullFileName;
+ else
+ fileName = fullFileName.substring(0, dot);
- return fileName;
- }
+ return fileName;
+ }
- public static String getFileSizeDescription(long fileSize) {
- String suffix = "b";
+ public static String getFileSizeDescription(long fileSize) {
+ String suffix = "b";
- if (fileSize > (1024 * 1024 * 10)) {
- fileSize = fileSize / (1024 * 1024);
- suffix = "Mb";
- } else if (fileSize > (1024 * 10)) {
- fileSize = fileSize / 1024;
- suffix = "Kb";
- }
+ if (fileSize > (1024 * 1024 * 10)) {
+ fileSize = fileSize / (1024 * 1024);
+ suffix = "MiB";
+ } else if (fileSize > (1024 * 10)) {
+ fileSize = fileSize / 1024;
+ suffix = "KiB";
+ }
- final String fileSizeString = String.valueOf(fileSize) + " " + suffix;
-
- return fileSizeString;
- }
+ return String.valueOf(fileSize) + " " + suffix;
+ }
}
package eu.svjatoslav.commons.file;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
+import java.io.*;
public class IOHelper {
- /**
- * Deletes files and directories recursively. WARNING!!! Follows symlinks!!!
- *
- * @param file
- * directory to delete with entire contents.
- *
- * @throws IOException
- * if filesystem error happens
- */
- public static void deleteRecursively(final File file) throws IOException {
- if (file.isDirectory()) {
-
- for (final File subFile : file.listFiles())
- deleteRecursively(subFile);
-
- if (!file.delete())
- throw new FileNotFoundException("Failed to delete directory: "
- + file);
-
- return;
- }
-
- if (file.isFile())
- if (!file.delete())
- throw new FileNotFoundException("Failed to delete file: "
- + file);
- }
-
- public static byte[] getFileContents(final File file)
- throws FileNotFoundException, IOException {
-
- final byte[] result = new byte[(int) file.length()];
- final FileInputStream fileInputStream = new FileInputStream(file);
- fileInputStream.read(result);
- fileInputStream.close();
- return result;
- }
-
- public static String getFileContentsAsString(final File file)
- throws FileNotFoundException, IOException {
- try {
- return new String(getFileContents(file), "UTF-8");
- } catch (final UnsupportedEncodingException exception) {
- throw new RuntimeException(exception);
- }
- }
-
- /**
- * Compares new file content with old file content. If content in equal,
- * then leaves file as-is. If content differs, then overrides file with the
- * new content.
- *
- * @param file
- * file to potentially overwrite
- * @param newContent
- * new content
- * @return <code>true</code> if file was overwritten.
- *
- * @throws FileNotFoundException
- * if file is not found.
- * @throws IOException
- * if error happens during file IO.
- */
- public static boolean overwriteFileIfContentDiffers(final File file,
- final byte[] newContent) throws FileNotFoundException, IOException {
-
- checkForEquality: {
- if (file.length() == newContent.length) {
-
- final byte[] oldContent = getFileContents(file);
-
- for (int i = 0; i < newContent.length; i++)
- if (newContent[i] != oldContent[i])
- break checkForEquality;
-
- // new file content in identical to old content
- return false;
- }
- }
-
- // New content differs from existing. Overwrite file.
- saveToFile(file, newContent);
- return true;
- }
-
- public static void saveToFile(final File file, final byte[] content)
- throws IOException {
- final FileOutputStream fos = new FileOutputStream(file);
- fos.write(content);
- fos.close();
- }
+ /**
+ * Deletes files and directories recursively. WARNING!!! Follows symlinks!!!
+ *
+ * @param file directory to delete with entire contents.
+ * @throws IOException if filesystem error happens
+ */
+ public static void deleteRecursively(final File file) throws IOException {
+ if (file.isDirectory()) {
+
+ File[] files = file.listFiles();
+ if (files == null)
+ throw new RuntimeException("Failed to read directory content for: "
+ + file);
+
+ for (final File subFile : files)
+ deleteRecursively(subFile);
+
+ if (!file.delete())
+ throw new RuntimeException("Failed to delete directory: "
+ + file);
+
+ return;
+ }
+
+ if (file.isFile())
+ if (!file.delete())
+ throw new FileNotFoundException("Failed to delete file: "
+ + file);
+ }
+
+ public static byte[] getFileContents(final File file)
+ throws IOException {
+
+ final byte[] result = new byte[(int) file.length()];
+ try (final FileInputStream fileInputStream = new FileInputStream(file)) {
+ if (fileInputStream.read(result) != result.length)
+ throw new RuntimeException("Could not read file content:" + file);
+ }
+ return result;
+ }
+
+ public static String getFileContentsAsString(final File file)
+ throws IOException {
+ try {
+ return new String(getFileContents(file), "UTF-8");
+ } catch (final UnsupportedEncodingException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ /**
+ * Compares new file content with old file content. If content in equal,
+ * then leaves file as-is. If content differs, then overrides file with the
+ * new content.
+ *
+ * @param file file to potentially overwrite
+ * @param newContent new content
+ * @return <code>true</code> if file was overwritten.
+ * @throws FileNotFoundException if file is not found.
+ * @throws IOException if error happens during file IO.
+ */
+ public static boolean overwriteFileIfContentDiffers(final File file,
+ final byte[] newContent) throws IOException {
+
+ checkForEquality:
+ {
+ if (file.length() == newContent.length) {
+
+ final byte[] oldContent = getFileContents(file);
+
+ for (int i = 0; i < newContent.length; i++)
+ if (newContent[i] != oldContent[i])
+ break checkForEquality;
+
+ // new file content in identical to old content
+ return false;
+ }
+ }
+
+ // New content differs from existing. Overwrite file.
+ saveToFile(file, newContent);
+ return true;
+ }
+
+ public static void saveToFile(final File file, final byte[] content)
+ throws IOException {
+ try (final FileOutputStream fos = new FileOutputStream(file)) {
+ fos.write(content);
+ }
+ }
}
package eu.svjatoslav.commons.gui.dialog;
-import java.awt.BorderLayout;
-import java.awt.TextArea;
-
-import javax.swing.BoxLayout;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
+import javax.swing.*;
+import java.awt.*;
public class ExceptionDialog {
- /**
- * This method is for testing
- *
- * @param args
- * commandline arguments
- */
- public static void main(final String[] args) {
-
- final Throwable cause = new Throwable("details.....");
-
- final Exception exception = new Exception("test", cause);
-
- new ExceptionDialog(exception);
- }
-
- public ExceptionDialog(final Exception exception) {
- showException(exception);
- }
-
- /**
- * @param exception
- * exception to show
- */
- public void showException(final Exception exception) {
-
- final JFrame frame = new JFrame("Exception occured!");
- final JPanel contentPanel = new JPanel(new BorderLayout());
- final Throwable cause = exception.getCause();
-
- // build top panel
- {
- final JPanel topPanel = new JPanel();
- topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
-
- // add exception type
- final JLabel exceptionType = new JLabel("Exception type: "
- + exception.getClass().getCanonicalName());
- topPanel.add(exceptionType);
-
- // add error message
- final JLabel message = new JLabel("Error message: "
- + exception.getMessage());
- topPanel.add(message);
-
- // add cause message
- if (cause != null)
- if (cause.getMessage() != null) {
- final JLabel message2 = new JLabel("Cause: "
- + cause.getMessage());
- topPanel.add(message2);
- }
-
- contentPanel.add(topPanel, BorderLayout.NORTH);
- }
-
- // build stack trace view
- {
- final StringBuffer buffer = new StringBuffer();
-
- // if cause is available, show original stack trace
- if (cause != null) {
- buffer.append("Stack trace:\n");
- final StackTraceElement[] stackTrace = cause.getStackTrace();
- for (final StackTraceElement stackTraceElement : stackTrace)
- buffer.append(stackTraceElement.toString() + "\n");
- } else {
- // otherwise show at least current stack trace
- buffer.append("Stack trace from original cause is not available.\nShowing current stack trace instead:\n");
-
- for (final StackTraceElement stackTraceElement : new Exception(
- "Stack trace").getStackTrace())
- buffer.append(stackTraceElement.toString() + "\n");
- }
-
- final TextArea textArea = new TextArea(buffer.toString());
- contentPanel.add(textArea, BorderLayout.CENTER);
- }
-
- // finalize frame
- frame.getContentPane().add(contentPanel);
- frame.setSize(800, 600);
- frame.setVisible(true);
-
- // Thread.dumpStack();
-
- }
+ public ExceptionDialog(final Exception exception) {
+ showException(exception);
+ }
+
+ /**
+ * This method is for testing
+ *
+ * @param args commandline arguments
+ */
+ public static void main(final String[] args) {
+
+ final Throwable cause = new Throwable("details.....");
+
+ final Exception exception = new Exception("test", cause);
+
+ new ExceptionDialog(exception);
+ }
+
+ /**
+ * @param exception exception to show
+ */
+ public void showException(final Exception exception) {
+
+ final JFrame frame = new JFrame("Exception occurred!");
+ final JPanel contentPanel = new JPanel(new BorderLayout());
+ final Throwable cause = exception.getCause();
+
+ // build top panel
+ {
+ final JPanel topPanel = new JPanel();
+ topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
+
+ // add exception type
+ final JLabel exceptionType = new JLabel("Exception type: "
+ + exception.getClass().getCanonicalName());
+ topPanel.add(exceptionType);
+
+ // add error message
+ final JLabel message = new JLabel("Error message: "
+ + exception.getMessage());
+ topPanel.add(message);
+
+ // add cause message
+ if (cause != null)
+ if (cause.getMessage() != null) {
+ final JLabel message2 = new JLabel("Cause: "
+ + cause.getMessage());
+ topPanel.add(message2);
+ }
+
+ contentPanel.add(topPanel, BorderLayout.NORTH);
+ }
+
+ // build stack trace view
+ {
+ final StringBuilder buffer = new StringBuilder();
+
+ // if cause is available, show original stack trace
+ if (cause != null) {
+ buffer.append("Stack trace:\n");
+ final StackTraceElement[] stackTrace = cause.getStackTrace();
+ for (final StackTraceElement stackTraceElement : stackTrace)
+ buffer.append(stackTraceElement.toString() + "\n");
+ } else {
+ // otherwise show at least current stack trace
+ buffer.append("Stack trace from original cause is not available.\nShowing current stack trace instead:\n");
+
+ for (final StackTraceElement stackTraceElement : new Exception(
+ "Stack trace").getStackTrace())
+ buffer.append(stackTraceElement.toString() + "\n");
+ }
+
+ final TextArea textArea = new TextArea(buffer.toString());
+ contentPanel.add(textArea, BorderLayout.CENTER);
+ }
+
+ // finalize frame
+ frame.getContentPane().add(contentPanel);
+ frame.setSize(800, 600);
+ frame.setVisible(true);
+
+ // Thread.dumpStack();
+
+ }
}
package eu.svjatoslav.commons.network;
+import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
-import javax.servlet.http.HttpServletRequest;
-
public class LocaleConfiguration {
- String defaultLocale;
-
- private final List<String> allowedLocales = new ArrayList<String>();
+ final String defaultLocale;
+ private final List<String> allowedLocales = new ArrayList<>();
- public LocaleConfiguration(final String defaultLocale,
- final String... allowedLocales) {
+ public LocaleConfiguration(final String defaultLocale,
+ final String... allowedLocales) {
- this.defaultLocale = defaultLocale;
+ this.defaultLocale = defaultLocale;
- for (final String locale : allowedLocales)
- getAllowedLocales().add(locale);
- }
+ for (final String locale : allowedLocales)
+ getAllowedLocales().add(locale);
+ }
- public String detectCurrentLocale(final HttpServletRequest request) {
+ public String detectCurrentLocale(final HttpServletRequest request) {
- final String sessionLocaleString = (String) request.getSession()
- .getAttribute("locale");
+ final String sessionLocaleString = (String) request.getSession()
+ .getAttribute("locale");
- String result = defaultLocale;
- if (isAllowedLocale(sessionLocaleString))
- result = sessionLocaleString;
+ String result = defaultLocale;
+ if (isAllowedLocale(sessionLocaleString))
+ result = sessionLocaleString;
- final String requestLocale = request.getParameter("locale");
+ final String requestLocale = request.getParameter("locale");
- if (isAllowedLocale(requestLocale))
- result = requestLocale;
+ if (isAllowedLocale(requestLocale))
+ result = requestLocale;
- request.getSession().setAttribute("locale", result);
+ request.getSession().setAttribute("locale", result);
- return result;
- }
+ return result;
+ }
- public List<String> getAllowedLocales() {
- return allowedLocales;
- }
+ public List<String> getAllowedLocales() {
+ return allowedLocales;
+ }
- public boolean isAllowedLocale(final String locale) {
- return allowedLocales.contains(locale);
- }
+ public boolean isAllowedLocale(final String locale) {
+ return allowedLocales.contains(locale);
+ }
}
package eu.svjatoslav.commons.network.navigation;
+import eu.svjatoslav.commons.network.LocaleConfiguration;
+
+import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
-import javax.servlet.http.HttpServletRequest;
-
-import eu.svjatoslav.commons.network.LocaleConfiguration;
-
public class Navigation<NI extends NavigationItem> {
- private NI rootNavigationItem;
-
- private NI defaultNavigationItem;
-
- protected final LocaleConfiguration localeConfiguration;
+ protected final LocaleConfiguration localeConfiguration;
+ private NI rootNavigationItem;
+ private NI defaultNavigationItem;
- public Navigation(final LocaleConfiguration localeConfiguration) {
- this.localeConfiguration = localeConfiguration;
- }
+ public Navigation(final LocaleConfiguration localeConfiguration) {
+ this.localeConfiguration = localeConfiguration;
+ }
- public NI getDefaultNavigationItem() {
- return defaultNavigationItem;
- }
+ public NI getDefaultNavigationItem() {
+ return defaultNavigationItem;
+ }
- private String getGetNotNullString(final String string) {
- if (string != null)
- return string;
+ private String getGetNotNullString(final String string) {
+ if (string != null)
+ return string;
- return "";
- }
+ return "";
+ }
- public LocaleConfiguration getLocaleConfiguration() {
- return localeConfiguration;
- }
+ public LocaleConfiguration getLocaleConfiguration() {
+ return localeConfiguration;
+ }
- public NI getRootNavigationItem() {
- return rootNavigationItem;
- }
+ public NI getRootNavigationItem() {
+ return rootNavigationItem;
+ }
- public NI getSelectedItem(final HttpServletRequest request) {
- final String requestUrl = request.getRequestURL().toString();
+ public NI getSelectedItem(final HttpServletRequest request) {
+ final String requestUrl = request.getRequestURL().toString();
- try {
- final String requestPath = new URL(requestUrl).getPath();
+ try {
+ final String requestPath = new URL(requestUrl).getPath();
- @SuppressWarnings("unchecked")
- final NI match = (NI) rootNavigationItem.getMatchingNavigationItem(requestPath);
+ @SuppressWarnings("unchecked")
+ final NI match = (NI) rootNavigationItem.getMatchingNavigationItem(requestPath);
- if (match != null)
- return match;
- } catch (final MalformedURLException e) {
- System.out.println("Cannot handle URL: " + requestUrl);
- e.printStackTrace();
- }
+ if (match != null)
+ return match;
+ } catch (final MalformedURLException e) {
+ System.out.println("Cannot handle URL: " + requestUrl);
+ e.printStackTrace();
+ }
- return getDefaultNavigationItem();
- }
+ return getDefaultNavigationItem();
+ }
- @SuppressWarnings("unchecked")
- public String getTopMenu(final HttpServletRequest request) {
+ @SuppressWarnings("unchecked")
+ public String getTopMenu(final HttpServletRequest request) {
- final String currentLocale = localeConfiguration.detectCurrentLocale(request);
+ final String currentLocale = localeConfiguration.detectCurrentLocale(request);
- final NI selectedItem = getSelectedItem(request);
- final StringBuffer result = new StringBuffer();
+ final NI selectedItem = getSelectedItem(request);
+ final StringBuilder result = new StringBuilder();
- result.append("<div class=\"" + getGetNotNullString(rootNavigationItem.getCssPrefix()) + "navigationMenu\">");
+ result.append("<div class=\"" + getGetNotNullString(rootNavigationItem.getCssPrefix()) + "navigationMenu\">");
- for (final NI item : (List<NI>) getRootNavigationItem().getSubElements()) {
+ for (final NI item : (List<NI>) getRootNavigationItem().getSubElements()) {
- if (item == selectedItem)
- result.append("<a class=\"" + getGetNotNullString(item.getCssPrefix()) + "menuItemSelected\" href=\""
- + item.getLinkUrl() + "\">");
- else
- result.append("<a class=\"" + getGetNotNullString(item.getCssPrefix()) + "menuItem\" href=\""
- + item.getLinkUrl() + "\">");
+ if (item == selectedItem)
+ result.append("<a class=\"" + getGetNotNullString(item.getCssPrefix()) + "menuItemSelected\" href=\""
+ + item.getLinkUrl() + "\">");
+ else
+ result.append("<a class=\"" + getGetNotNullString(item.getCssPrefix()) + "menuItem\" href=\""
+ + item.getLinkUrl() + "\">");
- result.append("<div>" + item.getTitle(currentLocale) + "</div>");
- result.append("</a>");
- }
+ result.append("<div>" + item.getTitle(currentLocale) + "</div>");
+ result.append("</a>");
+ }
- result.append("</div>");
+ result.append("</div>");
- return result.toString();
- }
+ return result.toString();
+ }
- public NI setDefaultNavigationItem(final NI defaultNavigationItem) {
- this.defaultNavigationItem = defaultNavigationItem;
- return defaultNavigationItem;
- }
+ public NI setDefaultNavigationItem(final NI defaultNavigationItem) {
+ this.defaultNavigationItem = defaultNavigationItem;
+ return defaultNavigationItem;
+ }
- public NI setRootNavigationItem(final NI rootNavigationItem) {
- this.rootNavigationItem = rootNavigationItem;
- return rootNavigationItem;
- }
+ public NI setRootNavigationItem(final NI rootNavigationItem) {
+ this.rootNavigationItem = rootNavigationItem;
+ return rootNavigationItem;
+ }
}
package eu.svjatoslav.commons.network.navigation;
+import eu.svjatoslav.commons.string.WildCardMatcher;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import eu.svjatoslav.commons.string.WildCardMatcher;
-
public class NavigationItem {
- private String matchingPattern;
-
- private final Map<String, String> localeToTitle = new HashMap<String, String>();
- private final ArrayList<NavigationItem> subElements = new ArrayList<NavigationItem>();
- private final NavigationItem parent;
- private final Navigation<? extends NavigationItem> navigation;
- private final String linkUrl;
- /**
- * CSS prefix is inherited to child menu items.
- */
- private String cssPrefix;
-
- /**
- * Used to build root navigation item.
- */
- public NavigationItem(final Navigation<? extends NavigationItem> navigation) {
- this.navigation = navigation;
- parent = null;
- matchingPattern = null;
- linkUrl = null;
- }
-
- public NavigationItem(final NavigationItem parent, final String linkUrl, final String... titles) {
-
- navigation = parent.getNavigation();
- this.parent = parent;
- this.linkUrl = linkUrl;
- matchingPattern = linkUrl;
-
- initializeLocalizedTitles(titles);
-
- parent.addNavigationItem(this);
- }
-
- public void addNavigationItem(final NavigationItem navigationItem) {
- subElements.add(navigationItem);
- }
-
- protected String getCssPrefix() {
- if (cssPrefix != null)
- return cssPrefix;
-
- if (parent == null)
- return null;
-
- return parent.getCssPrefix();
- }
-
- public String getLinkUrl() {
- return linkUrl;
- }
-
- NavigationItem getMatchingNavigationItem(final String requestPath) {
- if (matchesUrl(requestPath))
- return this;
-
- for (final NavigationItem childNavigationItem : subElements) {
- final NavigationItem match = childNavigationItem.getMatchingNavigationItem(requestPath);
-
- if (match != null)
- return match;
- }
- return null;
- }
-
- public Navigation<? extends NavigationItem> getNavigation() {
- return navigation;
- }
-
- public List<NavigationItem> getSubElements() {
- return subElements;
- }
-
- public String getTitle(final String locale) {
- return localeToTitle.get(locale);
- }
-
- private void initializeLocalizedTitles(final String... titles) {
- final List<String> locales = getNavigation().getLocaleConfiguration().getAllowedLocales();
- if (locales.size() != titles.length)
- throw new RuntimeException("There should be exactly " + locales.size() + " title(s).");
-
- for (int i = 0; i < titles.length; i++)
- localeToTitle.put(locales.get(i), titles[i]);
- }
-
- public boolean matchesUrl(final String url) {
- return WildCardMatcher.match(url, matchingPattern);
- }
-
- public void setCssPrefix(final String cssPrefix) {
- this.cssPrefix = cssPrefix;
- }
-
- public NavigationItem setPattern(final String pattern) {
- matchingPattern = pattern;
- return this;
- }
-
- @Override
- public String toString() {
- return "NavigationItem [matchingPattern=" + matchingPattern + ", localeToTitle=" + localeToTitle
- + ", subElements count=" + subElements.size() + ", linkUrl=" + linkUrl + ", cssPrefix=" + cssPrefix
- + "]";
- }
+ private final Map<String, String> localeToTitle = new HashMap<>();
+ private final ArrayList<NavigationItem> subElements = new ArrayList<>();
+ private final NavigationItem parent;
+ private final Navigation<? extends NavigationItem> navigation;
+ private final String linkUrl;
+ private String matchingPattern;
+ /**
+ * CSS prefix is inherited to child menu items.
+ */
+ private String cssPrefix;
+
+ /**
+ * Used to build root navigation item.
+ */
+ public NavigationItem(final Navigation<? extends NavigationItem> navigation) {
+ this.navigation = navigation;
+ parent = null;
+ matchingPattern = null;
+ linkUrl = null;
+ }
+
+ public NavigationItem(final NavigationItem parent, final String linkUrl, final String... titles) {
+
+ navigation = parent.getNavigation();
+ this.parent = parent;
+ this.linkUrl = linkUrl;
+ matchingPattern = linkUrl;
+
+ initializeLocalizedTitles(titles);
+
+ parent.addNavigationItem(this);
+ }
+
+ public void addNavigationItem(final NavigationItem navigationItem) {
+ subElements.add(navigationItem);
+ }
+
+ protected String getCssPrefix() {
+ if (cssPrefix != null)
+ return cssPrefix;
+
+ if (parent == null)
+ return null;
+
+ return parent.getCssPrefix();
+ }
+
+ public void setCssPrefix(final String cssPrefix) {
+ this.cssPrefix = cssPrefix;
+ }
+
+ public String getLinkUrl() {
+ return linkUrl;
+ }
+
+ NavigationItem getMatchingNavigationItem(final String requestPath) {
+ if (matchesUrl(requestPath))
+ return this;
+
+ for (final NavigationItem childNavigationItem : subElements) {
+ final NavigationItem match = childNavigationItem.getMatchingNavigationItem(requestPath);
+
+ if (match != null)
+ return match;
+ }
+ return null;
+ }
+
+ public Navigation<? extends NavigationItem> getNavigation() {
+ return navigation;
+ }
+
+ public List<NavigationItem> getSubElements() {
+ return subElements;
+ }
+
+ public String getTitle(final String locale) {
+ return localeToTitle.get(locale);
+ }
+
+ private void initializeLocalizedTitles(final String... titles) {
+ final List<String> locales = getNavigation().getLocaleConfiguration().getAllowedLocales();
+ if (locales.size() != titles.length)
+ throw new RuntimeException("There should be exactly " + locales.size() + " title(s).");
+
+ for (int i = 0; i < titles.length; i++)
+ localeToTitle.put(locales.get(i), titles[i]);
+ }
+
+ public boolean matchesUrl(final String url) {
+ return WildCardMatcher.match(url, matchingPattern);
+ }
+
+ public NavigationItem setPattern(final String pattern) {
+ matchingPattern = pattern;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return "NavigationItem [matchingPattern=" + matchingPattern + ", localeToTitle=" + localeToTitle
+ + ", subElements count=" + subElements.size() + ", linkUrl=" + linkUrl + ", cssPrefix=" + cssPrefix
+ + "]";
+ }
}
public class String2 {
- private final Vector<Character> chars = new Vector<Character>();
-
- public String2(final String value) {
- for (final Character c : value.toCharArray())
- chars.add(c);
- }
-
- public String2 addPrefix(final String prefix) {
- int j = 0;
- for (final char c : prefix.toCharArray())
- chars.insertElementAt(c, j++);
-
- return this;
- }
-
- public String2 addSuffix(final String suffix) {
- for (final char c : suffix.toCharArray())
- chars.add(c);
-
- return this;
- }
-
- /**
- * Cut given amount of characters from the left of the string.
- *
- * @param cutAmount
- * of characters to cut
- * @return cutted part.
- */
- public String cutLeft(final int cutAmount) {
-
- int actualCutAmount = cutAmount;
-
- if (actualCutAmount > getLength())
- actualCutAmount = getLength();
-
- final String result = getSubString(0, actualCutAmount);
-
- chars.subList(0, actualCutAmount).clear();
-
- return result;
- }
-
- public String2 enforceLength(final int targetLength) {
- if (getLength() > targetLength)
- chars.subList(targetLength, getLength()).clear();
- else if (getLength() < targetLength) {
- final int charactersToAdd = targetLength - getLength();
- for (int i = 0; i < charactersToAdd; i++)
- chars.add(' ');
- }
-
- return this;
- }
-
- public int getLength() {
- return chars.size();
- }
-
- public String getSubString(final int startInclusive, final int endExclusive) {
- final char[] charArray = new char[endExclusive - startInclusive];
-
- int j = 0;
- for (int i = startInclusive; i < endExclusive; i++) {
- charArray[j] = chars.get(i);
- j++;
- }
- return new String(charArray);
- }
-
- public boolean isEmpty() {
- return chars.size() == 0;
- }
-
- @Override
- public String toString() {
- return getSubString(0, chars.size());
- }
+ private final Vector<Character> chars = new Vector<>();
+
+ public String2(final String value) {
+ for (final Character c : value.toCharArray())
+ chars.add(c);
+ }
+
+ public String2 addPrefix(final String prefix) {
+ int j = 0;
+ for (final char c : prefix.toCharArray())
+ chars.insertElementAt(c, j++);
+
+ return this;
+ }
+
+ public String2 addSuffix(final String suffix) {
+ for (final char c : suffix.toCharArray())
+ chars.add(c);
+
+ return this;
+ }
+
+ /**
+ * Cut given amount of characters from the left of the string.
+ *
+ * @param cutAmount of characters to cut
+ * @return part that was cut.
+ */
+ public String trimLeft(final int cutAmount) {
+
+ int actualCutAmount = cutAmount;
+
+ if (actualCutAmount > getLength())
+ actualCutAmount = getLength();
+
+ final String result = getSubString(0, actualCutAmount);
+
+ chars.subList(0, actualCutAmount).clear();
+
+ return result;
+ }
+
+ public String2 enforceLength(final int targetLength) {
+ if (getLength() > targetLength)
+ chars.subList(targetLength, getLength()).clear();
+ else if (getLength() < targetLength) {
+ final int charactersToAdd = targetLength - getLength();
+ for (int i = 0; i < charactersToAdd; i++)
+ chars.add(' ');
+ }
+
+ return this;
+ }
+
+ public int getLength() {
+ return chars.size();
+ }
+
+ public String getSubString(final int startInclusive, final int endExclusive) {
+ final char[] charArray = new char[endExclusive - startInclusive];
+
+ int j = 0;
+ for (int i = startInclusive; i < endExclusive; i++) {
+ charArray[j] = chars.get(i);
+ j++;
+ }
+ return new String(charArray);
+ }
+
+ public boolean isEmpty() {
+ return chars.size() == 0;
+ }
+
+ @Override
+ public String toString() {
+ return getSubString(0, chars.size());
+ }
}
public class WildCardMatcher {
- /**
- * Allow only for * in wildcards
- */
- private static boolean checkWildCardEnd(final String wildcardExpression,
- int wildCardPosition) {
- for (; wildCardPosition < wildcardExpression.length(); wildCardPosition++) {
- final char wildCardChar = wildcardExpression
- .charAt(wildCardPosition);
- if (wildCardChar != '*')
- return false;
- }
-
- return true;
- }
-
- /**
- * <pre>
- * Test input string against wildcard expression.
- * * -- corresponds to any amount of characters.
- * ? -- corresponds to any single character.
- * </pre>
- *
- * @param inputString
- * input string
- * @param wildcardExpression
- * wildcard expression
- * @return <code>true</code> if input string matches input pattern
- */
- public static boolean match(final String inputString,
- final String wildcardExpression) {
-
- if (inputString == null)
- return false;
-
- if (wildcardExpression == null)
- return false;
-
- int i;
-
- for (i = 0; i < inputString.length(); i++) {
- if (i >= wildcardExpression.length())
- return false;
- final char wildCardChar = wildcardExpression.charAt(i);
- if (wildCardChar == '*')
- return matchPiece(inputString, i, wildcardExpression, i + 1);
- if (wildCardChar != '?')
- if (inputString.charAt(i) != wildCardChar)
- return false;
- }
-
- return checkWildCardEnd(wildcardExpression, i);
- }
-
- private static boolean matchPiece(final String inputString,
- final int inputStringIndex, final String wildcardExpression,
- final int wildCardExpressionIndex) {
-
- int wildCardPosition = wildCardExpressionIndex;
-
- for (int i = inputStringIndex; i < inputString.length(); i++) {
-
- wildCardPosition = wildCardExpressionIndex;
-
- subMatchAttempt: {
-
- for (int j = i; j < inputString.length(); j++) {
- if (wildCardPosition >= wildcardExpression.length())
- break subMatchAttempt;
- final char wildCardChar = wildcardExpression
- .charAt(wildCardPosition);
-
- if (wildCardChar == '*')
- return matchPiece(inputString, j, wildcardExpression,
- wildCardPosition + 1);
-
- if (wildCardChar != '?')
- if (inputString.charAt(j) != wildCardChar)
- break subMatchAttempt;
-
- wildCardPosition++;
- }
-
- return checkWildCardEnd(wildcardExpression, wildCardPosition);
- }
-
- }
-
- return checkWildCardEnd(wildcardExpression, wildCardPosition);
- }
+ /**
+ * Allow only for * in wildcards
+ */
+ private static boolean checkWildCardEnd(final String wildcardExpression,
+ int wildCardPosition) {
+ for (; wildCardPosition < wildcardExpression.length(); wildCardPosition++) {
+ final char wildCardChar = wildcardExpression
+ .charAt(wildCardPosition);
+ if (wildCardChar != '*')
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * <pre>
+ * Test input string against wildcard expression.
+ * * -- corresponds to any amount of characters.
+ * ? -- corresponds to any single character.
+ * </pre>
+ *
+ * @param inputString input string
+ * @param wildcardExpression wildcard expression
+ * @return <code>true</code> if input string matches input pattern
+ */
+ public static boolean match(final String inputString,
+ final String wildcardExpression) {
+
+ if (inputString == null)
+ return false;
+
+ if (wildcardExpression == null)
+ return false;
+
+ int i;
+
+ for (i = 0; i < inputString.length(); i++) {
+ if (i >= wildcardExpression.length())
+ return false;
+ final char wildCardChar = wildcardExpression.charAt(i);
+ if (wildCardChar == '*')
+ return matchPiece(inputString, i, wildcardExpression, i + 1);
+ if (wildCardChar != '?')
+ if (inputString.charAt(i) != wildCardChar)
+ return false;
+ }
+
+ return checkWildCardEnd(wildcardExpression, i);
+ }
+
+ private static boolean matchPiece(final String inputString,
+ final int inputStringIndex, final String wildcardExpression,
+ final int wildCardExpressionIndex) {
+
+ int wildCardPosition = wildCardExpressionIndex;
+
+ for (int i = inputStringIndex; i < inputString.length(); i++) {
+
+ wildCardPosition = wildCardExpressionIndex;
+
+ subMatchAttempt:
+ {
+
+ for (int j = i; j < inputString.length(); j++) {
+ if (wildCardPosition >= wildcardExpression.length())
+ break subMatchAttempt;
+ final char wildCardChar = wildcardExpression
+ .charAt(wildCardPosition);
+
+ if (wildCardChar == '*')
+ return matchPiece(inputString, j, wildcardExpression,
+ wildCardPosition + 1);
+
+ if (wildCardChar != '?')
+ if (inputString.charAt(j) != wildCardChar)
+ break subMatchAttempt;
+
+ wildCardPosition++;
+ }
+
+ return checkWildCardEnd(wildcardExpression, wildCardPosition);
+ }
+
+ }
+
+ return checkWildCardEnd(wildcardExpression, wildCardPosition);
+ }
}
public class InvalidSyntaxException extends Exception {
- private static final long serialVersionUID = 88294980027680555L;
+ private static final long serialVersionUID = 88294980027680555L;
- public InvalidSyntaxException(final String cause) {
- super(cause);
- }
+ public InvalidSyntaxException(final String cause) {
+ super(cause);
+ }
}
public class Terminator {
- String startSequence;
- String endSequence;
- boolean ignoreTerminator;
+ final String startSequence;
+ final boolean ignoreTerminator;
+ String endSequence;
- public Terminator(final String startPattern, final boolean ignoreTerminator) {
- startSequence = startPattern;
- this.ignoreTerminator = ignoreTerminator;
- }
+ public Terminator(final String startPattern, final boolean ignoreTerminator) {
+ startSequence = startPattern;
+ this.ignoreTerminator = ignoreTerminator;
+ }
- public Terminator(final String startSequence, final String endSequence,
- final boolean ignoreTerminator) {
+ public Terminator(final String startSequence, final String endSequence,
+ final boolean ignoreTerminator) {
- this.startSequence = startSequence;
- this.endSequence = endSequence;
- this.ignoreTerminator = ignoreTerminator;
- }
+ this.startSequence = startSequence;
+ this.endSequence = endSequence;
+ this.ignoreTerminator = ignoreTerminator;
+ }
}
public class Tokenizer {
- private final List<Terminator> terminators = new ArrayList<Terminator>();
- private final String source;
-
- Stack<Integer> tokenIndexes = new Stack<Integer>();
-
- private int currentIndex = 0;
-
- public Tokenizer(final String source) {
- this.source = source;
- }
-
- public void addTerminator(final String startSequence,
- final boolean ignoreTerminator) {
- terminators.add(new Terminator(startSequence, ignoreTerminator));
- }
-
- public void addTerminator(final String startSequence,
- final String endSequence, final boolean ignoreTerminator) {
- terminators.add(new Terminator(startSequence, endSequence,
- ignoreTerminator));
- }
-
- public void expectNextToken(final String value)
- throws InvalidSyntaxException {
- final TokenizerMatch match = getNextToken();
- if (!value.equals(match.token))
- throw new InvalidSyntaxException("Expected \"" + value
- + "\" but got \"" + match.token + "\" instead.");
- }
-
- public TokenizerMatch getNextToken() {
- tokenIndexes.push(currentIndex);
- final StringBuffer result = new StringBuffer();
-
- while (true) {
- if (currentIndex >= source.length())
- return null;
-
- boolean accumulateCurrentChar = true;
-
- findTerminator: for (final Terminator terminator : terminators)
- if (sequenceMatches(terminator.startSequence))
-
- if (terminator.ignoreTerminator) {
- currentIndex += terminator.startSequence.length();
-
- if (terminator.endSequence != null)
- skipUntilSequence(terminator.endSequence);
-
- if (result.length() > 0)
- return new TokenizerMatch(result.toString(),
- terminator);
- else {
- accumulateCurrentChar = false;
- break findTerminator;
- }
- } else if (result.length() > 0)
- return new TokenizerMatch(result.toString(), terminator);
- else {
- currentIndex += terminator.startSequence.length();
- return new TokenizerMatch(terminator.startSequence,
- terminator);
- }
-
- if (accumulateCurrentChar) {
- result.append(source.charAt(currentIndex));
- currentIndex++;
- }
- }
-
- }
-
- public boolean probeNextToken(final String token) {
- if (token.equals(getNextToken().token))
- return true;
-
- unreadToken();
- return false;
- }
-
- public boolean sequenceMatches(final String sequence) {
- if ((currentIndex + sequence.length()) > source.length())
- return false;
-
- for (int i = 0; i < sequence.length(); i++)
- if (sequence.charAt(i) != source.charAt(i + currentIndex))
- return false;
-
- return true;
- }
-
- public void skipUntilDataEnd() {
- tokenIndexes.push(currentIndex);
- currentIndex = source.length();
- }
-
- public void skipUntilSequence(final String sequence) {
- while (currentIndex < source.length()) {
- if (sequenceMatches(sequence)) {
- currentIndex += sequence.length();
- return;
- }
-
- currentIndex++;
- }
- }
-
- public void unreadToken() {
- currentIndex = tokenIndexes.pop();
- }
+ final Stack<Integer> tokenIndexes = new Stack<>();
+ private final List<Terminator> terminators = new ArrayList<>();
+ private final String source;
+ private int currentIndex = 0;
+
+ public Tokenizer(final String source) {
+ this.source = source;
+ }
+
+ public void addTerminator(final String startSequence,
+ final boolean ignoreTerminator) {
+ terminators.add(new Terminator(startSequence, ignoreTerminator));
+ }
+
+ public void addTerminator(final String startSequence,
+ final String endSequence, final boolean ignoreTerminator) {
+ terminators.add(new Terminator(startSequence, endSequence,
+ ignoreTerminator));
+ }
+
+ public void expectNextToken(final String value)
+ throws InvalidSyntaxException {
+ final TokenizerMatch match = getNextToken();
+ if (!value.equals(match.token))
+ throw new InvalidSyntaxException("Expected \"" + value
+ + "\" but got \"" + match.token + "\" instead.");
+ }
+
+ public TokenizerMatch getNextToken() {
+ tokenIndexes.push(currentIndex);
+ final StringBuilder result = new StringBuilder();
+
+ while (true) {
+ if (currentIndex >= source.length())
+ return null;
+
+ boolean accumulateCurrentChar = true;
+
+ for (final Terminator terminator : terminators)
+ if (sequenceMatches(terminator.startSequence))
+
+ if (terminator.ignoreTerminator) {
+ currentIndex += terminator.startSequence.length();
+
+ if (terminator.endSequence != null)
+ skipUntilSequence(terminator.endSequence);
+
+ if (result.length() > 0)
+ return new TokenizerMatch(result.toString(),
+ terminator);
+ else {
+ accumulateCurrentChar = false;
+ break;
+ }
+ } else if (result.length() > 0)
+ return new TokenizerMatch(result.toString(), terminator);
+ else {
+ currentIndex += terminator.startSequence.length();
+ return new TokenizerMatch(terminator.startSequence,
+ terminator);
+ }
+
+ if (accumulateCurrentChar) {
+ result.append(source.charAt(currentIndex));
+ currentIndex++;
+ }
+ }
+
+ }
+
+ public boolean probeNextToken(final String token) {
+ if (token.equals(getNextToken().token))
+ return true;
+
+ unreadToken();
+ return false;
+ }
+
+ public boolean sequenceMatches(final String sequence) {
+ if ((currentIndex + sequence.length()) > source.length())
+ return false;
+
+ for (int i = 0; i < sequence.length(); i++)
+ if (sequence.charAt(i) != source.charAt(i + currentIndex))
+ return false;
+
+ return true;
+ }
+
+ public void skipUntilDataEnd() {
+ tokenIndexes.push(currentIndex);
+ currentIndex = source.length();
+ }
+
+ public void skipUntilSequence(final String sequence) {
+ while (currentIndex < source.length()) {
+ if (sequenceMatches(sequence)) {
+ currentIndex += sequence.length();
+ return;
+ }
+
+ currentIndex++;
+ }
+ }
+
+ public void unreadToken() {
+ currentIndex = tokenIndexes.pop();
+ }
}
public class TokenizerMatch {
- public String token;
- public Terminator terminator;
+ public final String token;
+ public final Terminator terminator;
- public TokenizerMatch(final String token, final Terminator terminator) {
- this.token = token;
- this.terminator = terminator;
- }
+ public TokenizerMatch(final String token, final Terminator terminator) {
+ this.token = token;
+ this.terminator = terminator;
+ }
}
package eu.svjatoslav.commons.commandline.parameterparser;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
+import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameter;
import org.junit.Before;
import org.junit.Test;
-import eu.svjatoslav.commons.commandline.parameterparser.parameter.StringParameter;
+import static org.junit.Assert.*;
public class ParserTest {
- Parser parser;
+ Parser parser;
- @Before
- public void setUp() throws Exception {
- parser = new Parser();
- }
+ @Before
+ public void setUp() throws Exception {
+ parser = new Parser();
+ }
- @Test
- public void testParse() {
+ @Test
+ public void testParse() {
- // define allowed parameters
- final StringParameter helpParameter = parser
- .add(new StringParameter("Show help screen"))
- .addAliases("--help", "-h").setMandatory();
+ // define allowed parameters
+ final StringParameter helpParameter = parser
+ .add(new StringParameter("Show help screen"))
+ .addAliases("--help", "-h").setMandatory();
- final StringParameter compileParameter = parser.add(
- new StringParameter("Compile code")).addAliases("--compile",
- "-c");
+ final StringParameter compileParameter = parser.add(
+ new StringParameter("Compile code")).addAliases("--compile",
+ "-c");
- // check help generation
- parser.showHelp();
+ // check help generation
+ parser.showHelp();
- // parse arguments
- parser.parse(new String[] { "--help", "section" });
+ // parse arguments
+ parser.parse(new String[]{"--help", "section"});
- // --help was in the arguments
- assertTrue(helpParameter.isParameterSpecified());
+ // --help was in the arguments
+ assertTrue(helpParameter.isParameterSpecified());
- // compile was not present
- assertFalse(compileParameter.isParameterSpecified());
+ // compile was not present
+ assertFalse(compileParameter.isParameterSpecified());
- // validate that help argument was "section"
- assertEquals("section", helpParameter.getValue());
+ // validate that help argument was "section"
+ assertEquals("section", helpParameter.getValue());
- }
+ }
}
package eu.svjatoslav.commons.data;
-import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
public class HexConverterTest {
- @Test
- public void test() {
+ @Test
+ public void test() {
- final String string = HexConverter.byteArrayToHex(new byte[] { 1, 2,
- (byte) 255 });
+ final String string = HexConverter.byteArrayToHex(new byte[]{1, 2,
+ (byte) 255});
- assertEquals("0102FF", string);
+ assertEquals("0102FF", string);
- }
+ }
}
public class CommonPathResolverTest {
- @Test
- public final void testGetDesktopDirectory() {
- System.out.println(CommonPathResolver.getDesktopDirectory());
- }
+ @Test
+ public final void testGetDesktopDirectory() {
+ System.out.println(CommonPathResolver.getDesktopDirectory());
+ }
- @Test
- public final void testGetHomeDirectory() {
- System.out.println(CommonPathResolver.getHomeDirectory());
- }
+ @Test
+ public final void testGetHomeDirectory() {
+ System.out.println(CommonPathResolver.getHomeDirectory());
+ }
}
package eu.svjatoslav.commons.file;
+import org.junit.Assert;
+import org.junit.Test;
+
import java.io.File;
import java.io.IOException;
-import junit.framework.TestCase;
-
-import org.junit.Test;
+public class IOHelperTest {
-public class IOHelperTest extends TestCase {
+ public static final String UTF_8 = "UTF-8";
- @Test
- public void testOverwriteFileIfContentDiffers() throws IOException {
- final File file = new File("overrideTest.txt");
+ @Test
+ public void testOverwriteFileIfContentDiffers() throws IOException {
+ final File file = new File("overrideTest.txt");
- assertTrue(IOHelper.overwriteFileIfContentDiffers(file,
- "aoa".getBytes()));
+ Assert.assertTrue(IOHelper.overwriteFileIfContentDiffers(file,
+ "aoa".getBytes(UTF_8)));
- assertFalse(IOHelper.overwriteFileIfContentDiffers(file,
- "aoa".getBytes()));
+ Assert.assertFalse(IOHelper.overwriteFileIfContentDiffers(file,
+ "aoa".getBytes(UTF_8)));
- assertTrue(IOHelper.overwriteFileIfContentDiffers(file,
- "1234".getBytes()));
+ Assert.assertTrue(IOHelper.overwriteFileIfContentDiffers(file,
+ "1234".getBytes(UTF_8)));
- file.delete();
- }
+ file.delete();
+ }
}
package eu.svjatoslav.commons.string;
-import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
public class String2Test {
- @Test
- public void testCutLeft() {
+ @Test
+ public void testCutLeft() {
- final String2 s = new String2("this is a test");
+ final String2 s = new String2("this is a test");
- assertEquals("this ", s.cutLeft(5));
- assertEquals("is ", s.cutLeft(3));
- assertEquals("a ", s.cutLeft(2));
- assertEquals("test", s.cutLeft(25));
- assertEquals("", s.cutLeft(5));
+ assertEquals("this ", s.trimLeft(5));
+ assertEquals("is ", s.trimLeft(3));
+ assertEquals("a ", s.trimLeft(2));
+ assertEquals("test", s.trimLeft(25));
+ assertEquals("", s.trimLeft(5));
- }
+ }
- @Test
- public void testEnforceLength() {
- final String2 s = new String2("12345678");
- s.enforceLength(3);
- assertEquals("123", s.toString());
+ @Test
+ public void testEnforceLength() {
+ final String2 s = new String2("12345678");
+ s.enforceLength(3);
+ assertEquals("123", s.toString());
- s.enforceLength(5);
- assertEquals("123 ", s.toString());
- }
+ s.enforceLength(5);
+ assertEquals("123 ", s.toString());
+ }
- @Test
- public void testSuffexAndPrefix() {
- final String2 s = new String2("experiment");
- s.addPrefix("The ").addSuffix(" !");
+ @Test
+ public void testSuffixAndPrefix() {
+ final String2 s = new String2("experiment");
+ s.addPrefix("The ").addSuffix(" !");
- assertEquals("The experiment !", s.toString());
- }
+ assertEquals("The experiment !", s.toString());
+ }
}
package eu.svjatoslav.commons.string;
-import static org.junit.Assert.fail;
-
-import org.junit.Before;
import org.junit.Test;
-public class WildCardMatcherTest {
-
- private static void testWildcard(final String string, final String pattern,
- final boolean expectedResult) {
+import static org.junit.Assert.fail;
- final boolean result = WildCardMatcher.match(string, pattern);
+public class WildCardMatcherTest {
- if (result != expectedResult)
- fail("Wildcard match failed.");
- }
+ private static void testWildcard(final String string, final String pattern,
+ final boolean expectedResult) {
- WildCardMatcher matcher;
+ final boolean result = WildCardMatcher.match(string, pattern);
- @Before
- public void setUp() throws Exception {
+ if (result != expectedResult)
+ fail("Wildcard match failed.");
- }
+ }
- @Test
- public void test() {
+ @Test
+ public void test() {
- testWildcard("IMG_9770.JPG", "*.J*", true);
- testWildcard("1", "1", true);
- testWildcard("1", "*", true);
- testWildcard("f", "1", false);
- testWildcard("Hello !", "Hell*!***", true);
- testWildcard("Hello !", "Hell*!", true);
- testWildcard("Hello !", "Hell*", true);
- testWildcard("Hello !", "Hell", false);
- testWildcard("Hello !", "* *", true);
+ testWildcard("IMG_9770.JPG", "*.J*", true);
+ testWildcard("1", "1", true);
+ testWildcard("1", "*", true);
+ testWildcard("f", "1", false);
+ testWildcard("Hello !", "Hell*!***", true);
+ testWildcard("Hello !", "Hell*!", true);
+ testWildcard("Hello !", "Hell*", true);
+ testWildcard("Hello !", "Hell", false);
+ testWildcard("Hello !", "* *", true);
- }
+ }
}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
+ <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/target/classes" />
+ <output-test url="file://$MODULE_DIR$/target/test-classes" />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
+ <excludeFolder url="file://$MODULE_DIR$/target" />
+ </content>
+ <orderEntry type="inheritedJdk" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.8.1" level="project" />
+ <orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.5" level="project" />
+ </component>
+</module>
\ No newline at end of file