if the input was null
+ */
+ public static String quote(String str) {
+ return (str != null ? "'" + str + "'" : null);
+ }
+
+ /**
+ * Turn the given Object into a String with single quotes
+ * if it is a String; keeping the Object as-is else.
+ * @param obj the input Object (e.g. "myString")
+ * @return the quoted String (e.g. "'myString'"),
+ * or the input object as-is if not a String
+ */
+ public static Object quoteIfString(Object obj) {
+ return (obj instanceof String ? quote((String) obj) : obj);
+ }
+
+ /**
+ * Unqualify a string qualified by a '.' dot character. For example,
+ * "this.name.is.qualified", returns "qualified".
+ * @param qualifiedName the qualified name
+ */
+ public static String unqualify(String qualifiedName) {
+ return unqualify(qualifiedName, '.');
+ }
+
+ /**
+ * Unqualify a string qualified by a separator character. For example,
+ * "this:name:is:qualified" returns "qualified" if using a ':' separator.
+ * @param qualifiedName the qualified name
+ * @param separator the separator
+ */
+ public static String unqualify(String qualifiedName, char separator) {
+ return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);
+ }
+
+ /**
+ * Capitalize a String
, changing the first letter to
+ * upper case as per {@link Character#toUpperCase(char)}.
+ * No other letters are changed.
+ * @param str the String to capitalize, may be null
+ * @return the capitalized String, null
if null
+ */
+ public static String capitalize(String str) {
+ return changeFirstCharacterCase(str, true);
+ }
+
+ /**
+ * Uncapitalize a String
, changing the first letter to
+ * lower case as per {@link Character#toLowerCase(char)}.
+ * No other letters are changed.
+ * @param str the String to uncapitalize, may be null
+ * @return the uncapitalized String, null
if null
+ */
+ public static String uncapitalize(String str) {
+ return changeFirstCharacterCase(str, false);
+ }
+
+ private static String changeFirstCharacterCase(String str, boolean capitalize) {
+ if (str == null || str.length() == 0) {
+ return str;
+ }
+ StringBuilder sb = new StringBuilder(str.length());
+ if (capitalize) {
+ sb.append(Character.toUpperCase(str.charAt(0)));
+ }
+ else {
+ sb.append(Character.toLowerCase(str.charAt(0)));
+ }
+ sb.append(str.substring(1));
+ return sb.toString();
+ }
+
+ /**
+ * Extract the filename from the given path,
+ * e.g. "mypath/myfile.txt" -> "myfile.txt".
+ * @param path the file path (may be null
)
+ * @return the extracted filename, or null
if none
+ */
+ public static String getFilename(String path) {
+ if (path == null) {
+ return null;
+ }
+ int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
+ return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);
+ }
+
+ /**
+ * Extract the filename extension from the given path,
+ * e.g. "mypath/myfile.txt" -> "txt".
+ * @param path the file path (may be null
)
+ * @return the extracted filename extension, or null
if none
+ */
+ public static String getFilenameExtension(String path) {
+ if (path == null) {
+ return null;
+ }
+ int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
+ if (extIndex == -1) {
+ return null;
+ }
+ int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
+ if (folderIndex > extIndex) {
+ return null;
+ }
+ return path.substring(extIndex + 1);
+ }
+
+ /**
+ * Strip the filename extension from the given path,
+ * e.g. "mypath/myfile.txt" -> "mypath/myfile".
+ * @param path the file path (may be null
)
+ * @return the path with stripped filename extension,
+ * or null
if none
+ */
+ public static String stripFilenameExtension(String path) {
+ if (path == null) {
+ return null;
+ }
+ int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
+ if (extIndex == -1) {
+ return path;
+ }
+ int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
+ if (folderIndex > extIndex) {
+ return path;
+ }
+ return path.substring(0, extIndex);
+ }
+
+ /**
+ * Apply the given relative path to the given path,
+ * assuming standard Java folder separation (i.e. "/" separators).
+ * @param path the path to start from (usually a full file path)
+ * @param relativePath the relative path to apply
+ * (relative to the full file path above)
+ * @return the full file path that results from applying the relative path
+ */
+ public static String applyRelativePath(String path, String relativePath) {
+ int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
+ if (separatorIndex != -1) {
+ String newPath = path.substring(0, separatorIndex);
+ if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
+ newPath += FOLDER_SEPARATOR;
+ }
+ return newPath + relativePath;
+ }
+ else {
+ return relativePath;
+ }
+ }
+
+ /**
+ * Normalize the path by suppressing sequences like "path/.." and
+ * inner simple dots.
+ * The result is convenient for path comparison. For other uses,
+ * notice that Windows separators ("\") are replaced by simple slashes.
+ * @param path the original path
+ * @return the normalized path
+ */
+ public static String cleanPath(String path) {
+ if (path == null) {
+ return null;
+ }
+ String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
+
+ // Strip prefix from path to analyze, to not treat it as part of the
+ // first path element. This is necessary to correctly parse paths like
+ // "file:core/../core/io/Resource.class", where the ".." should just
+ // strip the first "core" directory while keeping the "file:" prefix.
+ int prefixIndex = pathToUse.indexOf(":");
+ String prefix = "";
+ if (prefixIndex != -1) {
+ prefix = pathToUse.substring(0, prefixIndex + 1);
+ pathToUse = pathToUse.substring(prefixIndex + 1);
+ }
+ if (pathToUse.startsWith(FOLDER_SEPARATOR)) {
+ prefix = prefix + FOLDER_SEPARATOR;
+ pathToUse = pathToUse.substring(1);
+ }
+
+ String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);
+ List pathElements = new LinkedList();
+ int tops = 0;
+
+ for (int i = pathArray.length - 1; i >= 0; i--) {
+ String element = pathArray[i];
+ if (CURRENT_PATH.equals(element)) {
+ // Points to current directory - drop it.
+ }
+ else if (TOP_PATH.equals(element)) {
+ // Registering top path found.
+ tops++;
+ }
+ else {
+ if (tops > 0) {
+ // Merging path element with element corresponding to top path.
+ tops--;
+ }
+ else {
+ // Normal path element found.
+ pathElements.add(0, element);
+ }
+ }
+ }
+
+ // Remaining top paths need to be retained.
+ for (int i = 0; i < tops; i++) {
+ pathElements.add(0, TOP_PATH);
+ }
+
+ return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
+ }
+
+ /**
+ * Compare two paths after normalization of them.
+ * @param path1 first path for comparison
+ * @param path2 second path for comparison
+ * @return whether the two paths are equivalent after normalization
+ */
+ public static boolean pathEquals(String path1, String path2) {
+ return cleanPath(path1).equals(cleanPath(path2));
+ }
+
+ /**
+ * Parse the given localeString
value into a {@link java.util.Locale}.
+ * This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.
+ * @param localeString the locale string, following Locale's
+ * toString()
format ("en", "en_UK", etc);
+ * also accepts spaces as separators, as an alternative to underscores
+ * @return a corresponding Locale
instance
+ */
+ public static Locale parseLocaleString(String localeString) {
+ String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
+ String language = (parts.length > 0 ? parts[0] : "");
+ String country = (parts.length > 1 ? parts[1] : "");
+ validateLocalePart(language);
+ validateLocalePart(country);
+ String variant = "";
+ if (parts.length >= 2) {
+ // There is definitely a variant, and it is everything after the country
+ // code sans the separator between the country code and the variant.
+ int endIndexOfCountryCode = localeString.indexOf(country) + country.length();
+ // Strip off any leading '_' and whitespace, what's left is the variant.
+ variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
+ if (variant.startsWith("_")) {
+ variant = trimLeadingCharacter(variant, '_');
+ }
+ }
+ return (language.length() > 0 ? new Locale(language, country, variant) : null);
+ }
+
+ private static void validateLocalePart(String localePart) {
+ for (int i = 0; i < localePart.length(); i++) {
+ char ch = localePart.charAt(i);
+ if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {
+ throw new IllegalArgumentException(
+ "Locale part \"" + localePart + "\" contains invalid characters");
+ }
+ }
+ }
+
+ /**
+ * Determine the RFC 3066 compliant language tag,
+ * as used for the HTTP "Accept-Language" header.
+ * @param locale the Locale to transform to a language tag
+ * @return the RFC 3066 compliant language tag as String
+ */
+ public static String toLanguageTag(Locale locale) {
+ return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
+ }
+
+
+ //---------------------------------------------------------------------
+ // Convenience methods for working with String arrays
+ //---------------------------------------------------------------------
+
+ /**
+ * Append the given String to the given String array, returning a new array
+ * consisting of the input array contents plus the given String.
+ * @param array the array to append to (can be null
)
+ * @param str the String to append
+ * @return the new array (never null
)
+ */
+ public static String[] addStringToArray(String[] array, String str) {
+ if (Objects.isEmpty(array)) {
+ return new String[] {str};
+ }
+ String[] newArr = new String[array.length + 1];
+ System.arraycopy(array, 0, newArr, 0, array.length);
+ newArr[array.length] = str;
+ return newArr;
+ }
+
+ /**
+ * Concatenate the given String arrays into one,
+ * with overlapping array elements included twice.
+ *
The order of elements in the original arrays is preserved.
+ * @param array1 the first array (can be null
)
+ * @param array2 the second array (can be null
)
+ * @return the new array (null
if both given arrays were null
)
+ */
+ public static String[] concatenateStringArrays(String[] array1, String[] array2) {
+ if (Objects.isEmpty(array1)) {
+ return array2;
+ }
+ if (Objects.isEmpty(array2)) {
+ return array1;
+ }
+ String[] newArr = new String[array1.length + array2.length];
+ System.arraycopy(array1, 0, newArr, 0, array1.length);
+ System.arraycopy(array2, 0, newArr, array1.length, array2.length);
+ return newArr;
+ }
+
+ /**
+ * Merge the given String arrays into one, with overlapping
+ * array elements only included once.
+ *
The order of elements in the original arrays is preserved
+ * (with the exception of overlapping elements, which are only
+ * included on their first occurrence).
+ * @param array1 the first array (can be null
)
+ * @param array2 the second array (can be null
)
+ * @return the new array (null
if both given arrays were null
)
+ */
+ public static String[] mergeStringArrays(String[] array1, String[] array2) {
+ if (Objects.isEmpty(array1)) {
+ return array2;
+ }
+ if (Objects.isEmpty(array2)) {
+ return array1;
+ }
+ List result = new ArrayList();
+ result.addAll(Arrays.asList(array1));
+ for (String str : array2) {
+ if (!result.contains(str)) {
+ result.add(str);
+ }
+ }
+ return toStringArray(result);
+ }
+
+ /**
+ * Turn given source String array into sorted array.
+ * @param array the source array
+ * @return the sorted array (never null
)
+ */
+ public static String[] sortStringArray(String[] array) {
+ if (Objects.isEmpty(array)) {
+ return new String[0];
+ }
+ Arrays.sort(array);
+ return array;
+ }
+
+ /**
+ * Copy the given Collection into a String array.
+ * The Collection must contain String elements only.
+ * @param collection the Collection to copy
+ * @return the String array (null
if the passed-in
+ * Collection was null
)
+ */
+ public static String[] toStringArray(Collection collection) {
+ if (collection == null) {
+ return null;
+ }
+ return collection.toArray(new String[collection.size()]);
+ }
+
+ /**
+ * Copy the given Enumeration into a String array.
+ * The Enumeration must contain String elements only.
+ * @param enumeration the Enumeration to copy
+ * @return the String array (null
if the passed-in
+ * Enumeration was null
)
+ */
+ public static String[] toStringArray(Enumeration enumeration) {
+ if (enumeration == null) {
+ return null;
+ }
+ List list = java.util.Collections.list(enumeration);
+ return list.toArray(new String[list.size()]);
+ }
+
+ /**
+ * Trim the elements of the given String array,
+ * calling String.trim()
on each of them.
+ * @param array the original String array
+ * @return the resulting array (of the same size) with trimmed elements
+ */
+ public static String[] trimArrayElements(String[] array) {
+ if (Objects.isEmpty(array)) {
+ return new String[0];
+ }
+ String[] result = new String[array.length];
+ for (int i = 0; i < array.length; i++) {
+ String element = array[i];
+ result[i] = (element != null ? element.trim() : null);
+ }
+ return result;
+ }
+
+ /**
+ * Remove duplicate Strings from the given array.
+ * Also sorts the array, as it uses a TreeSet.
+ * @param array the String array
+ * @return an array without duplicates, in natural sort order
+ */
+ public static String[] removeDuplicateStrings(String[] array) {
+ if (Objects.isEmpty(array)) {
+ return array;
+ }
+ Set set = new TreeSet();
+ for (String element : array) {
+ set.add(element);
+ }
+ return toStringArray(set);
+ }
+
+ /**
+ * Split a String at the first occurrence of the delimiter.
+ * Does not include the delimiter in the result.
+ * @param toSplit the string to split
+ * @param delimiter to split the string up with
+ * @return a two element array with index 0 being before the delimiter, and
+ * index 1 being after the delimiter (neither element includes the delimiter);
+ * or null
if the delimiter wasn't found in the given input String
+ */
+ public static String[] split(String toSplit, String delimiter) {
+ if (!hasLength(toSplit) || !hasLength(delimiter)) {
+ return null;
+ }
+ int offset = toSplit.indexOf(delimiter);
+ if (offset < 0) {
+ return null;
+ }
+ String beforeDelimiter = toSplit.substring(0, offset);
+ String afterDelimiter = toSplit.substring(offset + delimiter.length());
+ return new String[] {beforeDelimiter, afterDelimiter};
+ }
+
+ /**
+ * Take an array Strings and split each element based on the given delimiter.
+ * A Properties
instance is then generated, with the left of the
+ * delimiter providing the key, and the right of the delimiter providing the value.
+ * Will trim both the key and value before adding them to the
+ * Properties
instance.
+ * @param array the array to process
+ * @param delimiter to split each element using (typically the equals symbol)
+ * @return a Properties
instance representing the array contents,
+ * or null
if the array to process was null or empty
+ */
+ public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {
+ return splitArrayElementsIntoProperties(array, delimiter, null);
+ }
+
+ /**
+ * Take an array Strings and split each element based on the given delimiter.
+ * A Properties
instance is then generated, with the left of the
+ * delimiter providing the key, and the right of the delimiter providing the value.
+ *
Will trim both the key and value before adding them to the
+ * Properties
instance.
+ * @param array the array to process
+ * @param delimiter to split each element using (typically the equals symbol)
+ * @param charsToDelete one or more characters to remove from each element
+ * prior to attempting the split operation (typically the quotation mark
+ * symbol), or null
if no removal should occur
+ * @return a Properties
instance representing the array contents,
+ * or null
if the array to process was null
or empty
+ */
+ public static Properties splitArrayElementsIntoProperties(
+ String[] array, String delimiter, String charsToDelete) {
+
+ if (Objects.isEmpty(array)) {
+ return null;
+ }
+ Properties result = new Properties();
+ for (String element : array) {
+ if (charsToDelete != null) {
+ element = deleteAny(element, charsToDelete);
+ }
+ String[] splittedElement = split(element, delimiter);
+ if (splittedElement == null) {
+ continue;
+ }
+ result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());
+ }
+ return result;
+ }
+
+ /**
+ * Tokenize the given String into a String array via a StringTokenizer.
+ * Trims tokens and omits empty tokens.
+ *
The given delimiters string is supposed to consist of any number of
+ * delimiter characters. Each of those characters can be used to separate
+ * tokens. A delimiter is always a single character; for multi-character
+ * delimiters, consider using delimitedListToStringArray
+ * @param str the String to tokenize
+ * @param delimiters the delimiter characters, assembled as String
+ * (each of those characters is individually considered as delimiter).
+ * @return an array of the tokens
+ * @see java.util.StringTokenizer
+ * @see java.lang.String#trim()
+ * @see #delimitedListToStringArray
+ */
+ public static String[] tokenizeToStringArray(String str, String delimiters) {
+ return tokenizeToStringArray(str, delimiters, true, true);
+ }
+
+ /**
+ * Tokenize the given String into a String array via a StringTokenizer.
+ *
The given delimiters string is supposed to consist of any number of
+ * delimiter characters. Each of those characters can be used to separate
+ * tokens. A delimiter is always a single character; for multi-character
+ * delimiters, consider using delimitedListToStringArray
+ * @param str the String to tokenize
+ * @param delimiters the delimiter characters, assembled as String
+ * (each of those characters is individually considered as delimiter)
+ * @param trimTokens trim the tokens via String's trim
+ * @param ignoreEmptyTokens omit empty tokens from the result array
+ * (only applies to tokens that are empty after trimming; StringTokenizer
+ * will not consider subsequent delimiters as token in the first place).
+ * @return an array of the tokens (null
if the input String
+ * was null
)
+ * @see java.util.StringTokenizer
+ * @see java.lang.String#trim()
+ * @see #delimitedListToStringArray
+ */
+ public static String[] tokenizeToStringArray(
+ String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {
+
+ if (str == null) {
+ return null;
+ }
+ StringTokenizer st = new StringTokenizer(str, delimiters);
+ List tokens = new ArrayList();
+ while (st.hasMoreTokens()) {
+ String token = st.nextToken();
+ if (trimTokens) {
+ token = token.trim();
+ }
+ if (!ignoreEmptyTokens || token.length() > 0) {
+ tokens.add(token);
+ }
+ }
+ return toStringArray(tokens);
+ }
+
+ /**
+ * Take a String which is a delimited list and convert it to a String array.
+ * A single delimiter can consists of more than one character: It will still
+ * be considered as single delimiter string, rather than as bunch of potential
+ * delimiter characters - in contrast to tokenizeToStringArray
.
+ * @param str the input String
+ * @param delimiter the delimiter between elements (this is a single delimiter,
+ * rather than a bunch individual delimiter characters)
+ * @return an array of the tokens in the list
+ * @see #tokenizeToStringArray
+ */
+ public static String[] delimitedListToStringArray(String str, String delimiter) {
+ return delimitedListToStringArray(str, delimiter, null);
+ }
+
+ /**
+ * Take a String which is a delimited list and convert it to a String array.
+ *
A single delimiter can consists of more than one character: It will still
+ * be considered as single delimiter string, rather than as bunch of potential
+ * delimiter characters - in contrast to tokenizeToStringArray
.
+ * @param str the input String
+ * @param delimiter the delimiter between elements (this is a single delimiter,
+ * rather than a bunch individual delimiter characters)
+ * @param charsToDelete a set of characters to delete. Useful for deleting unwanted
+ * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.
+ * @return an array of the tokens in the list
+ * @see #tokenizeToStringArray
+ */
+ public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
+ if (str == null) {
+ return new String[0];
+ }
+ if (delimiter == null) {
+ return new String[] {str};
+ }
+ List result = new ArrayList();
+ if ("".equals(delimiter)) {
+ for (int i = 0; i < str.length(); i++) {
+ result.add(deleteAny(str.substring(i, i + 1), charsToDelete));
+ }
+ }
+ else {
+ int pos = 0;
+ int delPos;
+ while ((delPos = str.indexOf(delimiter, pos)) != -1) {
+ result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
+ pos = delPos + delimiter.length();
+ }
+ if (str.length() > 0 && pos <= str.length()) {
+ // Add rest of String, but not in case of empty input.
+ result.add(deleteAny(str.substring(pos), charsToDelete));
+ }
+ }
+ return toStringArray(result);
+ }
+
+ /**
+ * Convert a CSV list into an array of Strings.
+ * @param str the input String
+ * @return an array of Strings, or the empty array in case of empty input
+ */
+ public static String[] commaDelimitedListToStringArray(String str) {
+ return delimitedListToStringArray(str, ",");
+ }
+
+ /**
+ * Convenience method to convert a CSV string list to a set.
+ * Note that this will suppress duplicates.
+ * @param str the input String
+ * @return a Set of String entries in the list
+ */
+ public static Set commaDelimitedListToSet(String str) {
+ Set set = new TreeSet();
+ String[] tokens = commaDelimitedListToStringArray(str);
+ for (String token : tokens) {
+ set.add(token);
+ }
+ return set;
+ }
+
+ /**
+ * Convenience method to return a Collection as a delimited (e.g. CSV)
+ * String. E.g. useful for toString()
implementations.
+ * @param coll the Collection to display
+ * @param delim the delimiter to use (probably a ",")
+ * @param prefix the String to start each element with
+ * @param suffix the String to end each element with
+ * @return the delimited String
+ */
+ public static String collectionToDelimitedString(Collection> coll, String delim, String prefix, String suffix) {
+ if (Collections.isEmpty(coll)) {
+ return "";
+ }
+ StringBuilder sb = new StringBuilder();
+ Iterator> it = coll.iterator();
+ while (it.hasNext()) {
+ sb.append(prefix).append(it.next()).append(suffix);
+ if (it.hasNext()) {
+ sb.append(delim);
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Convenience method to return a Collection as a delimited (e.g. CSV)
+ * String. E.g. useful for toString()
implementations.
+ * @param coll the Collection to display
+ * @param delim the delimiter to use (probably a ",")
+ * @return the delimited String
+ */
+ public static String collectionToDelimitedString(Collection> coll, String delim) {
+ return collectionToDelimitedString(coll, delim, "", "");
+ }
+
+ /**
+ * Convenience method to return a Collection as a CSV String.
+ * E.g. useful for toString()
implementations.
+ * @param coll the Collection to display
+ * @return the delimited String
+ */
+ public static String collectionToCommaDelimitedString(Collection> coll) {
+ return collectionToDelimitedString(coll, ",");
+ }
+
+ /**
+ * Convenience method to return a String array as a delimited (e.g. CSV)
+ * String. E.g. useful for toString()
implementations.
+ * @param arr the array to display
+ * @param delim the delimiter to use (probably a ",")
+ * @return the delimited String
+ */
+ public static String arrayToDelimitedString(Object[] arr, String delim) {
+ if (Objects.isEmpty(arr)) {
+ return "";
+ }
+ if (arr.length == 1) {
+ return Objects.nullSafeToString(arr[0]);
+ }
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < arr.length; i++) {
+ if (i > 0) {
+ sb.append(delim);
+ }
+ sb.append(arr[i]);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Convenience method to return a String array as a CSV String.
+ * E.g. useful for toString()
implementations.
+ * @param arr the array to display
+ * @return the delimited String
+ */
+ public static String arrayToCommaDelimitedString(Object[] arr) {
+ return arrayToDelimitedString(arr, ",");
+ }
+
+}
+
diff --git a/src/main/java/io/jsonwebtoken/lang/UnknownClassException.java b/src/main/java/io/jsonwebtoken/lang/UnknownClassException.java
new file mode 100644
index 00000000..a4eba997
--- /dev/null
+++ b/src/main/java/io/jsonwebtoken/lang/UnknownClassException.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2014 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.lang;
+
+/**
+ * A RuntimeException
equivalent of the JDK's
+ * ClassNotFoundException
, to maintain a RuntimeException paradigm.
+ *
+ * @since 0.1
+ */
+public class UnknownClassException extends RuntimeException {
+
+ /**
+ * Creates a new UnknownClassException.
+ */
+ public UnknownClassException() {
+ super();
+ }
+
+ /**
+ * Constructs a new UnknownClassException.
+ *
+ * @param message the reason for the exception
+ */
+ public UnknownClassException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new UnknownClassException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownClassException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new UnknownClassException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownClassException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/groovy/io/jsonwebtoken/JWTsTest.groovy b/src/test/groovy/io/jsonwebtoken/JWTsTest.groovy
new file mode 100644
index 00000000..4b67dff0
--- /dev/null
+++ b/src/test/groovy/io/jsonwebtoken/JWTsTest.groovy
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2014 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken
+
+import org.testng.annotations.Test
+
+import java.security.KeyPair
+import java.security.KeyPairGenerator
+import java.security.PrivateKey
+import java.security.PublicKey
+import java.security.SecureRandom
+
+import static org.testng.Assert.*
+
+class JWTsTest {
+
+ @Test
+ void testPlaintextJwtString() {
+
+ // Assert exact output per example at https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-6.1
+
+ // The base64url encoding of the example claims set in the spec shows that their original payload ends lines with
+ // carriage return + newline, so we have to include them in the test payload to assert our encoded output
+ // matches what is in the spec:
+
+ def payload = '{"iss":"joe",\r\n' +
+ ' "exp":1300819380,\r\n' +
+ ' "http://example.com/is_root":true}'
+
+ String val = JWTs.builder().setPayload(payload).compact();
+
+ def specOutput = 'eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.'
+
+ assertEquals val, specOutput
+ }
+
+ @Test
+ void testParsePlaintextToken() {
+
+ def claims = [iss: 'joe', exp: 1300819380, 'http://example.com/is_root':true]
+
+ String jwt = JWTs.builder().setClaims(claims).compact();
+
+ def token = JWTs.parser().parse(jwt);
+
+ assertEquals token.body, claims
+ }
+
+ @Test(expectedExceptions = IllegalArgumentException)
+ void testParseNull() {
+ JWTs.parser().parse(null)
+ }
+
+ @Test(expectedExceptions = IllegalArgumentException)
+ void testParseEmptyString() {
+ JWTs.parser().parse('')
+ }
+
+ @Test(expectedExceptions = IllegalArgumentException)
+ void testParseWhitespaceString() {
+ JWTs.parser().parse(' ')
+ }
+
+ @Test
+ void testParseWithNoPeriods() {
+ try {
+ JWTs.parser().parse('foo')
+ fail()
+ } catch (MalformedJwtException e) {
+ assertEquals e.message, "JWT strings must contain exactly 2 period characters. Found: 0"
+ }
+ }
+
+ @Test
+ void testParseWithOnePeriodOnly() {
+ try {
+ JWTs.parser().parse('.')
+ fail()
+ } catch (MalformedJwtException e) {
+ assertEquals e.message, "JWT strings must contain exactly 2 period characters. Found: 1"
+ }
+ }
+
+ @Test
+ void testParseWithTwoPeriodsOnly() {
+ try {
+ JWTs.parser().parse('..')
+ fail()
+ } catch (MalformedJwtException e) {
+ assertEquals e.message, "JWT string '..' is missing a body/payload."
+ }
+ }
+
+ @Test
+ void testParseWithHeaderOnly() {
+ try {
+ JWTs.parser().parse('foo..')
+ fail()
+ } catch (MalformedJwtException e) {
+ assertEquals e.message, "JWT string 'foo..' is missing a body/payload."
+ }
+ }
+
+ @Test
+ void testParseWithSignatureOnly() {
+ try {
+ JWTs.parser().parse('..bar')
+ fail()
+ } catch (MalformedJwtException e) {
+ assertEquals e.message, "JWT string '..bar' is missing a body/payload."
+ }
+ }
+
+ @Test
+ void testParseWithHeaderAndSignatureOnly() {
+ try {
+ JWTs.parser().parse('foo..bar')
+ fail()
+ } catch (MalformedJwtException e) {
+ assertEquals e.message, "JWT string 'foo..bar' is missing a body/payload."
+ }
+ }
+
+ @Test
+ void testHS256() {
+ testHmac(SignatureAlgorithm.HS256);
+ }
+
+ @Test
+ void testHS384() {
+ testHmac(SignatureAlgorithm.HS384);
+ }
+
+ @Test
+ void testHS512() {
+ testHmac(SignatureAlgorithm.HS512);
+ }
+
+ @Test
+ void testRS256() {
+ testRsa(SignatureAlgorithm.RS256);
+ }
+
+ @Test
+ void testRS384() {
+ testRsa(SignatureAlgorithm.RS384);
+ }
+
+ @Test
+ void testRS512() {
+ testRsa(SignatureAlgorithm.RS512);
+ }
+
+ @Test
+ void testPS256() {
+ testRsa(SignatureAlgorithm.PS256);
+ }
+
+ @Test
+ void testPS384() {
+ testRsa(SignatureAlgorithm.PS384);
+ }
+
+ @Test
+ void testPS512() {
+ testRsa(SignatureAlgorithm.PS512, 2048, false);
+ }
+
+ @Test
+ void testRSA256WithPrivateKeyValidation() {
+ testRsa(SignatureAlgorithm.RS256, 1024, true);
+ }
+
+ @Test
+ void testRSA384WithPrivateKeyValidation() {
+ testRsa(SignatureAlgorithm.RS384, 1024, true);
+ }
+
+ @Test
+ void testRSA512WithPrivateKeyValidation() {
+ testRsa(SignatureAlgorithm.RS512, 1024, true);
+ }
+
+ static void testRsa(SignatureAlgorithm alg) {
+ testRsa(alg, 1024, false);
+ }
+
+ static void testRsa(SignatureAlgorithm alg, int keySize, boolean verifyWithPrivateKey) {
+
+ KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
+ keyGenerator.initialize(keySize);
+
+ KeyPair kp = keyGenerator.genKeyPair();
+ PublicKey publicKey = kp.getPublic();
+ PrivateKey privateKey = kp.getPrivate();
+
+ def claims = [iss: 'joe', exp: 1300819380, 'http://example.com/is_root':true]
+
+ String jwt = JWTs.builder().setClaims(claims).signWith(alg, privateKey).compact();
+
+ def key = publicKey;
+ if (verifyWithPrivateKey) {
+ key = privateKey;
+ }
+
+ def token = JWTs.parser().setSigningKey(key).parse(jwt);
+
+ assertEquals token.header, [alg: alg.name()]
+
+ assertEquals token.body, claims
+
+ }
+
+ static void testHmac(SignatureAlgorithm alg) {
+ //create random signing key for testing:
+ Random random = new SecureRandom();
+ byte[] key = new byte[64];
+ random.nextBytes(key);
+
+ def claims = [iss: 'joe', exp: 1300819380, 'http://example.com/is_root':true]
+
+ String jwt = JWTs.builder().setClaims(claims).signWith(alg, key).compact();
+
+ def token = JWTs.parser().setSigningKey(key).parse(jwt)
+
+ assertEquals token.header, [alg: alg.name()]
+
+ assertEquals token.body, claims
+ }
+}
+
diff --git a/src/test/groovy/io/jsonwebtoken/SignatureAlgorithmTest.groovy b/src/test/groovy/io/jsonwebtoken/SignatureAlgorithmTest.groovy
new file mode 100644
index 00000000..acea7635
--- /dev/null
+++ b/src/test/groovy/io/jsonwebtoken/SignatureAlgorithmTest.groovy
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2014 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken
+
+import org.testng.annotations.Test
+import static org.testng.Assert.*
+
+class SignatureAlgorithmTest {
+
+ @Test
+ void testNames() {
+ def algNames = ['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512',
+ 'ES256', 'ES384', 'ES512', 'PS256', 'PS384', 'PS512', 'NONE']
+
+ for( String name : algNames ) {
+ testName(name)
+ }
+ }
+
+ private static void testName(String name) {
+ def alg = SignatureAlgorithm.forName(name);
+ def namedAlg = name as SignatureAlgorithm //Groovy type coercion FTW!
+ assertTrue alg == namedAlg
+ assert alg.description != null && alg.description != ""
+ }
+
+ @Test(expectedExceptions = SignatureException)
+ void testUnrecognizedAlgorithmName() {
+ SignatureAlgorithm.forName('whatever')
+ }
+}
diff --git a/src/test/groovy/io/jsonwebtoken/impl/crypto/DefaultSignerFactoryTest.groovy b/src/test/groovy/io/jsonwebtoken/impl/crypto/DefaultSignerFactoryTest.groovy
new file mode 100644
index 00000000..1c8e3d8f
--- /dev/null
+++ b/src/test/groovy/io/jsonwebtoken/impl/crypto/DefaultSignerFactoryTest.groovy
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2014 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.impl.crypto
+
+import io.jsonwebtoken.SignatureAlgorithm
+import org.testng.annotations.Test
+
+import javax.crypto.spec.SecretKeySpec
+
+import static org.testng.Assert.*
+
+class DefaultSignerFactoryTest {
+
+ private static final Random rng = new Random(); //doesn't need to be secure - we're just testing
+
+ @Test
+ void testCreateSignerWithNoneAlgorithm() {
+
+ byte[] keyBytes = new byte[32];
+ rng.nextBytes(keyBytes);
+ SecretKeySpec key = new SecretKeySpec(keyBytes, "foo");
+
+ def factory = new DefaultSignerFactory();
+
+ try {
+ factory.createSigner(SignatureAlgorithm.NONE, key);
+ fail();
+ } catch (IllegalArgumentException iae) {
+ assertEquals iae.message, "The 'NONE' algorithm cannot be used for signing."
+ }
+ }
+
+}
diff --git a/src/test/groovy/io/jsonwebtoken/impl/crypto/MacSignerTest.groovy b/src/test/groovy/io/jsonwebtoken/impl/crypto/MacSignerTest.groovy
new file mode 100644
index 00000000..c0a5745e
--- /dev/null
+++ b/src/test/groovy/io/jsonwebtoken/impl/crypto/MacSignerTest.groovy
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2014 jsonwebtoken.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.jsonwebtoken.impl.crypto
+
+import io.jsonwebtoken.SignatureAlgorithm
+import io.jsonwebtoken.SignatureException
+import org.testng.annotations.Test
+import static org.testng.Assert.*
+
+import javax.crypto.Mac
+import java.security.InvalidKeyException
+import java.security.NoSuchAlgorithmException
+
+class MacSignerTest {
+
+ private static final Random rng = new Random(); //doesn't need to be secure - we're just testing
+
+ @Test
+ void testNoSuchAlgorithmException() {
+ byte[] key = new byte[32];
+ byte[] data = new byte[32];
+ rng.nextBytes(key);
+ rng.nextBytes(data);
+
+ def s = new MacSigner(SignatureAlgorithm.HS256, key) {
+ @Override
+ protected Mac doGetMacInstance() throws NoSuchAlgorithmException, InvalidKeyException {
+ throw new NoSuchAlgorithmException("foo");
+ }
+ }
+ try {
+ s.sign(data);
+ fail();
+ } catch (SignatureException e) {
+ assertTrue e.cause instanceof NoSuchAlgorithmException
+ assertEquals e.cause.message, 'foo'
+ }
+ }
+
+ @Test
+ void testInvalidKeyException() {
+ byte[] key = new byte[32];
+ byte[] data = new byte[32];
+ rng.nextBytes(key);
+ rng.nextBytes(data);
+
+ def s = new MacSigner(SignatureAlgorithm.HS256, key) {
+ @Override
+ protected Mac doGetMacInstance() throws NoSuchAlgorithmException, InvalidKeyException {
+ throw new InvalidKeyException("foo");
+ }
+ }
+ try {
+ s.sign(data);
+ fail();
+ } catch (SignatureException e) {
+ assertTrue e.cause instanceof InvalidKeyException
+ assertEquals e.cause.message, 'foo'
+ }
+ }
+}