From fbef106efa9eb3b54279007c6b0fb74df4b1e91a Mon Sep 17 00:00:00 2001 From: rovo89 Date: Mon, 6 May 2013 22:51:30 +0200 Subject: [PATCH 01/90] Add a function to make SharedPreferences world-readable --- src/de/robv/android/xposed/XSharedPreferences.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/de/robv/android/xposed/XSharedPreferences.java b/src/de/robv/android/xposed/XSharedPreferences.java index aa80a411..b0508a0f 100644 --- a/src/de/robv/android/xposed/XSharedPreferences.java +++ b/src/de/robv/android/xposed/XSharedPreferences.java @@ -43,6 +43,13 @@ public XSharedPreferences(String packageName, String prefFileName) { startLoadFromDisk(); } + public boolean makeWorldReadable() { + if (!mFile.exists()) // just in case - the file should never be created if it doesn'e exist + return false; + + return mFile.setReadable(true, false); + } + private void startLoadFromDisk() { synchronized (this) { mLoaded = false; From b411f285000f900f5b8fba9fa09ece5b7ab21a1d Mon Sep 17 00:00:00 2001 From: Fiouz Date: Sat, 1 Jun 2013 12:08:09 +0200 Subject: [PATCH 02/90] Disable hooks if instrumentation is detected Detect instrumentation at application binding. New static flag in XposedBridge which acts as a "kill switch" for user installed mods - that flag is enabled when instrumentation is detected. --- src/de/robv/android/xposed/XposedBridge.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/de/robv/android/xposed/XposedBridge.java b/src/de/robv/android/xposed/XposedBridge.java index 9ced3d4f..80974355 100644 --- a/src/de/robv/android/xposed/XposedBridge.java +++ b/src/de/robv/android/xposed/XposedBridge.java @@ -33,6 +33,7 @@ import android.app.ActivityThread; import android.app.AndroidAppHelper; import android.app.LoadedApk; +import android.content.ComponentName; import android.content.pm.ApplicationInfo; import android.content.res.CompatibilityInfo; import android.content.res.Configuration; @@ -57,6 +58,7 @@ public final class XposedBridge { private static PrintWriter logWriter = null; // log for initialization of a few mods is about 500 bytes, so 2*20 kB (2*~350 lines) should be enough private static final int MAX_LOGFILE_SIZE = 20*1024; + private static boolean disableHooks = false; private static final Object[] EMPTY_ARRAY = new Object[0]; public static final ClassLoader BOOTCLASSLOADER = ClassLoader.getSystemClassLoader(); @@ -125,6 +127,12 @@ private static void initXbridgeZygote() throws Exception { protected void beforeHookedMethod(MethodHookParam param) throws Throwable { ActivityThread activityThread = (ActivityThread) param.thisObject; ApplicationInfo appInfo = (ApplicationInfo) getObjectField(param.args[0], "appInfo"); + ComponentName instrumentationName = (ComponentName) getObjectField(param.args[0], "instrumentationName"); + if (instrumentationName != null) { + XposedBridge.log("Instrumentation detected, disabling framework for " + appInfo.packageName); + disableHooks = true; + return; + } CompatibilityInfo compatInfo = (CompatibilityInfo) getObjectField(param.args[0], "compatInfo"); if (appInfo.sourceDir == null) return; @@ -403,6 +411,14 @@ public static Set hookAllConstructors(Class hookClass, */ @SuppressWarnings("unchecked") private static Object handleHookedMethod(Member method, Object thisObject, Object[] args) throws Throwable { + if (disableHooks) { + try { + return invokeOriginalMethod(method, thisObject, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + TreeSet callbacks; synchronized (hookedMethodCallbacks) { callbacks = hookedMethodCallbacks.get(method); From 70134b2d8e4e2ecdb4b1f9d4a496aa2268c69be3 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sat, 24 Aug 2013 20:18:59 +0200 Subject: [PATCH 03/90] don't trigger layout inflation callback if errors occured --- src/android/content/res/XResources.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/android/content/res/XResources.java b/src/android/content/res/XResources.java index 9551ac81..b864a4b2 100644 --- a/src/android/content/res/XResources.java +++ b/src/android/content/res/XResources.java @@ -120,6 +120,9 @@ protected void afterHookedMethod(MethodHookParam param) throws Throwable { findAndHookMethod(LayoutInflater.class, "inflate", XmlPullParser.class, ViewGroup.class, boolean.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { + if (param.hasThrowable()) + return; + XMLInstanceDetails details; synchronized (xmlInstanceDetails) { details = xmlInstanceDetails.get(param.args[0]); From 5dbb3b3a289ebcdffdaa3989127cebc8ee740e63 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sat, 24 Aug 2013 20:21:10 +0200 Subject: [PATCH 04/90] fix double scaling in compatibility mode --- src/android/content/res/XResources.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/android/content/res/XResources.java b/src/android/content/res/XResources.java index b864a4b2..9660ba66 100644 --- a/src/android/content/res/XResources.java +++ b/src/android/content/res/XResources.java @@ -2,6 +2,7 @@ import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.getObjectField; +import static de.robv.android.xposed.XposedHelpers.setObjectField; import java.io.File; import java.util.HashMap; @@ -45,7 +46,8 @@ public class XResources extends Resources { public XResources(Resources parent, String resDir) { super(parent.getAssets(), null, null, null); this.resDir = resDir; - updateConfiguration(parent.getConfiguration(), parent.getDisplayMetrics(), parent.getCompatibilityInfo()); + updateConfiguration(parent.getConfiguration(), parent.getDisplayMetrics()); + setObjectField(this, "mCompatibilityInfo", getObjectField(parent, "mCompatibilityInfo")); } /** Framework only, don't call this from your module! */ From e62fa7f78189ec14dce814c3cd456cdef7dd3ad6 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sat, 24 Aug 2013 20:29:43 +0200 Subject: [PATCH 05/90] fix replacing colors that are used as drawables --- src/android/content/res/XResources.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/android/content/res/XResources.java b/src/android/content/res/XResources.java index 9660ba66..f2d8cba8 100644 --- a/src/android/content/res/XResources.java +++ b/src/android/content/res/XResources.java @@ -12,6 +12,7 @@ import org.xmlpull.v1.XmlPullParser; import android.graphics.Movie; +import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.SparseArray; import android.util.TypedValue; @@ -349,6 +350,8 @@ public Drawable getDrawable(int id) throws NotFoundException { if (result != null) return result; } catch (Throwable t) { XposedBridge.log(t); } + } else if (replacement instanceof Integer) { + return new ColorDrawable((Integer) replacement); } else if (replacement instanceof XResForwarder) { Resources repRes = ((XResForwarder) replacement).getResources(); int repId = ((XResForwarder) replacement).getId(); @@ -366,6 +369,8 @@ public Drawable getDrawableForDensity(int id, int density) throws NotFoundExcept if (result != null) return result; } catch (Throwable t) { XposedBridge.log(t); } + } else if (replacement instanceof Integer) { + return new ColorDrawable((Integer) replacement); } else if (replacement instanceof XResForwarder) { Resources repRes = ((XResForwarder) replacement).getResources(); int repId = ((XResForwarder) replacement).getId(); @@ -735,6 +740,8 @@ public Drawable getDrawable(int index) { if (result != null) return result; } catch (Throwable t) { XposedBridge.log(t); } + } else if (replacement instanceof Integer) { + return new ColorDrawable((Integer) replacement); } else if (replacement instanceof XResForwarder) { Resources repRes = ((XResForwarder) replacement).getResources(); int repId = ((XResForwarder) replacement).getId(); From 096e6b7e8050771d76c0864e1fccdcbe9ef516a9 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sat, 24 Aug 2013 20:57:29 +0200 Subject: [PATCH 06/90] callMethod() helper now also works for inherited methods Previously it didn't work for methods from the superclass that weren't overridden (and thus not present in getDeclaredMethods()). Now findMethodBestMatch() also checks getMethods(), so it should behave like a normal compiler/VM. Don't use findMethodBestMatch() for hooking methods unless you like surprises! --- src/de/robv/android/xposed/XposedHelpers.java | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/de/robv/android/xposed/XposedHelpers.java b/src/de/robv/android/xposed/XposedHelpers.java index 1696feca..11b8cc10 100644 --- a/src/de/robv/android/xposed/XposedHelpers.java +++ b/src/de/robv/android/xposed/XposedHelpers.java @@ -214,18 +214,20 @@ public static Method findMethodBestMatch(Class clazz, String methodName, Clas } catch (NoSuchMethodError ignored) {} Method bestMatch = null; - Method[] methods = clazz.getDeclaredMethods(); - for (Method method : methods) { - // compare name and parameters - if (method.getName().equals(methodName) && ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) { - // get accessible version of method - if (bestMatch == null || MemberUtils.compareParameterTypes( - method.getParameterTypes(), - bestMatch.getParameterTypes(), - parameterTypes) < 0) { - bestMatch = method; - } - } + for (int i = 0; i < 2; i++) { + Method[] methods = (i == 0) ? clazz.getDeclaredMethods() : clazz.getMethods(); + for (Method method : methods) { + // compare name and parameters + if (method.getName().equals(methodName) && ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) { + // get accessible version of method + if (bestMatch == null || MemberUtils.compareParameterTypes( + method.getParameterTypes(), + bestMatch.getParameterTypes(), + parameterTypes) < 0) { + bestMatch = method; + } + } + } } if (bestMatch != null) { From 5384966637c695a1172f004bc5cdd1fb45604ba9 Mon Sep 17 00:00:00 2001 From: Francisco Ferreira Date: Sat, 15 Jun 2013 21:34:39 +0200 Subject: [PATCH 07/90] returnConstant() with priority wasn't using it --- src/de/robv/android/xposed/XC_MethodReplacement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/robv/android/xposed/XC_MethodReplacement.java b/src/de/robv/android/xposed/XC_MethodReplacement.java index 23219b44..ffaa5bb9 100644 --- a/src/de/robv/android/xposed/XC_MethodReplacement.java +++ b/src/de/robv/android/xposed/XC_MethodReplacement.java @@ -45,7 +45,7 @@ public static XC_MethodReplacement returnConstant(final Object result) { * @see #returnConstant(Object) */ public static XC_MethodReplacement returnConstant(int priority, final Object result) { - return new XC_MethodReplacement() { + return new XC_MethodReplacement(priority) { @Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { return result; From 81354531bf556398607e989048f29461109f1390 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sun, 25 Aug 2013 11:29:50 +0200 Subject: [PATCH 08/90] declare license --- NOTICE.txt | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 NOTICE.txt diff --git a/NOTICE.txt b/NOTICE.txt new file mode 100644 index 00000000..d1fc673f --- /dev/null +++ b/NOTICE.txt @@ -0,0 +1,25 @@ +LICENSE FOR THE MAIN PRODUCT +============================ + +Copyright 2013 rovo89, Tungstwenty + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + + +INCLUDED LIBRARIES +================== + +This product includes slightly modified code of the "Apache Commons Lang" +library. See lib/apache-commons-lang/NOTICE.txt for licensing details. + From d54bbaba33121b15f2ace2189893e641d576c453 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sun, 25 Aug 2013 11:30:15 +0200 Subject: [PATCH 09/90] Bump version to 30 Why moving from 2.1.4 to 30? Version numbers can be anything. Using the x.y.z format is a tradional way of indicating the amount and importance of changes between two versions to end-users. However, Xposed is more than XposedBridge, there is also the native binary and the installer. The state of this set of components is better shown by the version number of the installer, which is displayed in the "About" screen. That currently makes two very similar x.y.z versions which can easily be confusing. Apart from the one mentioned above, there is no big advantage of writing the version as x.y.z. On the contrary, simple integers are much easier to compare - and that's what this version number is mainly used for. Checking whether the latest JAR is installed and checking "xposedminversion" of modules. And the best thing: Both formats are compatible with the current version comparison implementation. 30 is like 30.0.0, which is clearly bigger than 2.1.4. And 2.1.4 can be seen as 2, which is lower than 30. The lowest possible number would have been 3, but as this seems too small and wouldn't reflect the many iterations XposedBridge already went through. Therefore, it's 30 now. --- assets/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/VERSION b/assets/VERSION index c346e7a0..64bb6b74 100644 --- a/assets/VERSION +++ b/assets/VERSION @@ -1 +1 @@ -2.1.4 \ No newline at end of file +30 From ed9277291368e420d91a2304f34ba436ea5de8e9 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sun, 25 Aug 2013 12:35:33 +0200 Subject: [PATCH 10/90] make sure to include NOTICE.txt in the compiled file --- .classpath | 6 ++++-- NOTICE.txt | 14 ++++++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/.classpath b/.classpath index 4683f9b8..5861e979 100644 --- a/.classpath +++ b/.classpath @@ -2,13 +2,15 @@ - + - + + + diff --git a/NOTICE.txt b/NOTICE.txt index d1fc673f..a50b1337 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -21,5 +21,15 @@ INCLUDED LIBRARIES ================== This product includes slightly modified code of the "Apache Commons Lang" -library. See lib/apache-commons-lang/NOTICE.txt for licensing details. - +library. See lib/apache-commons-lang for details. +Here is a copy of the NOTICE.txt from that directory: +------------------------------------------------------------------------- +Apache Commons Lang +Copyright 2001-2011 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +This product includes software from the Spring Framework, +under the Apache License 2.0 (see: StringUtils.containsWhitespace()) +------------------------------------------------------------------------- From d1325efd220e8d3acae90e5d897ef15d25890c1f Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sun, 25 Aug 2013 20:21:55 +0200 Subject: [PATCH 11/90] fix build --- .classpath | 1 - .project | 5 +++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.classpath b/.classpath index 5861e979..ca30b19f 100644 --- a/.classpath +++ b/.classpath @@ -11,6 +11,5 @@ - diff --git a/.project b/.project index 8b30bd11..3f966ddc 100644 --- a/.project +++ b/.project @@ -36,5 +36,10 @@ 2 ANDROID_SDK/sources/android-15 + + src/NOTICE.txt + 1 + PROJECT_LOC/NOTICE.txt + From 9f3508d7ccf59f6037e28a3a18b432b4d886e105 Mon Sep 17 00:00:00 2001 From: rovo89 Date: Sun, 15 Sep 2013 09:21:45 +0200 Subject: [PATCH 12/90] v31: Get rid of /data/xposed --- assets/VERSION | 2 +- install.bat | 4 ++-- src/de/robv/android/xposed/XposedBridge.java | 18 ++++++++++-------- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/assets/VERSION b/assets/VERSION index 64bb6b74..e85087af 100644 --- a/assets/VERSION +++ b/assets/VERSION @@ -1 +1 @@ -30 +31 diff --git a/install.bat b/install.bat index f00dfe7d..4670717c 100644 --- a/install.bat +++ b/install.bat @@ -1,4 +1,4 @@ cd /d %~dp0 dir bin\XposedBridge.apk -adb push bin\XposedBridge.apk /data/xposed/XposedBridge.jar.newversion -pause \ No newline at end of file +adb push bin\XposedBridge.apk /data/data/de.robv.android.xposed.installer/bin/XposedBridge.jar.newversion +pause diff --git a/src/de/robv/android/xposed/XposedBridge.java b/src/de/robv/android/xposed/XposedBridge.java index 80974355..fb26fbc6 100644 --- a/src/de/robv/android/xposed/XposedBridge.java +++ b/src/de/robv/android/xposed/XposedBridge.java @@ -30,6 +30,7 @@ import java.util.Set; import java.util.TreeSet; +import android.annotation.SuppressLint; import android.app.ActivityThread; import android.app.AndroidAppHelper; import android.app.LoadedApk; @@ -59,10 +60,12 @@ public final class XposedBridge { // log for initialization of a few mods is about 500 bytes, so 2*20 kB (2*~350 lines) should be enough private static final int MAX_LOGFILE_SIZE = 20*1024; private static boolean disableHooks = false; - + private static final Object[] EMPTY_ARRAY = new Object[0]; public static final ClassLoader BOOTCLASSLOADER = ClassLoader.getSystemClassLoader(); - + @SuppressLint("SdCardPath") + public static final String BASE_DIR = "/data/data/de.robv.android.xposed.installer/"; + // built-in handlers private static final Map> hookedMethodCallbacks = new HashMap>(); @@ -80,9 +83,9 @@ private static void main(String[] args) { try { // initialize log file try { - File logFile = new File("/data/xposed/debug.log"); + File logFile = new File(BASE_DIR + "log/debug.log"); if (startClassName == null && logFile.length() > MAX_LOGFILE_SIZE) - logFile.renameTo(new File("/data/xposed/debug.log.old")); + logFile.renameTo(new File(BASE_DIR + "log/debug.log.old")); logWriter = new PrintWriter(new FileWriter(logFile, true)); logFile.setReadable(true, false); logFile.setWritable(true, false); @@ -233,10 +236,10 @@ protected void beforeHookedMethod(MethodHookParam param) throws Throwable { } /** - * Try to load all modules defined in /data/xposed/modules.list + * Try to load all modules defined in BASE_DIR/conf/modules.list */ private static void loadModules(String startClassName) throws IOException { - BufferedReader apks = new BufferedReader(new FileReader("/data/xposed/modules.list")); + BufferedReader apks = new BufferedReader(new FileReader(BASE_DIR + "conf/modules.list")); String apk; while ((apk = apks.readLine()) != null) { loadModule(apk, startClassName); @@ -247,7 +250,6 @@ private static void loadModules(String startClassName) throws IOException { /** * Load a module from an APK by calling the init(String) method for all classes defined * in assets/xposed_init. - * @see MethodSignatureGuide#init */ private static void loadModule(String apk, String startClassName) { log("Loading modules from " + apk); @@ -317,7 +319,7 @@ private static void loadModule(String apk, String startClassName) { } /** - * Writes a message to /data/xposed/debug.log (needs to have chmod 777) + * Writes a message to BASE_DIR/log/debug.log (needs to have chmod 777) * @param text log message */ public synchronized static void log(String text) { From 3926fa79b802ac6d0a68dff022e25e9202664e5f Mon Sep 17 00:00:00 2001 From: rovo89 Date: Mon, 30 Sep 2013 23:52:12 +0200 Subject: [PATCH 13/90] v32: Removed unused classes from the Commons Lang Lib The resulting XposedBridge.jar is then 91 kB instead of 186 kB. --- assets/VERSION | 2 +- lib/apache-commons-lang/MODIFICATIONS.txt | 40 +- .../apache/commons/lang3/AnnotationUtils.java | 371 --- .../org/apache/commons/lang3/BitField.java | 283 -- .../apache/commons/lang3/BooleanUtils.java | 1082 ------- .../apache/commons/lang3/CharEncoding.java | 105 - .../org/apache/commons/lang3/CharRange.java | 356 -- .../org/apache/commons/lang3/CharSet.java | 278 -- .../apache/commons/lang3/CharSetUtils.java | 217 -- .../org/apache/commons/lang3/EnumUtils.java | 208 -- .../org/apache/commons/lang3/LocaleUtils.java | 297 -- .../commons/lang3/RandomStringUtils.java | 322 -- .../org/apache/commons/lang3/Range.java | 493 --- .../commons/lang3/SerializationException.java | 78 - .../commons/lang3/SerializationUtils.java | 271 -- .../commons/lang3/StringEscapeUtils.java | 585 ---- .../lang3/builder/StandardToStringStyle.java | 560 ---- .../lang3/concurrent/AtomicInitializer.java | 106 - .../concurrent/AtomicSafeInitializer.java | 96 - .../concurrent/BackgroundInitializer.java | 333 -- .../lang3/concurrent/BasicThreadFactory.java | 381 --- .../CallableBackgroundInitializer.java | 126 - .../lang3/concurrent/ConcurrentException.java | 70 - .../concurrent/ConcurrentInitializer.java | 54 - .../ConcurrentRuntimeException.java | 72 - .../lang3/concurrent/ConcurrentUtils.java | 386 --- .../lang3/concurrent/ConstantInitializer.java | 128 - .../lang3/concurrent/LazyInitializer.java | 119 - .../MultiBackgroundInitializer.java | 352 -- .../lang3/concurrent/TimedSemaphore.java | 421 --- .../commons/lang3/concurrent/package.html | 23 - .../lang3/event/EventListenerSupport.java | 316 -- .../commons/lang3/event/EventUtils.java | 130 - .../apache/commons/lang3/event/package.html | 22 - .../lang3/exception/ContextedException.java | 246 -- .../exception/ContextedRuntimeException.java | 247 -- .../exception/DefaultExceptionContext.java | 159 - .../lang3/exception/ExceptionContext.java | 103 - .../lang3/exception/ExceptionUtils.java | 697 ---- .../apache/commons/lang3/math/Fraction.java | 959 ------ .../commons/lang3/math/IEEE754rUtils.java | 265 -- .../commons/lang3/math/NumberUtils.java | 1414 -------- .../apache/commons/lang3/math/package.html | 25 - .../commons/lang3/mutable/MutableBoolean.java | 193 -- .../commons/lang3/mutable/MutableByte.java | 283 -- .../commons/lang3/mutable/MutableDouble.java | 312 -- .../commons/lang3/mutable/MutableFloat.java | 313 -- .../commons/lang3/mutable/MutableLong.java | 273 -- .../commons/lang3/mutable/MutableObject.java | 126 - .../commons/lang3/mutable/MutableShort.java | 283 -- .../lang3/reflect/ConstructorUtils.java | 289 -- .../commons/lang3/reflect/FieldUtils.java | 595 ---- .../commons/lang3/reflect/TypeUtils.java | 1088 ------- .../commons/lang3/text/CompositeFormat.java | 116 - .../lang3/text/ExtendedMessageFormat.java | 535 ---- .../commons/lang3/text/FormatFactory.java | 42 - .../commons/lang3/text/FormattableUtils.java | 151 - .../apache/commons/lang3/text/StrBuilder.java | 2849 ----------------- .../apache/commons/lang3/text/StrLookup.java | 172 - .../apache/commons/lang3/text/StrMatcher.java | 436 --- .../commons/lang3/text/StrSubstitutor.java | 926 ------ .../commons/lang3/text/StrTokenizer.java | 1104 ------- .../apache/commons/lang3/text/WordUtils.java | 497 --- .../apache/commons/lang3/text/package.html | 26 - .../text/translate/AggregateTranslator.java | 60 - .../translate/CharSequenceTranslator.java | 125 - .../text/translate/CodePointTranslator.java | 56 - .../lang3/text/translate/EntityArrays.java | 425 --- .../text/translate/LookupTranslator.java | 80 - .../text/translate/NumericEntityEscaper.java | 119 - .../translate/NumericEntityUnescaper.java | 139 - .../lang3/text/translate/OctalUnescaper.java | 60 - .../lang3/text/translate/UnicodeEscaper.java | 130 - .../text/translate/UnicodeUnescaper.java | 66 - .../commons/lang3/text/translate/package.html | 27 - .../commons/lang3/time/DateFormatUtils.java | 320 -- .../apache/commons/lang3/time/DateUtils.java | 1831 ----------- .../lang3/time/DurationFormatUtils.java | 662 ---- .../commons/lang3/time/FastDateFormat.java | 1519 --------- .../commons/lang3/time/FormatCache.java | 202 -- .../apache/commons/lang3/time/StopWatch.java | 382 --- .../apache/commons/lang3/time/package.html | 23 - .../commons/lang3/tuple/MutablePair.java | 123 - 83 files changed, 40 insertions(+), 29716 deletions(-) delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/AnnotationUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/BitField.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/BooleanUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/CharEncoding.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/CharRange.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/CharSet.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/CharSetUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/EnumUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/LocaleUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/RandomStringUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/Range.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationException.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/StringEscapeUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/builder/StandardToStringStyle.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BackgroundInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BasicThreadFactory.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentException.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentRuntimeException.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConstantInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/LazyInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/TimedSemaphore.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/package.html delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventListenerSupport.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/event/package.html delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedException.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedRuntimeException.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/exception/DefaultExceptionContext.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionContext.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/math/Fraction.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/math/IEEE754rUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/math/NumberUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/math/package.html delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableBoolean.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableByte.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableDouble.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableFloat.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableLong.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableObject.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableShort.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/ConstructorUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/FieldUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/TypeUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/CompositeFormat.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/ExtendedMessageFormat.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormatFactory.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormattableUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrBuilder.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrLookup.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrMatcher.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrSubstitutor.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrTokenizer.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/WordUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/package.html delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/AggregateTranslator.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CodePointTranslator.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/EntityArrays.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/LookupTranslator.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityEscaper.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/OctalUnescaper.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/UnicodeEscaper.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/UnicodeUnescaper.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/package.html delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/time/DateFormatUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/time/DateUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/time/DurationFormatUtils.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/time/FastDateFormat.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/time/FormatCache.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/time/StopWatch.java delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/time/package.html delete mode 100644 lib/apache-commons-lang/external/org/apache/commons/lang3/tuple/MutablePair.java diff --git a/assets/VERSION b/assets/VERSION index e85087af..f5c89552 100644 --- a/assets/VERSION +++ b/assets/VERSION @@ -1 +1 @@ -31 +32 diff --git a/lib/apache-commons-lang/MODIFICATIONS.txt b/lib/apache-commons-lang/MODIFICATIONS.txt index 3ac474de..d6f4e370 100644 --- a/lib/apache-commons-lang/MODIFICATIONS.txt +++ b/lib/apache-commons-lang/MODIFICATIONS.txt @@ -3,4 +3,42 @@ as downloaded from http://commons.apache.org/lang/download_lang.cgi, except for these modifications: - Class MemberUtils changed to public - Method compareParameterTypes in MemberUtils changed to public -- Prefix "external." for packages to avoid conflicts with other apps \ No newline at end of file +- Prefix "external." for packages to avoid conflicts with other apps +- Removed unused sub-packages for smaller file size: +concurrent/ +event/ +math/ +text/ +time/ +- Removed unused classes for smaller file size: +AnnotationUtils.java +BitField.java +BooleanUtils.java +CharEncoding.java +CharRange.java +CharSet.java +CharSetUtils.java +EnumUtils.java +LocaleUtils.java +RandomStringUtils.java +Range.java +SerializationException.java +SerializationUtils.java +StringEscapeUtils.java +builder/StandardToStringStyle.java +exception/ContextedException.java +exception/ContextedRuntimeException.java +exception/DefaultExceptionContext.java +exception/ExceptionContext.java +exception/ExceptionUtils.java +mutable/MutableBoolean.java +mutable/MutableByte.java +mutable/MutableDouble.java +mutable/MutableFloat.java +mutable/MutableLong.java +mutable/MutableObject.java +mutable/MutableShort.java +reflect/ConstructorUtils.java +reflect/FieldUtils.java +reflect/TypeUtils.java +tuple/MutablePair.java diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/AnnotationUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/AnnotationUtils.java deleted file mode 100644 index 57fa3922..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/AnnotationUtils.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; - -import external.org.apache.commons.lang3.builder.ToStringBuilder; -import external.org.apache.commons.lang3.builder.ToStringStyle; - -/** - *

Helper methods for working with {@link Annotation} instances.

- * - *

This class contains various utility methods that make working with - * annotations simpler.

- * - *

{@link Annotation} instances are always proxy objects; unfortunately - * dynamic proxies cannot be depended upon to know how to implement certain - * methods in the same manner as would be done by "natural" {@link Annotation}s. - * The methods presented in this class can be used to avoid that possibility. It - * is of course also possible for dynamic proxies to actually delegate their - * e.g. {@link Annotation#equals(Object)}/{@link Annotation#hashCode()}/ - * {@link Annotation#toString()} implementations to {@link AnnotationUtils}.

- * - *

#ThreadSafe#

- * - * @since 3.0 - * @version $Id: AnnotationUtils.java 1083850 2011-03-21 15:59:10Z mbenson $ - */ -public class AnnotationUtils { - - /** - * A style that prints annotations as recommended. - */ - private static final ToStringStyle TO_STRING_STYLE = new ToStringStyle() { - /** Serialization version */ - private static final long serialVersionUID = 1L; - - { - setDefaultFullDetail(true); - setArrayContentDetail(true); - setUseClassName(true); - setUseShortClassName(true); - setUseIdentityHashCode(false); - setContentStart("("); - setContentEnd(")"); - setFieldSeparator(", "); - setArrayStart("["); - setArrayEnd("]"); - } - - /** - * {@inheritDoc} - */ - @Override - protected String getShortClassName(java.lang.Class cls) { - Class annotationType = null; - for (Class iface : ClassUtils.getAllInterfaces(cls)) { - if (Annotation.class.isAssignableFrom(iface)) { - @SuppressWarnings("unchecked") - //because we just checked the assignability - Class found = (Class) iface; - annotationType = found; - break; - } - } - return new StringBuilder(annotationType == null ? "" : annotationType.getName()) - .insert(0, '@').toString(); - } - - /** - * {@inheritDoc} - */ - @Override - protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { - if (value instanceof Annotation) { - value = AnnotationUtils.toString((Annotation) value); - } - super.appendDetail(buffer, fieldName, value); - } - - }; - - /** - *

{@code AnnotationUtils} instances should NOT be constructed in - * standard programming. Instead, the class should be used statically.

- * - *

This constructor is public to permit tools that require a JavaBean - * instance to operate.

- */ - public AnnotationUtils() { - } - - //----------------------------------------------------------------------- - /** - *

Checks if two annotations are equal using the criteria for equality - * presented in the {@link Annotation#equals(Object)} API docs.

- * - * @param a1 the first Annotation to compare, {@code null} returns - * {@code false} unless both are {@code null} - * @param a2 the second Annotation to compare, {@code null} returns - * {@code false} unless both are {@code null} - * @return {@code true} if the two annotations are {@code equal} or both - * {@code null} - */ - public static boolean equals(Annotation a1, Annotation a2) { - if (a1 == a2) { - return true; - } - if (a1 == null || a2 == null) { - return false; - } - Class type = a1.annotationType(); - Class type2 = a2.annotationType(); - Validate.notNull(type, "Annotation %s with null annotationType()", a1); - Validate.notNull(type2, "Annotation %s with null annotationType()", a2); - if (!type.equals(type2)) { - return false; - } - try { - for (Method m : type.getDeclaredMethods()) { - if (m.getParameterTypes().length == 0 - && isValidAnnotationMemberType(m.getReturnType())) { - Object v1 = m.invoke(a1); - Object v2 = m.invoke(a2); - if (!memberEquals(m.getReturnType(), v1, v2)) { - return false; - } - } - } - } catch (IllegalAccessException ex) { - return false; - } catch (InvocationTargetException ex) { - return false; - } - return true; - } - - /** - *

Generate a hash code for the given annotation using the algorithm - * presented in the {@link Annotation#hashCode()} API docs.

- * - * @param a the Annotation for a hash code calculation is desired, not - * {@code null} - * @return the calculated hash code - * @throws RuntimeException if an {@code Exception} is encountered during - * annotation member access - * @throws IllegalStateException if an annotation method invocation returns - * {@code null} - */ - public static int hashCode(Annotation a) { - int result = 0; - Class type = a.annotationType(); - for (Method m : type.getDeclaredMethods()) { - try { - Object value = m.invoke(a); - if (value == null) { - throw new IllegalStateException( - String.format("Annotation method %s returned null", m)); - } - result += hashMember(m.getName(), value); - } catch (RuntimeException ex) { - throw ex; - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - return result; - } - - /** - *

Generate a string representation of an Annotation, as suggested by - * {@link Annotation#toString()}.

- * - * @param a the annotation of which a string representation is desired - * @return the standard string representation of an annotation, not - * {@code null} - */ - public static String toString(final Annotation a) { - ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE); - for (Method m : a.annotationType().getDeclaredMethods()) { - if (m.getParameterTypes().length > 0) { - continue; //wtf? - } - try { - builder.append(m.getName(), m.invoke(a)); - } catch (RuntimeException ex) { - throw ex; - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - return builder.build(); - } - - /** - *

Checks if the specified type is permitted as an annotation member.

- * - *

The Java language specification only permits certain types to be used - * in annotations. These include {@link String}, {@link Class}, primitive - * types, {@link Annotation}, {@link Enum}, and single-dimensional arrays of - * these types.

- * - * @param type the type to check, {@code null} - * @return {@code true} if the type is a valid type to use in an annotation - */ - public static boolean isValidAnnotationMemberType(Class type) { - if (type == null) { - return false; - } - if (type.isArray()) { - type = type.getComponentType(); - } - return type.isPrimitive() || type.isEnum() || type.isAnnotation() - || String.class.equals(type) || Class.class.equals(type); - } - - //besides modularity, this has the advantage of autoboxing primitives: - /** - * Helper method for generating a hash code for a member of an annotation. - * - * @param name the name of the member - * @param value the value of the member - * @return a hash code for this member - */ - private static int hashMember(String name, Object value) { - int part1 = name.hashCode() * 127; - if (value.getClass().isArray()) { - return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value); - } - if (value instanceof Annotation) { - return part1 ^ hashCode((Annotation) value); - } - return part1 ^ value.hashCode(); - } - - /** - * Helper method for checking whether two objects of the given type are - * equal. This method is used to compare the parameters of two annotation - * instances. - * - * @param type the type of the objects to be compared - * @param o1 the first object - * @param o2 the second object - * @return a flag whether these objects are equal - */ - private static boolean memberEquals(Class type, Object o1, Object o2) { - if (o1 == o2) { - return true; - } - if (o1 == null || o2 == null) { - return false; - } - if (type.isArray()) { - return arrayMemberEquals(type.getComponentType(), o1, o2); - } - if (type.isAnnotation()) { - return equals((Annotation) o1, (Annotation) o2); - } - return o1.equals(o2); - } - - /** - * Helper method for comparing two objects of an array type. - * - * @param componentType the component type of the array - * @param o1 the first object - * @param o2 the second object - * @return a flag whether these objects are equal - */ - private static boolean arrayMemberEquals(Class componentType, Object o1, Object o2) { - if (componentType.isAnnotation()) { - return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2); - } - if (componentType.equals(Byte.TYPE)) { - return Arrays.equals((byte[]) o1, (byte[]) o2); - } - if (componentType.equals(Short.TYPE)) { - return Arrays.equals((short[]) o1, (short[]) o2); - } - if (componentType.equals(Integer.TYPE)) { - return Arrays.equals((int[]) o1, (int[]) o2); - } - if (componentType.equals(Character.TYPE)) { - return Arrays.equals((char[]) o1, (char[]) o2); - } - if (componentType.equals(Long.TYPE)) { - return Arrays.equals((long[]) o1, (long[]) o2); - } - if (componentType.equals(Float.TYPE)) { - return Arrays.equals((float[]) o1, (float[]) o2); - } - if (componentType.equals(Double.TYPE)) { - return Arrays.equals((double[]) o1, (double[]) o2); - } - if (componentType.equals(Boolean.TYPE)) { - return Arrays.equals((boolean[]) o1, (boolean[]) o2); - } - return Arrays.equals((Object[]) o1, (Object[]) o2); - } - - /** - * Helper method for comparing two arrays of annotations. - * - * @param a1 the first array - * @param a2 the second array - * @return a flag whether these arrays are equal - */ - private static boolean annotationArrayMemberEquals(Annotation[] a1, Annotation[] a2) { - if (a1.length != a2.length) { - return false; - } - for (int i = 0; i < a1.length; i++) { - if (!equals(a1[i], a2[i])) { - return false; - } - } - return true; - } - - /** - * Helper method for generating a hash code for an array. - * - * @param componentType the component type of the array - * @param o the array - * @return a hash code for the specified array - */ - private static int arrayMemberHash(Class componentType, Object o) { - if (componentType.equals(Byte.TYPE)) { - return Arrays.hashCode((byte[]) o); - } - if (componentType.equals(Short.TYPE)) { - return Arrays.hashCode((short[]) o); - } - if (componentType.equals(Integer.TYPE)) { - return Arrays.hashCode((int[]) o); - } - if (componentType.equals(Character.TYPE)) { - return Arrays.hashCode((char[]) o); - } - if (componentType.equals(Long.TYPE)) { - return Arrays.hashCode((long[]) o); - } - if (componentType.equals(Float.TYPE)) { - return Arrays.hashCode((float[]) o); - } - if (componentType.equals(Double.TYPE)) { - return Arrays.hashCode((double[]) o); - } - if (componentType.equals(Boolean.TYPE)) { - return Arrays.hashCode((boolean[]) o); - } - return Arrays.hashCode((Object[]) o); - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/BitField.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/BitField.java deleted file mode 100644 index 1ba2153d..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/BitField.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -/** - *

Operations on bit-mapped fields.

- * - * @since 2.0 - * @version $Id: BitField.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class BitField { - - private final int _mask; - private final int _shift_count; - - /** - *

Creates a BitField instance.

- * - * @param mask the mask specifying which bits apply to this - * BitField. Bits that are set in this mask are the bits - * that this BitField operates on - */ - public BitField(int mask) { - _mask = mask; - int count = 0; - int bit_pattern = mask; - - if (bit_pattern != 0) { - while ((bit_pattern & 1) == 0) { - count++; - bit_pattern >>= 1; - } - } - _shift_count = count; - } - - /** - *

Obtains the value for the specified BitField, appropriately - * shifted right.

- * - *

Many users of a BitField will want to treat the specified - * bits as an int value, and will not want to be aware that the - * value is stored as a BitField (and so shifted left so many - * bits).

- * - * @see #setValue(int,int) - * @param holder the int data containing the bits we're interested - * in - * @return the selected bits, shifted right appropriately - */ - public int getValue(int holder) { - return getRawValue(holder) >> _shift_count; - } - - /** - *

Obtains the value for the specified BitField, appropriately - * shifted right, as a short.

- * - *

Many users of a BitField will want to treat the specified - * bits as an int value, and will not want to be aware that the - * value is stored as a BitField (and so shifted left so many - * bits).

- * - * @see #setShortValue(short,short) - * @param holder the short data containing the bits we're - * interested in - * @return the selected bits, shifted right appropriately - */ - public short getShortValue(short holder) { - return (short) getValue(holder); - } - - /** - *

Obtains the value for the specified BitField, unshifted.

- * - * @param holder the int data containing the bits we're - * interested in - * @return the selected bits - */ - public int getRawValue(int holder) { - return holder & _mask; - } - - /** - *

Obtains the value for the specified BitField, unshifted.

- * - * @param holder the short data containing the bits we're - * interested in - * @return the selected bits - */ - public short getShortRawValue(short holder) { - return (short) getRawValue(holder); - } - - /** - *

Returns whether the field is set or not.

- * - *

This is most commonly used for a single-bit field, which is - * often used to represent a boolean value; the results of using - * it for a multi-bit field is to determine whether *any* of its - * bits are set.

- * - * @param holder the int data containing the bits we're interested - * in - * @return {@code true} if any of the bits are set, - * else {@code false} - */ - public boolean isSet(int holder) { - return (holder & _mask) != 0; - } - - /** - *

Returns whether all of the bits are set or not.

- * - *

This is a stricter test than {@link #isSet(int)}, - * in that all of the bits in a multi-bit set must be set - * for this method to return {@code true}.

- * - * @param holder the int data containing the bits we're - * interested in - * @return {@code true} if all of the bits are set, - * else {@code false} - */ - public boolean isAllSet(int holder) { - return (holder & _mask) == _mask; - } - - /** - *

Replaces the bits with new values.

- * - * @see #getValue(int) - * @param holder the int data containing the bits we're - * interested in - * @param value the new value for the specified bits - * @return the value of holder with the bits from the value - * parameter replacing the old bits - */ - public int setValue(int holder, int value) { - return (holder & ~_mask) | ((value << _shift_count) & _mask); - } - - /** - *

Replaces the bits with new values.

- * - * @see #getShortValue(short) - * @param holder the short data containing the bits we're - * interested in - * @param value the new value for the specified bits - * @return the value of holder with the bits from the value - * parameter replacing the old bits - */ - public short setShortValue(short holder, short value) { - return (short) setValue(holder, value); - } - - /** - *

Clears the bits.

- * - * @param holder the int data containing the bits we're - * interested in - * @return the value of holder with the specified bits cleared - * (set to {@code 0}) - */ - public int clear(int holder) { - return holder & ~_mask; - } - - /** - *

Clears the bits.

- * - * @param holder the short data containing the bits we're - * interested in - * @return the value of holder with the specified bits cleared - * (set to {@code 0}) - */ - public short clearShort(short holder) { - return (short) clear(holder); - } - - /** - *

Clears the bits.

- * - * @param holder the byte data containing the bits we're - * interested in - * - * @return the value of holder with the specified bits cleared - * (set to {@code 0}) - */ - public byte clearByte(byte holder) { - return (byte) clear(holder); - } - - /** - *

Sets the bits.

- * - * @param holder the int data containing the bits we're - * interested in - * @return the value of holder with the specified bits set - * to {@code 1} - */ - public int set(int holder) { - return holder | _mask; - } - - /** - *

Sets the bits.

- * - * @param holder the short data containing the bits we're - * interested in - * @return the value of holder with the specified bits set - * to {@code 1} - */ - public short setShort(short holder) { - return (short) set(holder); - } - - /** - *

Sets the bits.

- * - * @param holder the byte data containing the bits we're - * interested in - * - * @return the value of holder with the specified bits set - * to {@code 1} - */ - public byte setByte(byte holder) { - return (byte) set(holder); - } - - /** - *

Sets a boolean BitField.

- * - * @param holder the int data containing the bits we're - * interested in - * @param flag indicating whether to set or clear the bits - * @return the value of holder with the specified bits set or - * cleared - */ - public int setBoolean(int holder, boolean flag) { - return flag ? set(holder) : clear(holder); - } - - /** - *

Sets a boolean BitField.

- * - * @param holder the short data containing the bits we're - * interested in - * @param flag indicating whether to set or clear the bits - * @return the value of holder with the specified bits set or - * cleared - */ - public short setShortBoolean(short holder, boolean flag) { - return flag ? setShort(holder) : clearShort(holder); - } - - /** - *

Sets a boolean BitField.

- * - * @param holder the byte data containing the bits we're - * interested in - * @param flag indicating whether to set or clear the bits - * @return the value of holder with the specified bits set or - * cleared - */ - public byte setByteBoolean(byte holder, boolean flag) { - return flag ? setByte(holder) : clearByte(holder); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/BooleanUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/BooleanUtils.java deleted file mode 100644 index 795a6c52..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/BooleanUtils.java +++ /dev/null @@ -1,1082 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import external.org.apache.commons.lang3.math.NumberUtils; - -/** - *

Operations on boolean primitives and Boolean objects.

- * - *

This class tries to handle {@code null} input gracefully. - * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

- * - *

#ThreadSafe#

- * @since 2.0 - * @version $Id: BooleanUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class BooleanUtils { - - /** - *

{@code BooleanUtils} instances should NOT be constructed in standard programming. - * Instead, the class should be used as {@code BooleanUtils.negate(true);}.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- */ - public BooleanUtils() { - super(); - } - - // Boolean utilities - //-------------------------------------------------------------------------- - /** - *

Negates the specified boolean.

- * - *

If {@code null} is passed in, {@code null} will be returned.

- * - *

NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.

- * - *
-     *   BooleanUtils.negate(Boolean.TRUE)  = Boolean.FALSE;
-     *   BooleanUtils.negate(Boolean.FALSE) = Boolean.TRUE;
-     *   BooleanUtils.negate(null)          = null;
-     * 
- * - * @param bool the Boolean to negate, may be null - * @return the negated Boolean, or {@code null} if {@code null} input - */ - public static Boolean negate(Boolean bool) { - if (bool == null) { - return null; - } - return bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE; - } - - // boolean Boolean methods - //----------------------------------------------------------------------- - /** - *

Checks if a {@code Boolean} value is {@code true}, - * handling {@code null} by returning {@code false}.

- * - *
-     *   BooleanUtils.isTrue(Boolean.TRUE)  = true
-     *   BooleanUtils.isTrue(Boolean.FALSE) = false
-     *   BooleanUtils.isTrue(null)          = false
-     * 
- * - * @param bool the boolean to check, null returns {@code false} - * @return {@code true} only if the input is non-null and true - * @since 2.1 - */ - public static boolean isTrue(Boolean bool) { - return Boolean.TRUE.equals(bool); - } - - /** - *

Checks if a {@code Boolean} value is not {@code true}, - * handling {@code null} by returning {@code true}.

- * - *
-     *   BooleanUtils.isNotTrue(Boolean.TRUE)  = false
-     *   BooleanUtils.isNotTrue(Boolean.FALSE) = true
-     *   BooleanUtils.isNotTrue(null)          = true
-     * 
- * - * @param bool the boolean to check, null returns {@code true} - * @return {@code true} if the input is null or false - * @since 2.3 - */ - public static boolean isNotTrue(Boolean bool) { - return !isTrue(bool); - } - - /** - *

Checks if a {@code Boolean} value is {@code false}, - * handling {@code null} by returning {@code false}.

- * - *
-     *   BooleanUtils.isFalse(Boolean.TRUE)  = false
-     *   BooleanUtils.isFalse(Boolean.FALSE) = true
-     *   BooleanUtils.isFalse(null)          = false
-     * 
- * - * @param bool the boolean to check, null returns {@code false} - * @return {@code true} only if the input is non-null and false - * @since 2.1 - */ - public static boolean isFalse(Boolean bool) { - return Boolean.FALSE.equals(bool); - } - - /** - *

Checks if a {@code Boolean} value is not {@code false}, - * handling {@code null} by returning {@code true}.

- * - *
-     *   BooleanUtils.isNotFalse(Boolean.TRUE)  = true
-     *   BooleanUtils.isNotFalse(Boolean.FALSE) = false
-     *   BooleanUtils.isNotFalse(null)          = true
-     * 
- * - * @param bool the boolean to check, null returns {@code true} - * @return {@code true} if the input is null or true - * @since 2.3 - */ - public static boolean isNotFalse(Boolean bool) { - return !isFalse(bool); - } - - //----------------------------------------------------------------------- - /** - *

Converts a Boolean to a boolean handling {@code null} - * by returning {@code false}.

- * - *
-     *   BooleanUtils.toBoolean(Boolean.TRUE)  = true
-     *   BooleanUtils.toBoolean(Boolean.FALSE) = false
-     *   BooleanUtils.toBoolean(null)          = false
-     * 
- * - * @param bool the boolean to convert - * @return {@code true} or {@code false}, {@code null} returns {@code false} - */ - public static boolean toBoolean(Boolean bool) { - return bool != null && bool.booleanValue(); - } - - /** - *

Converts a Boolean to a boolean handling {@code null}.

- * - *
-     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false) = true
-     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true) = false
-     *   BooleanUtils.toBooleanDefaultIfNull(null, true)          = true
-     * 
- * - * @param bool the boolean to convert - * @param valueIfNull the boolean value to return if {@code null} - * @return {@code true} or {@code false} - */ - public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) { - if (bool == null) { - return valueIfNull; - } - return bool.booleanValue(); - } - - // Integer to Boolean methods - //----------------------------------------------------------------------- - /** - *

Converts an int to a boolean using the convention that {@code zero} - * is {@code false}.

- * - *
-     *   BooleanUtils.toBoolean(0) = false
-     *   BooleanUtils.toBoolean(1) = true
-     *   BooleanUtils.toBoolean(2) = true
-     * 
- * - * @param value the int to convert - * @return {@code true} if non-zero, {@code false} - * if zero - */ - public static boolean toBoolean(int value) { - return value != 0; - } - - /** - *

Converts an int to a Boolean using the convention that {@code zero} - * is {@code false}.

- * - *
-     *   BooleanUtils.toBoolean(0) = Boolean.FALSE
-     *   BooleanUtils.toBoolean(1) = Boolean.TRUE
-     *   BooleanUtils.toBoolean(2) = Boolean.TRUE
-     * 
- * - * @param value the int to convert - * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, - * {@code null} if {@code null} - */ - public static Boolean toBooleanObject(int value) { - return value == 0 ? Boolean.FALSE : Boolean.TRUE; - } - - /** - *

Converts an Integer to a Boolean using the convention that {@code zero} - * is {@code false}.

- * - *

{@code null} will be converted to {@code null}.

- * - *

NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.

- * - *
-     *   BooleanUtils.toBoolean(Integer.valueOf(0))    = Boolean.FALSE
-     *   BooleanUtils.toBoolean(Integer.valueOf(1))    = Boolean.TRUE
-     *   BooleanUtils.toBoolean(Integer.valueOf(null)) = null
-     * 
- * - * @param value the Integer to convert - * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, - * {@code null} if {@code null} input - */ - public static Boolean toBooleanObject(Integer value) { - if (value == null) { - return null; - } - return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE; - } - - /** - *

Converts an int to a boolean specifying the conversion values.

- * - *
-     *   BooleanUtils.toBoolean(0, 1, 0) = false
-     *   BooleanUtils.toBoolean(1, 1, 0) = true
-     *   BooleanUtils.toBoolean(2, 1, 2) = false
-     *   BooleanUtils.toBoolean(2, 2, 0) = true
-     * 
- * - * @param value the Integer to convert - * @param trueValue the value to match for {@code true} - * @param falseValue the value to match for {@code false} - * @return {@code true} or {@code false} - * @throws IllegalArgumentException if no match - */ - public static boolean toBoolean(int value, int trueValue, int falseValue) { - if (value == trueValue) { - return true; - } - if (value == falseValue) { - return false; - } - // no match - throw new IllegalArgumentException("The Integer did not match either specified value"); - } - - /** - *

Converts an Integer to a boolean specifying the conversion values.

- * - *
-     *   BooleanUtils.toBoolean(Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0)) = false
-     *   BooleanUtils.toBoolean(Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(0)) = true
-     *   BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2)) = false
-     *   BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(2), Integer.valueOf(0)) = true
-     *   BooleanUtils.toBoolean(null, null, Integer.valueOf(0))                     = true
-     * 
- * - * @param value the Integer to convert - * @param trueValue the value to match for {@code true}, may be {@code null} - * @param falseValue the value to match for {@code false}, may be {@code null} - * @return {@code true} or {@code false} - * @throws IllegalArgumentException if no match - */ - public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) { - if (value == null) { - if (trueValue == null) { - return true; - } - if (falseValue == null) { - return false; - } - } else if (value.equals(trueValue)) { - return true; - } else if (value.equals(falseValue)) { - return false; - } - // no match - throw new IllegalArgumentException("The Integer did not match either specified value"); - } - - /** - *

Converts an int to a Boolean specifying the conversion values.

- * - *

NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.

- * - *
-     *   BooleanUtils.toBooleanObject(0, 0, 2, 3) = Boolean.TRUE
-     *   BooleanUtils.toBooleanObject(2, 1, 2, 3) = Boolean.FALSE
-     *   BooleanUtils.toBooleanObject(3, 1, 2, 3) = null
-     * 
- * - * @param value the Integer to convert - * @param trueValue the value to match for {@code true} - * @param falseValue the value to match for {@code false} - * @param nullValue the value to to match for {@code null} - * @return Boolean.TRUE, Boolean.FALSE, or {@code null} - * @throws IllegalArgumentException if no match - */ - public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) { - if (value == trueValue) { - return Boolean.TRUE; - } - if (value == falseValue) { - return Boolean.FALSE; - } - if (value == nullValue) { - return null; - } - // no match - throw new IllegalArgumentException("The Integer did not match any specified value"); - } - - /** - *

Converts an Integer to a Boolean specifying the conversion values.

- * - *

NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.

- * - *
-     *   BooleanUtils.toBooleanObject(Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(2), Integer.valueOf(3)) = Boolean.TRUE
-     *   BooleanUtils.toBooleanObject(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)) = Boolean.FALSE
-     *   BooleanUtils.toBooleanObject(Integer.valueOf(3), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)) = null
-     * 
- * - * @param value the Integer to convert - * @param trueValue the value to match for {@code true}, may be {@code null} - * @param falseValue the value to match for {@code false}, may be {@code null} - * @param nullValue the value to to match for {@code null}, may be {@code null} - * @return Boolean.TRUE, Boolean.FALSE, or {@code null} - * @throws IllegalArgumentException if no match - */ - public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) { - if (value == null) { - if (trueValue == null) { - return Boolean.TRUE; - } - if (falseValue == null) { - return Boolean.FALSE; - } - if (nullValue == null) { - return null; - } - } else if (value.equals(trueValue)) { - return Boolean.TRUE; - } else if (value.equals(falseValue)) { - return Boolean.FALSE; - } else if (value.equals(nullValue)) { - return null; - } - // no match - throw new IllegalArgumentException("The Integer did not match any specified value"); - } - - // Boolean to Integer methods - //----------------------------------------------------------------------- - /** - *

Converts a boolean to an int using the convention that - * {@code zero} is {@code false}.

- * - *
-     *   BooleanUtils.toInteger(true)  = 1
-     *   BooleanUtils.toInteger(false) = 0
-     * 
- * - * @param bool the boolean to convert - * @return one if {@code true}, zero if {@code false} - */ - public static int toInteger(boolean bool) { - return bool ? 1 : 0; - } - - /** - *

Converts a boolean to an Integer using the convention that - * {@code zero} is {@code false}.

- * - *
-     *   BooleanUtils.toIntegerObject(true)  = Integer.valueOf(1)
-     *   BooleanUtils.toIntegerObject(false) = Integer.valueOf(0)
-     * 
- * - * @param bool the boolean to convert - * @return one if {@code true}, zero if {@code false} - */ - public static Integer toIntegerObject(boolean bool) { - return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; - } - - /** - *

Converts a Boolean to a Integer using the convention that - * {@code zero} is {@code false}.

- * - *

{@code null} will be converted to {@code null}.

- * - *
-     *   BooleanUtils.toIntegerObject(Boolean.TRUE)  = Integer.valueOf(1)
-     *   BooleanUtils.toIntegerObject(Boolean.FALSE) = Integer.valueOf(0)
-     * 
- * - * @param bool the Boolean to convert - * @return one if Boolean.TRUE, zero if Boolean.FALSE, {@code null} if {@code null} - */ - public static Integer toIntegerObject(Boolean bool) { - if (bool == null) { - return null; - } - return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; - } - - /** - *

Converts a boolean to an int specifying the conversion values.

- * - *
-     *   BooleanUtils.toInteger(true, 1, 0)  = 1
-     *   BooleanUtils.toInteger(false, 1, 0) = 0
-     * 
- * - * @param bool the to convert - * @param trueValue the value to return if {@code true} - * @param falseValue the value to return if {@code false} - * @return the appropriate value - */ - public static int toInteger(boolean bool, int trueValue, int falseValue) { - return bool ? trueValue : falseValue; - } - - /** - *

Converts a Boolean to an int specifying the conversion values.

- * - *
-     *   BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2)  = 1
-     *   BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0
-     *   BooleanUtils.toInteger(null, 1, 0, 2)          = 2
-     * 
- * - * @param bool the Boolean to convert - * @param trueValue the value to return if {@code true} - * @param falseValue the value to return if {@code false} - * @param nullValue the value to return if {@code null} - * @return the appropriate value - */ - public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) { - if (bool == null) { - return nullValue; - } - return bool.booleanValue() ? trueValue : falseValue; - } - - /** - *

Converts a boolean to an Integer specifying the conversion values.

- * - *
-     *   BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0))  = Integer.valueOf(1)
-     *   BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0)
-     * 
- * - * @param bool the to convert - * @param trueValue the value to return if {@code true}, may be {@code null} - * @param falseValue the value to return if {@code false}, may be {@code null} - * @return the appropriate value - */ - public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) { - return bool ? trueValue : falseValue; - } - - /** - *

Converts a Boolean to an Integer specifying the conversion values.

- * - *
-     *   BooleanUtils.toIntegerObject(Boolean.TRUE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2))  = Integer.valueOf(1)
-     *   BooleanUtils.toIntegerObject(Boolean.FALSE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(0)
-     *   BooleanUtils.toIntegerObject(null, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2))          = Integer.valueOf(2)
-     * 
- * - * @param bool the Boolean to convert - * @param trueValue the value to return if {@code true}, may be {@code null} - * @param falseValue the value to return if {@code false}, may be {@code null} - * @param nullValue the value to return if {@code null}, may be {@code null} - * @return the appropriate value - */ - public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) { - if (bool == null) { - return nullValue; - } - return bool.booleanValue() ? trueValue : falseValue; - } - - // String to Boolean methods - //----------------------------------------------------------------------- - /** - *

Converts a String to a Boolean.

- * - *

{@code 'true'}, {@code 'on'} or {@code 'yes'} - * (case insensitive) will return {@code true}. - * {@code 'false'}, {@code 'off'} or {@code 'no'} - * (case insensitive) will return {@code false}. - * Otherwise, {@code null} is returned.

- * - *

NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.

- * - *
-     *   BooleanUtils.toBooleanObject(null)    = null
-     *   BooleanUtils.toBooleanObject("true")  = Boolean.TRUE
-     *   BooleanUtils.toBooleanObject("false") = Boolean.FALSE
-     *   BooleanUtils.toBooleanObject("on")    = Boolean.TRUE
-     *   BooleanUtils.toBooleanObject("ON")    = Boolean.TRUE
-     *   BooleanUtils.toBooleanObject("off")   = Boolean.FALSE
-     *   BooleanUtils.toBooleanObject("oFf")   = Boolean.FALSE
-     *   BooleanUtils.toBooleanObject("blue")  = null
-     * 
- * - * @param str the String to check - * @return the Boolean value of the string, {@code null} if no match or {@code null} input - */ - public static Boolean toBooleanObject(String str) { - // Previously used equalsIgnoreCase, which was fast for interned 'true'. - // Non interned 'true' matched 15 times slower. - // - // Optimisation provides same performance as before for interned 'true'. - // Similar performance for null, 'false', and other strings not length 2/3/4. - // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower. - if (str == "true") { - return Boolean.TRUE; - } - if (str == null) { - return null; - } - switch (str.length()) { - case 1: { - char ch0 = str.charAt(0); - if (ch0 == 'y' || ch0 == 'Y' || - ch0 == 't' || ch0 == 'T') { - return Boolean.TRUE; - } - if (ch0 == 'n' || ch0 == 'N' || - ch0 == 'f' || ch0 == 'F') { - return Boolean.FALSE; - } - break; - } - case 2: { - char ch0 = str.charAt(0); - char ch1 = str.charAt(1); - if ((ch0 == 'o' || ch0 == 'O') && - (ch1 == 'n' || ch1 == 'N') ) { - return Boolean.TRUE; - } - if ((ch0 == 'n' || ch0 == 'N') && - (ch1 == 'o' || ch1 == 'O') ) { - return Boolean.FALSE; - } - break; - } - case 3: { - char ch0 = str.charAt(0); - char ch1 = str.charAt(1); - char ch2 = str.charAt(2); - if ((ch0 == 'y' || ch0 == 'Y') && - (ch1 == 'e' || ch1 == 'E') && - (ch2 == 's' || ch2 == 'S') ) { - return Boolean.TRUE; - } - if ((ch0 == 'o' || ch0 == 'O') && - (ch1 == 'f' || ch1 == 'F') && - (ch2 == 'f' || ch2 == 'F') ) { - return Boolean.FALSE; - } - break; - } - case 4: { - char ch0 = str.charAt(0); - char ch1 = str.charAt(1); - char ch2 = str.charAt(2); - char ch3 = str.charAt(3); - if ((ch0 == 't' || ch0 == 'T') && - (ch1 == 'r' || ch1 == 'R') && - (ch2 == 'u' || ch2 == 'U') && - (ch3 == 'e' || ch3 == 'E') ) { - return Boolean.TRUE; - } - break; - } - case 5: { - char ch0 = str.charAt(0); - char ch1 = str.charAt(1); - char ch2 = str.charAt(2); - char ch3 = str.charAt(3); - char ch4 = str.charAt(4); - if ((ch0 == 'f' || ch0 == 'F') && - (ch1 == 'a' || ch1 == 'A') && - (ch2 == 'l' || ch2 == 'L') && - (ch3 == 's' || ch3 == 'S') && - (ch4 == 'e' || ch4 == 'E') ) { - return Boolean.FALSE; - } - break; - } - } - - return null; - } - - /** - *

Converts a String to a Boolean throwing an exception if no match.

- * - *

NOTE: This returns null and will throw a NullPointerException if autoboxed to a boolean.

- * - *
-     *   BooleanUtils.toBooleanObject("true", "true", "false", "null")  = Boolean.TRUE
-     *   BooleanUtils.toBooleanObject("false", "true", "false", "null") = Boolean.FALSE
-     *   BooleanUtils.toBooleanObject("null", "true", "false", "null")  = null
-     * 
- * - * @param str the String to check - * @param trueString the String to match for {@code true} (case sensitive), may be {@code null} - * @param falseString the String to match for {@code false} (case sensitive), may be {@code null} - * @param nullString the String to match for {@code null} (case sensitive), may be {@code null} - * @return the Boolean value of the string, {@code null} if either the String matches {@code nullString} - * or if {@code null} input and {@code nullString} is {@code null} - * @throws IllegalArgumentException if the String doesn't match - */ - public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) { - if (str == null) { - if (trueString == null) { - return Boolean.TRUE; - } - if (falseString == null) { - return Boolean.FALSE; - } - if (nullString == null) { - return null; - } - } else if (str.equals(trueString)) { - return Boolean.TRUE; - } else if (str.equals(falseString)) { - return Boolean.FALSE; - } else if (str.equals(nullString)) { - return null; - } - // no match - throw new IllegalArgumentException("The String did not match any specified value"); - } - - // String to boolean methods - //----------------------------------------------------------------------- - /** - *

Converts a String to a boolean (optimised for performance).

- * - *

{@code 'true'}, {@code 'on'} or {@code 'yes'} - * (case insensitive) will return {@code true}. Otherwise, - * {@code false} is returned.

- * - *

This method performs 4 times faster (JDK1.4) than - * {@code Boolean.valueOf(String)}. However, this method accepts - * 'on' and 'yes' as true values. - * - *

-     *   BooleanUtils.toBoolean(null)    = false
-     *   BooleanUtils.toBoolean("true")  = true
-     *   BooleanUtils.toBoolean("TRUE")  = true
-     *   BooleanUtils.toBoolean("tRUe")  = true
-     *   BooleanUtils.toBoolean("on")    = true
-     *   BooleanUtils.toBoolean("yes")   = true
-     *   BooleanUtils.toBoolean("false") = false
-     *   BooleanUtils.toBoolean("x gti") = false
-     * 
- * - * @param str the String to check - * @return the boolean value of the string, {@code false} if no match or the String is null - */ - public static boolean toBoolean(String str) { - return toBooleanObject(str) == Boolean.TRUE; - } - - /** - *

Converts a String to a Boolean throwing an exception if no match found.

- * - *
-     *   BooleanUtils.toBoolean("true", "true", "false")  = true
-     *   BooleanUtils.toBoolean("false", "true", "false") = false
-     * 
- * - * @param str the String to check - * @param trueString the String to match for {@code true} (case sensitive), may be {@code null} - * @param falseString the String to match for {@code false} (case sensitive), may be {@code null} - * @return the boolean value of the string - * @throws IllegalArgumentException if the String doesn't match - */ - public static boolean toBoolean(String str, String trueString, String falseString) { - if (str == trueString) { - return true; - } else if (str == falseString) { - return false; - } else if (str != null) { - if (str.equals(trueString)) { - return true; - } else if (str.equals(falseString)) { - return false; - } - } - // no match - throw new IllegalArgumentException("The String did not match either specified value"); - } - - // Boolean to String methods - //----------------------------------------------------------------------- - /** - *

Converts a Boolean to a String returning {@code 'true'}, - * {@code 'false'}, or {@code null}.

- * - *
-     *   BooleanUtils.toStringTrueFalse(Boolean.TRUE)  = "true"
-     *   BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false"
-     *   BooleanUtils.toStringTrueFalse(null)          = null;
-     * 
- * - * @param bool the Boolean to check - * @return {@code 'true'}, {@code 'false'}, or {@code null} - */ - public static String toStringTrueFalse(Boolean bool) { - return toString(bool, "true", "false", null); - } - - /** - *

Converts a Boolean to a String returning {@code 'on'}, - * {@code 'off'}, or {@code null}.

- * - *
-     *   BooleanUtils.toStringOnOff(Boolean.TRUE)  = "on"
-     *   BooleanUtils.toStringOnOff(Boolean.FALSE) = "off"
-     *   BooleanUtils.toStringOnOff(null)          = null;
-     * 
- * - * @param bool the Boolean to check - * @return {@code 'on'}, {@code 'off'}, or {@code null} - */ - public static String toStringOnOff(Boolean bool) { - return toString(bool, "on", "off", null); - } - - /** - *

Converts a Boolean to a String returning {@code 'yes'}, - * {@code 'no'}, or {@code null}.

- * - *
-     *   BooleanUtils.toStringYesNo(Boolean.TRUE)  = "yes"
-     *   BooleanUtils.toStringYesNo(Boolean.FALSE) = "no"
-     *   BooleanUtils.toStringYesNo(null)          = null;
-     * 
- * - * @param bool the Boolean to check - * @return {@code 'yes'}, {@code 'no'}, or {@code null} - */ - public static String toStringYesNo(Boolean bool) { - return toString(bool, "yes", "no", null); - } - - /** - *

Converts a Boolean to a String returning one of the input Strings.

- * - *
-     *   BooleanUtils.toString(Boolean.TRUE, "true", "false", null)   = "true"
-     *   BooleanUtils.toString(Boolean.FALSE, "true", "false", null)  = "false"
-     *   BooleanUtils.toString(null, "true", "false", null)           = null;
-     * 
- * - * @param bool the Boolean to check - * @param trueString the String to return if {@code true}, may be {@code null} - * @param falseString the String to return if {@code false}, may be {@code null} - * @param nullString the String to return if {@code null}, may be {@code null} - * @return one of the three input Strings - */ - public static String toString(Boolean bool, String trueString, String falseString, String nullString) { - if (bool == null) { - return nullString; - } - return bool.booleanValue() ? trueString : falseString; - } - - // boolean to String methods - //----------------------------------------------------------------------- - /** - *

Converts a boolean to a String returning {@code 'true'} - * or {@code 'false'}.

- * - *
-     *   BooleanUtils.toStringTrueFalse(true)   = "true"
-     *   BooleanUtils.toStringTrueFalse(false)  = "false"
-     * 
- * - * @param bool the Boolean to check - * @return {@code 'true'}, {@code 'false'}, or {@code null} - */ - public static String toStringTrueFalse(boolean bool) { - return toString(bool, "true", "false"); - } - - /** - *

Converts a boolean to a String returning {@code 'on'} - * or {@code 'off'}.

- * - *
-     *   BooleanUtils.toStringOnOff(true)   = "on"
-     *   BooleanUtils.toStringOnOff(false)  = "off"
-     * 
- * - * @param bool the Boolean to check - * @return {@code 'on'}, {@code 'off'}, or {@code null} - */ - public static String toStringOnOff(boolean bool) { - return toString(bool, "on", "off"); - } - - /** - *

Converts a boolean to a String returning {@code 'yes'} - * or {@code 'no'}.

- * - *
-     *   BooleanUtils.toStringYesNo(true)   = "yes"
-     *   BooleanUtils.toStringYesNo(false)  = "no"
-     * 
- * - * @param bool the Boolean to check - * @return {@code 'yes'}, {@code 'no'}, or {@code null} - */ - public static String toStringYesNo(boolean bool) { - return toString(bool, "yes", "no"); - } - - /** - *

Converts a boolean to a String returning one of the input Strings.

- * - *
-     *   BooleanUtils.toString(true, "true", "false")   = "true"
-     *   BooleanUtils.toString(false, "true", "false")  = "false"
-     * 
- * - * @param bool the Boolean to check - * @param trueString the String to return if {@code true}, may be {@code null} - * @param falseString the String to return if {@code false}, may be {@code null} - * @return one of the two input Strings - */ - public static String toString(boolean bool, String trueString, String falseString) { - return bool ? trueString : falseString; - } - - // logical operations - // ---------------------------------------------------------------------- - /** - *

Performs an and on a set of booleans.

- * - *
-     *   BooleanUtils.and(true, true)         = true
-     *   BooleanUtils.and(false, false)       = false
-     *   BooleanUtils.and(true, false)        = false
-     *   BooleanUtils.and(true, true, false)  = false
-     *   BooleanUtils.and(true, true, true)   = true
-     * 
- * - * @param array an array of {@code boolean}s - * @return {@code true} if the and is successful. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @since 3.0.1 - */ - public static boolean and(boolean... array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - for (boolean element : array) { - if (!element) { - return false; - } - } - return true; - } - - /** - *

Performs an and on an array of Booleans.

- * - *
-     *   BooleanUtils.and(Boolean.TRUE, Boolean.TRUE)                 = Boolean.TRUE
-     *   BooleanUtils.and(Boolean.FALSE, Boolean.FALSE)               = Boolean.FALSE
-     *   BooleanUtils.and(Boolean.TRUE, Boolean.FALSE)                = Boolean.FALSE
-     *   BooleanUtils.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE)   = Boolean.TRUE
-     *   BooleanUtils.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
-     *   BooleanUtils.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE)  = Boolean.FALSE
-     * 
- * - * @param array an array of {@code Boolean}s - * @return {@code true} if the and is successful. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @throws IllegalArgumentException if {@code array} contains a {@code null} - * @since 3.0.1 - */ - public static Boolean and(Boolean... array) { - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - try { - boolean[] primitive = ArrayUtils.toPrimitive(array); - return and(primitive) ? Boolean.TRUE : Boolean.FALSE; - } catch (NullPointerException ex) { - throw new IllegalArgumentException("The array must not contain any null elements"); - } - } - - /** - *

Performs an or on a set of booleans.

- * - *
-     *   BooleanUtils.or(true, true)          = true
-     *   BooleanUtils.or(false, false)        = false
-     *   BooleanUtils.or(true, false)         = true
-     *   BooleanUtils.or(true, true, false)   = true
-     *   BooleanUtils.or(true, true, true)    = true
-     *   BooleanUtils.or(false, false, false) = false
-     * 
- * - * @param array an array of {@code boolean}s - * @return {@code true} if the or is successful. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @since 3.0.1 - */ - public static boolean or(boolean... array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - for (boolean element : array) { - if (element) { - return true; - } - } - return false; - } - - /** - *

Performs an or on an array of Booleans.

- * - *
-     *   BooleanUtils.or(Boolean.TRUE, Boolean.TRUE)                  = Boolean.TRUE
-     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE)                = Boolean.FALSE
-     *   BooleanUtils.or(Boolean.TRUE, Boolean.FALSE)                 = Boolean.TRUE
-     *   BooleanUtils.or(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE)    = Boolean.TRUE
-     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE)  = Boolean.TRUE
-     *   BooleanUtils.or(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE)   = Boolean.TRUE
-     *   BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
-     * 
- * - * @param array an array of {@code Boolean}s - * @return {@code true} if the or is successful. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @throws IllegalArgumentException if {@code array} contains a {@code null} - * @since 3.0.1 - */ - public static Boolean or(Boolean... array) { - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - try { - boolean[] primitive = ArrayUtils.toPrimitive(array); - return or(primitive) ? Boolean.TRUE : Boolean.FALSE; - } catch (NullPointerException ex) { - throw new IllegalArgumentException("The array must not contain any null elements"); - } - } - - /** - *

Performs an xor on a set of booleans.

- * - *
-     *   BooleanUtils.xor(true, true)   = false
-     *   BooleanUtils.xor(false, false) = false
-     *   BooleanUtils.xor(true, false)  = true
-     *   BooleanUtils.xor(true, true)   = false
-     *   BooleanUtils.xor(false, false) = false
-     *   BooleanUtils.xor(true, false)  = true
-     * 
- * - * @param array an array of {@code boolean}s - * @return {@code true} if the xor is successful. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - */ - public static boolean xor(boolean... array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - - // Loops through array, comparing each item - int trueCount = 0; - for (boolean element : array) { - // If item is true, and trueCount is < 1, increments count - // Else, xor fails - if (element) { - if (trueCount < 1) { - trueCount++; - } else { - return false; - } - } - } - - // Returns true if there was exactly 1 true item - return trueCount == 1; - } - - /** - *

Performs an xor on an array of Booleans.

- * - *
-     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE })   = Boolean.FALSE
-     *   BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE
-     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })  = Boolean.TRUE
-     * 
- * - * @param array an array of {@code Boolean}s - * @return {@code true} if the xor is successful. - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty. - * @throws IllegalArgumentException if {@code array} contains a {@code null} - */ - public static Boolean xor(Boolean... array) { - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } - if (array.length == 0) { - throw new IllegalArgumentException("Array is empty"); - } - try { - boolean[] primitive = ArrayUtils.toPrimitive(array); - return xor(primitive) ? Boolean.TRUE : Boolean.FALSE; - } catch (NullPointerException ex) { - throw new IllegalArgumentException("The array must not contain any null elements"); - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharEncoding.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/CharEncoding.java deleted file mode 100644 index 9666dd20..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharEncoding.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package external.org.apache.commons.lang3; - -import java.nio.charset.Charset; -import java.nio.charset.IllegalCharsetNameException; - -/** - *

Character encoding names required of every implementation of the Java platform.

- * - *

According to JRE character - * encoding names:

- * - *

Every implementation of the Java platform is required to support the following character encodings. - * Consult the release documentation for your implementation to see if any other encodings are supported. - *

- * - * @see JRE character encoding names - * @since 2.1 - * @version $Id: CharEncoding.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class CharEncoding { - - /** - *

ISO Latin Alphabet #1, also known as ISO-LATIN-1.

- * - *

Every implementation of the Java platform is required to support this character encoding.

- */ - public static final String ISO_8859_1 = "ISO-8859-1"; - - /** - *

Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block - * of the Unicode character set.

- * - *

Every implementation of the Java platform is required to support this character encoding.

- */ - public static final String US_ASCII = "US-ASCII"; - - /** - *

Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial - * byte-order mark (either order accepted on input, big-endian used on output).

- * - *

Every implementation of the Java platform is required to support this character encoding.

- */ - public static final String UTF_16 = "UTF-16"; - - /** - *

Sixteen-bit Unicode Transformation Format, big-endian byte order.

- * - *

Every implementation of the Java platform is required to support this character encoding.

- */ - public static final String UTF_16BE = "UTF-16BE"; - - /** - *

Sixteen-bit Unicode Transformation Format, little-endian byte order.

- * - *

Every implementation of the Java platform is required to support this character encoding.

- */ - public static final String UTF_16LE = "UTF-16LE"; - - /** - *

Eight-bit Unicode Transformation Format.

- * - *

Every implementation of the Java platform is required to support this character encoding.

- */ - public static final String UTF_8 = "UTF-8"; - - //----------------------------------------------------------------------- - /** - *

Returns whether the named charset is supported.

- * - *

This is similar to - * java.nio.charset.Charset.isSupported(String) but handles more formats

- * - * @param name the name of the requested charset; may be either a canonical name or an alias, null returns false - * @return {@code true} if the charset is available in the current Java virtual machine - */ - public static boolean isSupported(String name) { - if (name == null) { - return false; - } - try { - return Charset.isSupported(name); - } catch (IllegalCharsetNameException ex) { - return false; - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharRange.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/CharRange.java deleted file mode 100644 index 55db6c6a..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharRange.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - *

A contiguous range of characters, optionally negated.

- * - *

Instances are immutable.

- * - *

#ThreadSafe#

- * @since 1.0 - * @version $Id: CharRange.java 1090427 2011-04-08 20:17:10Z bayard $ - */ -// TODO: This is no longer public and will be removed later as CharSet is moved -// to depend on Range. -final class CharRange implements Iterable, Serializable { - - /** - * Required for serialization support. Lang version 2.0. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 8270183163158333422L; - - /** The first character, inclusive, in the range. */ - private final char start; - /** The last character, inclusive, in the range. */ - private final char end; - /** True if the range is everything except the characters specified. */ - private final boolean negated; - - /** Cached toString. */ - private transient String iToString; - - /** - *

Constructs a {@code CharRange} over a set of characters, - * optionally negating the range.

- * - *

A negated range includes everything except that defined by the - * start and end characters.

- * - *

If start and end are in the wrong order, they are reversed. - * Thus {@code a-e} is the same as {@code e-a}.

- * - * @param start first character, inclusive, in this range - * @param end last character, inclusive, in this range - * @param negated true to express everything except the range - */ - private CharRange(char start, char end, boolean negated) { - super(); - if (start > end) { - char temp = start; - start = end; - end = temp; - } - - this.start = start; - this.end = end; - this.negated = negated; - } - - /** - *

Constructs a {@code CharRange} over a single character.

- * - * @param ch only character in this range - * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) - * @since 2.5 - */ - public static CharRange is(char ch) { - return new CharRange(ch, ch, false); - } - - /** - *

Constructs a negated {@code CharRange} over a single character.

- * - * @param ch only character in this range - * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) - * @since 2.5 - */ - public static CharRange isNot(char ch) { - return new CharRange(ch, ch, true); - } - - /** - *

Constructs a {@code CharRange} over a set of characters.

- * - * @param start first character, inclusive, in this range - * @param end last character, inclusive, in this range - * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) - * @since 2.5 - */ - public static CharRange isIn(char start, char end) { - return new CharRange(start, end, false); - } - - /** - *

Constructs a negated {@code CharRange} over a set of characters.

- * - * @param start first character, inclusive, in this range - * @param end last character, inclusive, in this range - * @return the new CharRange object - * @see CharRange#CharRange(char, char, boolean) - * @since 2.5 - */ - public static CharRange isNotIn(char start, char end) { - return new CharRange(start, end, true); - } - - // Accessors - //----------------------------------------------------------------------- - /** - *

Gets the start character for this character range.

- * - * @return the start char (inclusive) - */ - public char getStart() { - return this.start; - } - - /** - *

Gets the end character for this character range.

- * - * @return the end char (inclusive) - */ - public char getEnd() { - return this.end; - } - - /** - *

Is this {@code CharRange} negated.

- * - *

A negated range includes everything except that defined by the - * start and end characters.

- * - * @return {@code true} if negated - */ - public boolean isNegated() { - return negated; - } - - // Contains - //----------------------------------------------------------------------- - /** - *

Is the character specified contained in this range.

- * - * @param ch the character to check - * @return {@code true} if this range contains the input character - */ - public boolean contains(char ch) { - return (ch >= start && ch <= end) != negated; - } - - /** - *

Are all the characters of the passed in range contained in - * this range.

- * - * @param range the range to check against - * @return {@code true} if this range entirely contains the input range - * @throws IllegalArgumentException if {@code null} input - */ - public boolean contains(CharRange range) { - if (range == null) { - throw new IllegalArgumentException("The Range must not be null"); - } - if (negated) { - if (range.negated) { - return start >= range.start && end <= range.end; - } - return range.end < start || range.start > end; - } - if (range.negated) { - return start == 0 && end == Character.MAX_VALUE; - } - return start <= range.start && end >= range.end; - } - - // Basics - //----------------------------------------------------------------------- - /** - *

Compares two CharRange objects, returning true if they represent - * exactly the same range of characters defined in the same way.

- * - * @param obj the object to compare to - * @return true if equal - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof CharRange == false) { - return false; - } - CharRange other = (CharRange) obj; - return start == other.start && end == other.end && negated == other.negated; - } - - /** - *

Gets a hashCode compatible with the equals method.

- * - * @return a suitable hashCode - */ - @Override - public int hashCode() { - return 83 + start + 7 * end + (negated ? 1 : 0); - } - - /** - *

Gets a string representation of the character range.

- * - * @return string representation of this range - */ - @Override - public String toString() { - if (iToString == null) { - StringBuilder buf = new StringBuilder(4); - if (isNegated()) { - buf.append('^'); - } - buf.append(start); - if (start != end) { - buf.append('-'); - buf.append(end); - } - iToString = buf.toString(); - } - return iToString; - } - - // Expansions - //----------------------------------------------------------------------- - /** - *

Returns an iterator which can be used to walk through the characters described by this range.

- * - *

#NotThreadSafe# the iterator is not threadsafe

- * @return an iterator to the chars represented by this range - * @since 2.5 - */ - public Iterator iterator() { - return new CharacterIterator(this); - } - - /** - * Character {@link Iterator}. - *

#NotThreadSafe#

- */ - private static class CharacterIterator implements Iterator { - /** The current character */ - private char current; - - private final CharRange range; - private boolean hasNext; - - /** - * Construct a new iterator for the character range. - * - * @param r The character range - */ - private CharacterIterator(CharRange r) { - range = r; - hasNext = true; - - if (range.negated) { - if (range.start == 0) { - if (range.end == Character.MAX_VALUE) { - // This range is an empty set - hasNext = false; - } else { - current = (char) (range.end + 1); - } - } else { - current = 0; - } - } else { - current = range.start; - } - } - - /** - * Prepare the next character in the range. - */ - private void prepareNext() { - if (range.negated) { - if (current == Character.MAX_VALUE) { - hasNext = false; - } else if (current + 1 == range.start) { - if (range.end == Character.MAX_VALUE) { - hasNext = false; - } else { - current = (char) (range.end + 1); - } - } else { - current = (char) (current + 1); - } - } else if (current < range.end) { - current = (char) (current + 1); - } else { - hasNext = false; - } - } - - /** - * Has the iterator not reached the end character yet? - * - * @return {@code true} if the iterator has yet to reach the character date - */ - public boolean hasNext() { - return hasNext; - } - - /** - * Return the next character in the iteration - * - * @return {@code Character} for the next character - */ - public Character next() { - if (hasNext == false) { - throw new NoSuchElementException(); - } - char cur = current; - prepareNext(); - return Character.valueOf(cur); - } - - /** - * Always throws UnsupportedOperationException. - * - * @throws UnsupportedOperationException - * @see java.util.Iterator#remove() - */ - public void remove() { - throw new UnsupportedOperationException(); - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharSet.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/CharSet.java deleted file mode 100644 index b745ea34..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharSet.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - *

A set of characters.

- * - *

Instances are immutable, but instances of subclasses may not be.

- * - *

#ThreadSafe#

- * @since 1.0 - * @version $Id: CharSet.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class CharSet implements Serializable { - - /** - * Required for serialization support. Lang version 2.0. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 5947847346149275958L; - - /** - * A CharSet defining no characters. - * @since 2.0 - */ - public static final CharSet EMPTY = new CharSet((String) null); - - /** - * A CharSet defining ASCII alphabetic characters "a-zA-Z". - * @since 2.0 - */ - public static final CharSet ASCII_ALPHA = new CharSet("a-zA-Z"); - - /** - * A CharSet defining ASCII alphabetic characters "a-z". - * @since 2.0 - */ - public static final CharSet ASCII_ALPHA_LOWER = new CharSet("a-z"); - - /** - * A CharSet defining ASCII alphabetic characters "A-Z". - * @since 2.0 - */ - public static final CharSet ASCII_ALPHA_UPPER = new CharSet("A-Z"); - - /** - * A CharSet defining ASCII alphabetic characters "0-9". - * @since 2.0 - */ - public static final CharSet ASCII_NUMERIC = new CharSet("0-9"); - - /** - * A Map of the common cases used in the factory. - * Subclasses can add more common patterns if desired - * @since 2.0 - */ - protected static final Map COMMON = Collections.synchronizedMap(new HashMap()); - - static { - COMMON.put(null, EMPTY); - COMMON.put("", EMPTY); - COMMON.put("a-zA-Z", ASCII_ALPHA); - COMMON.put("A-Za-z", ASCII_ALPHA); - COMMON.put("a-z", ASCII_ALPHA_LOWER); - COMMON.put("A-Z", ASCII_ALPHA_UPPER); - COMMON.put("0-9", ASCII_NUMERIC); - } - - /** The set of CharRange objects. */ - private final Set set = Collections.synchronizedSet(new HashSet()); - - //----------------------------------------------------------------------- - /** - *

Factory method to create a new CharSet using a special syntax.

- * - *
    - *
  • {@code null} or empty string ("") - * - set containing no characters
  • - *
  • Single character, such as "a" - * - set containing just that character
  • - *
  • Multi character, such as "a-e" - * - set containing characters from one character to the other
  • - *
  • Negated, such as "^a" or "^a-e" - * - set containing all characters except those defined
  • - *
  • Combinations, such as "abe-g" - * - set containing all the characters from the individual sets
  • - *
- * - *

The matching order is:

- *
    - *
  1. Negated multi character range, such as "^a-e" - *
  2. Ordinary multi character range, such as "a-e" - *
  3. Negated single character, such as "^a" - *
  4. Ordinary single character, such as "a" - *
- *

Matching works left to right. Once a match is found the - * search starts again from the next character.

- * - *

If the same range is defined twice using the same syntax, only - * one range will be kept. - * Thus, "a-ca-c" creates only one range of "a-c".

- * - *

If the start and end of a range are in the wrong order, - * they are reversed. Thus "a-e" is the same as "e-a". - * As a result, "a-ee-a" would create only one range, - * as the "a-e" and "e-a" are the same.

- * - *

The set of characters represented is the union of the specified ranges.

- * - *

All CharSet objects returned by this method will be immutable.

- * - * @param setStrs Strings to merge into the set, may be null - * @return a CharSet instance - * @since 2.4 - */ - public static CharSet getInstance(String... setStrs) { - if (setStrs == null) { - return null; - } - if (setStrs.length == 1) { - CharSet common = COMMON.get(setStrs[0]); - if (common != null) { - return common; - } - } - return new CharSet(setStrs); - } - - //----------------------------------------------------------------------- - /** - *

Constructs a new CharSet using the set syntax. - * Each string is merged in with the set.

- * - * @param set Strings to merge into the initial set - * @throws NullPointerException if set is {@code null} - */ - protected CharSet(String... set) { - super(); - int sz = set.length; - for (int i = 0; i < sz; i++) { - add(set[i]); - } - } - - //----------------------------------------------------------------------- - /** - *

Add a set definition string to the {@code CharSet}.

- * - * @param str set definition string - */ - protected void add(String str) { - if (str == null) { - return; - } - - int len = str.length(); - int pos = 0; - while (pos < len) { - int remainder = len - pos; - if (remainder >= 4 && str.charAt(pos) == '^' && str.charAt(pos + 2) == '-') { - // negated range - set.add(CharRange.isNotIn(str.charAt(pos + 1), str.charAt(pos + 3))); - pos += 4; - } else if (remainder >= 3 && str.charAt(pos + 1) == '-') { - // range - set.add(CharRange.isIn(str.charAt(pos), str.charAt(pos + 2))); - pos += 3; - } else if (remainder >= 2 && str.charAt(pos) == '^') { - // negated char - set.add(CharRange.isNot(str.charAt(pos + 1))); - pos += 2; - } else { - // char - set.add(CharRange.is(str.charAt(pos))); - pos += 1; - } - } - } - - //----------------------------------------------------------------------- - /** - *

Gets the internal set as an array of CharRange objects.

- * - * @return an array of immutable CharRange objects - * @since 2.0 - */ -// NOTE: This is no longer public as CharRange is no longer a public class. -// It may be replaced when CharSet moves to Range. - /*public*/ CharRange[] getCharRanges() { - return set.toArray(new CharRange[set.size()]); - } - - //----------------------------------------------------------------------- - /** - *

Does the {@code CharSet} contain the specified - * character {@code ch}.

- * - * @param ch the character to check for - * @return {@code true} if the set contains the characters - */ - public boolean contains(char ch) { - for (CharRange range : set) { - if (range.contains(ch)) { - return true; - } - } - return false; - } - - // Basics - //----------------------------------------------------------------------- - /** - *

Compares two {@code CharSet} objects, returning true if they represent - * exactly the same set of characters defined in the same way.

- * - *

The two sets {@code abc} and {@code a-c} are not - * equal according to this method.

- * - * @param obj the object to compare to - * @return true if equal - * @since 2.0 - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof CharSet == false) { - return false; - } - CharSet other = (CharSet) obj; - return set.equals(other.set); - } - - /** - *

Gets a hash code compatible with the equals method.

- * - * @return a suitable hash code - * @since 2.0 - */ - @Override - public int hashCode() { - return 89 + set.hashCode(); - } - - /** - *

Gets a string representation of the set.

- * - * @return string representation of the set - */ - @Override - public String toString() { - return set.toString(); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharSetUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/CharSetUtils.java deleted file mode 100644 index 82946ac4..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/CharSetUtils.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -/** - *

Operations on {@code CharSet} instances.

- * - *

This class handles {@code null} input gracefully. - * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

- * - *

#ThreadSafe#

- * @see CharSet - * @since 1.0 - * @version $Id: CharSetUtils.java 1144916 2011-07-10 17:50:21Z ggregory $ - */ -public class CharSetUtils { - - /** - *

CharSetUtils instances should NOT be constructed in standard programming. - * Instead, the class should be used as {@code CharSetUtils.evaluateSet(null);}.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- */ - public CharSetUtils() { - super(); - } - - // Squeeze - //----------------------------------------------------------------------- - /** - *

Squeezes any repetitions of a character that is mentioned in the - * supplied set.

- * - *
-     * CharSetUtils.squeeze(null, *)        = null
-     * CharSetUtils.squeeze("", *)          = ""
-     * CharSetUtils.squeeze(*, null)        = *
-     * CharSetUtils.squeeze(*, "")          = *
-     * CharSetUtils.squeeze("hello", "k-p") = "helo"
-     * CharSetUtils.squeeze("hello", "a-e") = "hello"
-     * 
- * - * @see CharSet#getInstance(java.lang.String...) for set-syntax. - * @param str the string to squeeze, may be null - * @param set the character set to use for manipulation, may be null - * @return the modified String, {@code null} if null string input - */ - public static String squeeze(String str, String... set) { - if (StringUtils.isEmpty(str) || deepEmpty(set)) { - return str; - } - CharSet chars = CharSet.getInstance(set); - StringBuilder buffer = new StringBuilder(str.length()); - char[] chrs = str.toCharArray(); - int sz = chrs.length; - char lastChar = ' '; - char ch = ' '; - for (int i = 0; i < sz; i++) { - ch = chrs[i]; - // Compare with contains() last for performance. - if (ch == lastChar && i != 0 && chars.contains(ch)) { - continue; - } - buffer.append(ch); - lastChar = ch; - } - return buffer.toString(); - } - - // Count - //----------------------------------------------------------------------- - /** - *

Takes an argument in set-syntax, see evaluateSet, - * and returns the number of characters present in the specified string.

- * - *
-     * CharSetUtils.count(null, *)        = 0
-     * CharSetUtils.count("", *)          = 0
-     * CharSetUtils.count(*, null)        = 0
-     * CharSetUtils.count(*, "")          = 0
-     * CharSetUtils.count("hello", "k-p") = 3
-     * CharSetUtils.count("hello", "a-e") = 1
-     * 
- * - * @see CharSet#getInstance(java.lang.String...) for set-syntax. - * @param str String to count characters in, may be null - * @param set String[] set of characters to count, may be null - * @return the character count, zero if null string input - */ - public static int count(String str, String... set) { - if (StringUtils.isEmpty(str) || deepEmpty(set)) { - return 0; - } - CharSet chars = CharSet.getInstance(set); - int count = 0; - for (char c : str.toCharArray()) { - if (chars.contains(c)) { - count++; - } - } - return count; - } - - // Keep - //----------------------------------------------------------------------- - /** - *

Takes an argument in set-syntax, see evaluateSet, - * and keeps any of characters present in the specified string.

- * - *
-     * CharSetUtils.keep(null, *)        = null
-     * CharSetUtils.keep("", *)          = ""
-     * CharSetUtils.keep(*, null)        = ""
-     * CharSetUtils.keep(*, "")          = ""
-     * CharSetUtils.keep("hello", "hl")  = "hll"
-     * CharSetUtils.keep("hello", "le")  = "ell"
-     * 
- * - * @see CharSet#getInstance(java.lang.String...) for set-syntax. - * @param str String to keep characters from, may be null - * @param set String[] set of characters to keep, may be null - * @return the modified String, {@code null} if null string input - * @since 2.0 - */ - public static String keep(String str, String... set) { - if (str == null) { - return null; - } - if (str.length() == 0 || deepEmpty(set)) { - return ""; - } - return modify(str, set, true); - } - - // Delete - //----------------------------------------------------------------------- - /** - *

Takes an argument in set-syntax, see evaluateSet, - * and deletes any of characters present in the specified string.

- * - *
-     * CharSetUtils.delete(null, *)        = null
-     * CharSetUtils.delete("", *)          = ""
-     * CharSetUtils.delete(*, null)        = *
-     * CharSetUtils.delete(*, "")          = *
-     * CharSetUtils.delete("hello", "hl")  = "eo"
-     * CharSetUtils.delete("hello", "le")  = "ho"
-     * 
- * - * @see CharSet#getInstance(java.lang.String...) for set-syntax. - * @param str String to delete characters from, may be null - * @param set String[] set of characters to delete, may be null - * @return the modified String, {@code null} if null string input - */ - public static String delete(String str, String... set) { - if (StringUtils.isEmpty(str) || deepEmpty(set)) { - return str; - } - return modify(str, set, false); - } - - //----------------------------------------------------------------------- - /** - * Implementation of delete and keep - * - * @param str String to modify characters within - * @param set String[] set of characters to modify - * @param expect whether to evaluate on match, or non-match - * @return the modified String, not null - */ - private static String modify(String str, String[] set, boolean expect) { - CharSet chars = CharSet.getInstance(set); - StringBuilder buffer = new StringBuilder(str.length()); - char[] chrs = str.toCharArray(); - int sz = chrs.length; - for(int i=0; iUtility library to provide helper methods for Java enums.

- * - *

#ThreadSafe#

- * - * @since 3.0 - * @version $Id: EnumUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class EnumUtils { - - /** - * This constructor is public to permit tools that require a JavaBean - * instance to operate. - */ - public EnumUtils() { - } - - /** - *

Gets the {@code Map} of enums by name.

- * - *

This method is useful when you need a map of enums by name.

- * - * @param the type of the enumeration - * @param enumClass the class of the enum to query, not null - * @return the modifiable map of enum names to enums, never null - */ - public static > Map getEnumMap(Class enumClass) { - Map map = new LinkedHashMap(); - for (E e: enumClass.getEnumConstants()) { - map.put(e.name(), e); - } - return map; - } - - /** - *

Gets the {@code List} of enums.

- * - *

This method is useful when you need a list of enums rather than an array.

- * - * @param the type of the enumeration - * @param enumClass the class of the enum to query, not null - * @return the modifiable list of enums, never null - */ - public static > List getEnumList(Class enumClass) { - return new ArrayList(Arrays.asList(enumClass.getEnumConstants())); - } - - /** - *

Checks if the specified name is a valid enum for the class.

- * - *

This method differs from {@link Enum#valueOf} in that checks if the name is - * a valid enum without needing to catch the exception.

- * - * @param the type of the enumeration - * @param enumClass the class of the enum to query, not null - * @param enumName the enum name, null returns false - * @return true if the enum name is valid, otherwise false - */ - public static > boolean isValidEnum(Class enumClass, String enumName) { - if (enumName == null) { - return false; - } - try { - Enum.valueOf(enumClass, enumName); - return true; - } catch (IllegalArgumentException ex) { - return false; - } - } - - /** - *

Gets the enum for the class, returning {@code null} if not found.

- * - *

This method differs from {@link Enum#valueOf} in that it does not throw an exception - * for an invalid enum name.

- * - * @param the type of the enumeration - * @param enumClass the class of the enum to query, not null - * @param enumName the enum name, null returns null - * @return the enum, null if not found - */ - public static > E getEnum(Class enumClass, String enumName) { - if (enumName == null) { - return null; - } - try { - return Enum.valueOf(enumClass, enumName); - } catch (IllegalArgumentException ex) { - return null; - } - } - - /** - *

Creates a long bit vector representation of the given subset of an Enum.

- * - *

This generates a value that is usable by {@link EnumUtils#processBitVector}.

- * - *

Do not use this method if you have more than 64 values in your Enum, as this - * would create a value greater than a long can hold.

- * - * @param enumClass the class of the enum we are working with, not {@code null} - * @param values the values we want to convert, not {@code null} - * @param the type of the enumeration - * @return a long whose binary value represents the given set of enum values. - * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null} - * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values - * @since 3.0.1 - */ - public static > long generateBitVector(Class enumClass, Iterable values) { - checkBitVectorable(enumClass); - Validate.notNull(values); - long total = 0; - for (E constant : values) { - total |= 1 << constant.ordinal(); - } - return total; - } - - /** - *

Creates a long bit vector representation of the given array of Enum values.

- * - *

This generates a value that is usable by {@link EnumUtils#processBitVector}.

- * - *

Do not use this method if you have more than 64 values in your Enum, as this - * would create a value greater than a long can hold.

- * - * @param enumClass the class of the enum we are working with, not {@code null} - * @param values the values we want to convert, not {@code null} - * @param the type of the enumeration - * @return a long whose binary value represents the given set of enum values. - * @throws NullPointerException if {@code enumClass} or {@code values} is {@code null} - * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values - * @since 3.0.1 - */ - public static > long generateBitVector(Class enumClass, E... values) { - Validate.noNullElements(values); - return generateBitVector(enumClass, Arrays. asList(values)); - } - - /** - *

Convert a long value created by {@link EnumUtils#generateBitVector} into the set of - * enum values that it represents.

- * - *

If you store this value, beware any changes to the enum that would affect ordinal values.

- * @param enumClass the class of the enum we are working with, not {@code null} - * @param value the long value representation of a set of enum values - * @param the type of the enumeration - * @return a set of enum values - * @throws NullPointerException if {@code enumClass} is {@code null} - * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values - * @since 3.0.1 - */ - public static > EnumSet processBitVector(Class enumClass, long value) { - final E[] constants = checkBitVectorable(enumClass).getEnumConstants(); - final EnumSet results = EnumSet.noneOf(enumClass); - for (E constant : constants) { - if ((value & 1 << constant.ordinal()) != 0) { - results.add(constant); - } - } - return results; - } - - /** - * Validate that {@code enumClass} is compatible with representation in a {@code long}. - * @param the type of the enumeration - * @param enumClass to check - * @return {@code enumClass} - * @throws NullPointerException if {@code enumClass} is {@code null} - * @throws IllegalArgumentException if {@code enumClass} is not an enum class or has more than 64 values - * @since 3.0.1 - */ - private static > Class checkBitVectorable(Class enumClass) { - Validate.notNull(enumClass, "EnumClass must be defined."); - - final E[] constants = enumClass.getEnumConstants(); - Validate.isTrue(constants != null, "%s does not seem to be an Enum type", enumClass); - Validate.isTrue(constants.length <= Long.SIZE, "Cannot store %s %s values in %s bits", constants.length, - enumClass.getSimpleName(), Long.SIZE); - - return enumClass; - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/LocaleUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/LocaleUtils.java deleted file mode 100644 index 4a714ac0..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/LocaleUtils.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - *

Operations to assist when working with a {@link Locale}.

- * - *

This class tries to handle {@code null} input gracefully. - * An exception will not be thrown for a {@code null} input. - * Each method documents its behaviour in more detail.

- * - * @since 2.2 - * @version $Id: LocaleUtils.java 1090563 2011-04-09 11:00:10Z sebb $ - */ -public class LocaleUtils { - - /** Concurrent map of language locales by country. */ - private static final ConcurrentMap> cLanguagesByCountry = - new ConcurrentHashMap>(); - - /** Concurrent map of country locales by language. */ - private static final ConcurrentMap> cCountriesByLanguage = - new ConcurrentHashMap>(); - - /** - *

{@code LocaleUtils} instances should NOT be constructed in standard programming. - * Instead, the class should be used as {@code LocaleUtils.toLocale("en_GB");}.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- */ - public LocaleUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - *

Converts a String to a Locale.

- * - *

This method takes the string format of a locale and creates the - * locale object from it.

- * - *
-     *   LocaleUtils.toLocale("en")         = new Locale("en", "")
-     *   LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
-     *   LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
-     * 
- * - *

(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4. - * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't. - * Thus, the result from getVariant() may vary depending on your JDK.

- * - *

This method validates the input strictly. - * The language code must be lowercase. - * The country code must be uppercase. - * The separator must be an underscore. - * The length must be correct. - *

- * - * @param str the locale String to convert, null returns null - * @return a Locale, null if null input - * @throws IllegalArgumentException if the string is an invalid format - */ - public static Locale toLocale(String str) { - if (str == null) { - return null; - } - int len = str.length(); - if (len != 2 && len != 5 && len < 7) { - throw new IllegalArgumentException("Invalid locale format: " + str); - } - char ch0 = str.charAt(0); - char ch1 = str.charAt(1); - if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { - throw new IllegalArgumentException("Invalid locale format: " + str); - } - if (len == 2) { - return new Locale(str, ""); - } else { - if (str.charAt(2) != '_') { - throw new IllegalArgumentException("Invalid locale format: " + str); - } - char ch3 = str.charAt(3); - if (ch3 == '_') { - return new Locale(str.substring(0, 2), "", str.substring(4)); - } - char ch4 = str.charAt(4); - if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { - throw new IllegalArgumentException("Invalid locale format: " + str); - } - if (len == 5) { - return new Locale(str.substring(0, 2), str.substring(3, 5)); - } else { - if (str.charAt(5) != '_') { - throw new IllegalArgumentException("Invalid locale format: " + str); - } - return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); - } - } - } - - //----------------------------------------------------------------------- - /** - *

Obtains the list of locales to search through when performing - * a locale search.

- * - *
-     * localeLookupList(Locale("fr","CA","xxx"))
-     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
-     * 
- * - * @param locale the locale to start from - * @return the unmodifiable list of Locale objects, 0 being locale, not null - */ - public static List localeLookupList(Locale locale) { - return localeLookupList(locale, locale); - } - - //----------------------------------------------------------------------- - /** - *

Obtains the list of locales to search through when performing - * a locale search.

- * - *
-     * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
-     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
-     * 
- * - *

The result list begins with the most specific locale, then the - * next more general and so on, finishing with the default locale. - * The list will never contain the same locale twice.

- * - * @param locale the locale to start from, null returns empty list - * @param defaultLocale the default locale to use if no other is found - * @return the unmodifiable list of Locale objects, 0 being locale, not null - */ - public static List localeLookupList(Locale locale, Locale defaultLocale) { - List list = new ArrayList(4); - if (locale != null) { - list.add(locale); - if (locale.getVariant().length() > 0) { - list.add(new Locale(locale.getLanguage(), locale.getCountry())); - } - if (locale.getCountry().length() > 0) { - list.add(new Locale(locale.getLanguage(), "")); - } - if (list.contains(defaultLocale) == false) { - list.add(defaultLocale); - } - } - return Collections.unmodifiableList(list); - } - - //----------------------------------------------------------------------- - /** - *

Obtains an unmodifiable list of installed locales.

- * - *

This method is a wrapper around {@link Locale#getAvailableLocales()}. - * It is more efficient, as the JDK method must create a new array each - * time it is called.

- * - * @return the unmodifiable list of available locales - */ - public static List availableLocaleList() { - return SyncAvoid.AVAILABLE_LOCALE_LIST; - } - - //----------------------------------------------------------------------- - /** - *

Obtains an unmodifiable set of installed locales.

- * - *

This method is a wrapper around {@link Locale#getAvailableLocales()}. - * It is more efficient, as the JDK method must create a new array each - * time it is called.

- * - * @return the unmodifiable set of available locales - */ - public static Set availableLocaleSet() { - return SyncAvoid.AVAILABLE_LOCALE_SET; - } - - //----------------------------------------------------------------------- - /** - *

Checks if the locale specified is in the list of available locales.

- * - * @param locale the Locale object to check if it is available - * @return true if the locale is a known locale - */ - public static boolean isAvailableLocale(Locale locale) { - return availableLocaleList().contains(locale); - } - - //----------------------------------------------------------------------- - /** - *

Obtains the list of languages supported for a given country.

- * - *

This method takes a country code and searches to find the - * languages available for that country. Variant locales are removed.

- * - * @param countryCode the 2 letter country code, null returns empty - * @return an unmodifiable List of Locale objects, not null - */ - public static List languagesByCountry(String countryCode) { - if (countryCode == null) { - return Collections.emptyList(); - } - List langs = cLanguagesByCountry.get(countryCode); - if (langs == null) { - langs = new ArrayList(); - List locales = availableLocaleList(); - for (int i = 0; i < locales.size(); i++) { - Locale locale = locales.get(i); - if (countryCode.equals(locale.getCountry()) && - locale.getVariant().length() == 0) { - langs.add(locale); - } - } - langs = Collections.unmodifiableList(langs); - cLanguagesByCountry.putIfAbsent(countryCode, langs); - langs = cLanguagesByCountry.get(countryCode); - } - return langs; - } - - //----------------------------------------------------------------------- - /** - *

Obtains the list of countries supported for a given language.

- * - *

This method takes a language code and searches to find the - * countries available for that language. Variant locales are removed.

- * - * @param languageCode the 2 letter language code, null returns empty - * @return an unmodifiable List of Locale objects, not null - */ - public static List countriesByLanguage(String languageCode) { - if (languageCode == null) { - return Collections.emptyList(); - } - List countries = cCountriesByLanguage.get(languageCode); - if (countries == null) { - countries = new ArrayList(); - List locales = availableLocaleList(); - for (int i = 0; i < locales.size(); i++) { - Locale locale = locales.get(i); - if (languageCode.equals(locale.getLanguage()) && - locale.getCountry().length() != 0 && - locale.getVariant().length() == 0) { - countries.add(locale); - } - } - countries = Collections.unmodifiableList(countries); - cCountriesByLanguage.putIfAbsent(languageCode, countries); - countries = cCountriesByLanguage.get(languageCode); - } - return countries; - } - - //----------------------------------------------------------------------- - // class to avoid synchronization - static class SyncAvoid { - /** Unmodifiable list of available locales. */ - private static List AVAILABLE_LOCALE_LIST; - /** Unmodifiable set of available locales. */ - private static Set AVAILABLE_LOCALE_SET; - - static { - List list = new ArrayList(Arrays.asList(Locale.getAvailableLocales())); // extra safe - AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list); - AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet(availableLocaleList())); - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/RandomStringUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/RandomStringUtils.java deleted file mode 100644 index 04e2101e..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/RandomStringUtils.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.util.Random; - -/** - *

Operations for random {@code String}s.

- *

Currently private high surrogate characters are ignored. - * These are Unicode characters that fall between the values 56192 (db80) - * and 56319 (dbff) as we don't know how to handle them. - * High and low surrogates are correctly dealt with - that is if a - * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) - * then it is followed by a low surrogate. If a low surrogate is chosen, - * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly - * chosen high surrogate.

- * - *

#ThreadSafe#

- * @since 1.0 - * @version $Id: RandomStringUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class RandomStringUtils { - - /** - *

Random object used by random method. This has to be not local - * to the random method so as to not return the same value in the - * same millisecond.

- */ - private static final Random RANDOM = new Random(); - - /** - *

{@code RandomStringUtils} instances should NOT be constructed in - * standard programming. Instead, the class should be used as - * {@code RandomStringUtils.random(5);}.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- */ - public RandomStringUtils() { - super(); - } - - // Random - //----------------------------------------------------------------------- - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of all characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String random(int count) { - return random(count, false, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters whose - * ASCII value is between {@code 32} and {@code 126} (inclusive).

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAscii(int count) { - return random(count, 32, 127, false, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alphabetic - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphabetic(int count) { - return random(count, true, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphanumeric(int count) { - return random(count, true, true); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of numeric - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomNumeric(int count) { - return random(count, false, true); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters as indicated by the arguments.

- * - * @param count the length of random string to create - * @param letters if {@code true}, generated string will include - * alphabetic characters - * @param numbers if {@code true}, generated string will include - * numeric characters - * @return the random string - */ - public static String random(int count, boolean letters, boolean numbers) { - return random(count, 0, 0, letters, numbers); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters as indicated by the arguments.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters if {@code true}, generated string will include - * alphabetic characters - * @param numbers if {@code true}, generated string will include - * numeric characters - * @return the random string - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers) { - return random(count, start, end, letters, numbers, null, RANDOM); - } - - /** - *

Creates a random string based on a variety of options, using - * default source of randomness.

- * - *

This method has exactly the same semantics as - * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but - * instead of using an externally supplied source of randomness, it uses - * the internal static {@link Random} instance.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from. - * If {@code null}, then it will use the set of all chars. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not - * {@code (end - start) + 1} characters in the set array. - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, char... chars) { - return random(count, start, end, letters, numbers, chars, RANDOM); - } - - /** - *

Creates a random string based on a variety of options, using - * supplied source of randomness.

- * - *

If start and end are both {@code 0}, start and end are set - * to {@code ' '} and {@code 'z'}, the ASCII printable - * characters, will be used, unless letters and numbers are both - * {@code false}, in which case, start and end are set to - * {@code 0} and {@code Integer.MAX_VALUE}. - * - *

If set is not {@code null}, characters between start and - * end are chosen.

- * - *

This method accepts a user-supplied {@link Random} - * instance to use as a source of randomness. By seeding a single - * {@link Random} instance with a fixed seed and using it for each call, - * the same random sequence of strings can be generated repeatedly - * and predictably.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from. - * If {@code null}, then it will use the set of all chars. - * @param random a source of randomness. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not - * {@code (end - start) + 1} characters in the set array. - * @throws IllegalArgumentException if {@code count} < 0. - * @since 2.0 - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, - char[] chars, Random random) { - if (count == 0) { - return ""; - } else if (count < 0) { - throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); - } - if (start == 0 && end == 0) { - end = 'z' + 1; - start = ' '; - if (!letters && !numbers) { - start = 0; - end = Integer.MAX_VALUE; - } - } - - char[] buffer = new char[count]; - int gap = end - start; - - while (count-- != 0) { - char ch; - if (chars == null) { - ch = (char) (random.nextInt(gap) + start); - } else { - ch = chars[random.nextInt(gap) + start]; - } - if (letters && Character.isLetter(ch) - || numbers && Character.isDigit(ch) - || !letters && !numbers) { - if(ch >= 56320 && ch <= 57343) { - if(count == 0) { - count++; - } else { - // low surrogate, insert high surrogate after putting it in - buffer[count] = ch; - count--; - buffer[count] = (char) (55296 + random.nextInt(128)); - } - } else if(ch >= 55296 && ch <= 56191) { - if(count == 0) { - count++; - } else { - // high surrogate, insert low surrogate before putting it in - buffer[count] = (char) (56320 + random.nextInt(128)); - count--; - buffer[count] = ch; - } - } else if(ch >= 56192 && ch <= 56319) { - // private high surrogate, no effing clue, so skip it - count++; - } else { - buffer[count] = ch; - } - } else { - count++; - } - } - return new String(buffer); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters - * specified.

- * - * @param count the length of random string to create - * @param chars the String containing the set of characters to use, - * may be null - * @return the random string - * @throws IllegalArgumentException if {@code count} < 0. - */ - public static String random(int count, String chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, chars.toCharArray()); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters specified.

- * - * @param count the length of random string to create - * @param chars the character array containing the set of characters to use, - * may be null - * @return the random string - * @throws IllegalArgumentException if {@code count} < 0. - */ - public static String random(int count, char... chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, 0, chars.length, false, false, chars, RANDOM); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/Range.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/Range.java deleted file mode 100644 index f3d43263..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/Range.java +++ /dev/null @@ -1,493 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.io.Serializable; -import java.util.Comparator; - -/** - *

An immutable range of objects from a minimum to maximum point inclusive.

- * - *

The objects need to either be implementations of {@code Comparable} - * or you need to supply a {@code Comparator}.

- * - *

#ThreadSafe# if the objects and comparator are thread-safe

- * - * @since 3.0 - * @version $Id: Range.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public final class Range implements Serializable { - - /** - * Serialization version. - * @see java.io.Serializable - */ - private static final long serialVersionUID = 1L; - - /** - * The ordering scheme used in this range. - */ - private final Comparator comparator; - /** - * The minimum value in this range (inclusive). - */ - private final T minimum; - /** - * The maximum value in this range (inclusive). - */ - private final T maximum; - /** - * Cached output hashCode (class is immutable). - */ - private transient int hashCode; - /** - * Cached output toString (class is immutable). - */ - private transient String toString; - - /** - *

Obtains a range using the specified element as both the minimum - * and maximum in this range.

- * - *

The range uses the natural ordering of the elements to determine where - * values lie in the range.

- * - * @param the type of the elements in this range - * @param element the value to use for this range, not null - * @return the range object, not null - * @throws IllegalArgumentException if the element is null - * @throws ClassCastException if the element is not {@code Comparable} - */ - public static > Range is(T element) { - return between(element, element, null); - } - - /** - *

Obtains a range using the specified element as both the minimum - * and maximum in this range.

- * - *

The range uses the specified {@code Comparator} to determine where - * values lie in the range.

- * - * @param the type of the elements in this range - * @param element the value to use for this range, must not be {@code null} - * @param comparator the comparator to be used, null for natural ordering - * @return the range object, not null - * @throws IllegalArgumentException if the element is null - * @throws ClassCastException if using natural ordering and the elements are not {@code Comparable} - */ - public static Range is(T element, Comparator comparator) { - return between(element, element, comparator); - } - - /** - *

Obtains a range with the specified minimum and maximum values (both inclusive).

- * - *

The range uses the natural ordering of the elements to determine where - * values lie in the range.

- * - *

The arguments may be passed in the order (min,max) or (max,min). - * The getMinimum and getMaximum methods will return the correct values.

- * - * @param the type of the elements in this range - * @param fromInclusive the first value that defines the edge of the range, inclusive - * @param toInclusive the second value that defines the edge of the range, inclusive - * @return the range object, not null - * @throws IllegalArgumentException if either element is null - * @throws ClassCastException if the elements are not {@code Comparable} - */ - public static > Range between(T fromInclusive, T toInclusive) { - return between(fromInclusive, toInclusive, null); - } - - /** - *

Obtains a range with the specified minimum and maximum values (both inclusive).

- * - *

The range uses the specified {@code Comparator} to determine where - * values lie in the range.

- * - *

The arguments may be passed in the order (min,max) or (max,min). - * The getMinimum and getMaximum methods will return the correct values.

- * - * @param the type of the elements in this range - * @param fromInclusive the first value that defines the edge of the range, inclusive - * @param toInclusive the second value that defines the edge of the range, inclusive - * @param comparator the comparator to be used, null for natural ordering - * @return the range object, not null - * @throws IllegalArgumentException if either element is null - * @throws ClassCastException if using natural ordering and the elements are not {@code Comparable} - */ - public static Range between(T fromInclusive, T toInclusive, Comparator comparator) { - return new Range(fromInclusive, toInclusive, comparator); - } - - /** - * Creates an instance. - * - * @param element1 the first element, not null - * @param element2 the second element, not null - * @param comparator the comparator to be used, null for natural ordering - */ - @SuppressWarnings("unchecked") - private Range(T element1, T element2, Comparator comparator) { - if (element1 == null || element2 == null) { - throw new IllegalArgumentException("Elements in a range must not be null: element1=" + - element1 + ", element2=" + element2); - } - if (comparator == null) { - comparator = ComparableComparator.INSTANCE; - } - if (comparator.compare(element1, element2) < 1) { - this.minimum = element1; - this.maximum = element2; - } else { - this.minimum = element2; - this.maximum = element1; - } - this.comparator = comparator; - } - - // Accessors - //-------------------------------------------------------------------- - - /** - *

Gets the minimum value in this range.

- * - * @return the minimum value in this range, not null - */ - public T getMinimum() { - return minimum; - } - - /** - *

Gets the maximum value in this range.

- * - * @return the maximum value in this range, not null - */ - public T getMaximum() { - return maximum; - } - - /** - *

Gets the comparator being used to determine if objects are within the range.

- * - *

Natural ordering uses an internal comparator implementation, thus this - * method never returns null. See {@link #isNaturalOrdering()}.

- * - * @return the comparator being used, not null - */ - public Comparator getComparator() { - return comparator; - } - - /** - *

Whether or not the Range is using the natural ordering of the elements.

- * - *

Natural ordering uses an internal comparator implementation, thus this - * method is the only way to check if a null comparator was specified.

- * - * @return true if using natural ordering - */ - public boolean isNaturalOrdering() { - return comparator == ComparableComparator.INSTANCE; - } - - // Element tests - //-------------------------------------------------------------------- - - /** - *

Checks whether the specified element occurs within this range.

- * - * @param element the element to check for, null returns false - * @return true if the specified element occurs within this range - */ - public boolean contains(T element) { - if (element == null) { - return false; - } - return comparator.compare(element, minimum) > -1 && comparator.compare(element, maximum) < 1; - } - - /** - *

Checks whether this range is after the specified element.

- * - * @param element the element to check for, null returns false - * @return true if this range is entirely after the specified element - */ - public boolean isAfter(T element) { - if (element == null) { - return false; - } - return comparator.compare(element, minimum) < 0; - } - - /** - *

Checks whether this range starts with the specified element.

- * - * @param element the element to check for, null returns false - * @return true if the specified element occurs within this range - */ - public boolean isStartedBy(T element) { - if (element == null) { - return false; - } - return comparator.compare(element, minimum) == 0; - } - - /** - *

Checks whether this range starts with the specified element.

- * - * @param element the element to check for, null returns false - * @return true if the specified element occurs within this range - */ - public boolean isEndedBy(T element) { - if (element == null) { - return false; - } - return comparator.compare(element, maximum) == 0; - } - - /** - *

Checks whether this range is before the specified element.

- * - * @param element the element to check for, null returns false - * @return true if this range is entirely before the specified element - */ - public boolean isBefore(T element) { - if (element == null) { - return false; - } - return comparator.compare(element, maximum) > 0; - } - - /** - *

Checks where the specified element occurs relative to this range.

- * - *

The API is reminiscent of the Comparable interface returning {@code -1} if - * the element is before the range, {@code 0} if contained within the range and - * {@code 1} if the element is after the range.

- * - * @param element the element to check for, not null - * @return -1, 0 or +1 depending on the element's location relative to the range - */ - public int elementCompareTo(T element) { - if (element == null) { - // Comparable API says throw NPE on null - throw new NullPointerException("Element is null"); - } - if (isAfter(element)) { - return -1; - } else if (isBefore(element)) { - return 1; - } else { - return 0; - } - } - - // Range tests - //-------------------------------------------------------------------- - - /** - *

Checks whether this range contains all the elements of the specified range.

- * - *

This method may fail if the ranges have two different comparators or element types.

- * - * @param otherRange the range to check, null returns false - * @return true if this range contains the specified range - * @throws RuntimeException if ranges cannot be compared - */ - public boolean containsRange(Range otherRange) { - if (otherRange == null) { - return false; - } - return contains(otherRange.minimum) - && contains(otherRange.maximum); - } - - /** - *

Checks whether this range is completely after the specified range.

- * - *

This method may fail if the ranges have two different comparators or element types.

- * - * @param otherRange the range to check, null returns false - * @return true if this range is completely after the specified range - * @throws RuntimeException if ranges cannot be compared - */ - public boolean isAfterRange(Range otherRange) { - if (otherRange == null) { - return false; - } - return isAfter(otherRange.maximum); - } - - /** - *

Checks whether this range is overlapped by the specified range.

- * - *

Two ranges overlap if there is at least one element in common.

- * - *

This method may fail if the ranges have two different comparators or element types.

- * - * @param otherRange the range to test, null returns false - * @return true if the specified range overlaps with this - * range; otherwise, {@code false} - * @throws RuntimeException if ranges cannot be compared - */ - public boolean isOverlappedBy(Range otherRange) { - if (otherRange == null) { - return false; - } - return otherRange.contains(minimum) - || otherRange.contains(maximum) - || contains(otherRange.minimum); - } - - /** - *

Checks whether this range is completely before the specified range.

- * - *

This method may fail if the ranges have two different comparators or element types.

- * - * @param otherRange the range to check, null returns false - * @return true if this range is completely before the specified range - * @throws RuntimeException if ranges cannot be compared - */ - public boolean isBeforeRange(Range otherRange) { - if (otherRange == null) { - return false; - } - return isBefore(otherRange.minimum); - } - - /** - * Calculate the intersection of {@code this} and an overlapping Range. - * @param other overlapping Range - * @return range representing the intersection of {@code this} and {@code other} ({@code this} if equal) - * @throws IllegalArgumentException if {@code other} does not overlap {@code this} - * @since 3.0.1 - */ - public Range intersectionWith(Range other) { - if (!this.isOverlappedBy(other)) { - throw new IllegalArgumentException(String.format( - "Cannot calculate intersection with non-overlapping range %s", other)); - } - if (this.equals(other)) { - return this; - } - T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum; - T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum; - return between(min, max, getComparator()); - } - - // Basics - //-------------------------------------------------------------------- - - /** - *

Compares this range to another object to test if they are equal.

. - * - *

To be equal, the minimum and maximum values must be equal, which - * ignores any differences in the comparator.

- * - * @param obj the reference object with which to compare - * @return true if this object is equal - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } else if (obj == null || obj.getClass() != getClass()) { - return false; - } else { - @SuppressWarnings("unchecked") // OK because we checked the class above - Range range = (Range) obj; - return minimum.equals(range.minimum) && - maximum.equals(range.maximum); - } - } - - /** - *

Gets a suitable hash code for the range.

- * - * @return a hash code value for this object - */ - @Override - public int hashCode() { - int result = hashCode; - if (hashCode == 0) { - result = 17; - result = 37 * result + getClass().hashCode(); - result = 37 * result + minimum.hashCode(); - result = 37 * result + maximum.hashCode(); - hashCode = result; - } - return result; - } - - /** - *

Gets the range as a {@code String}.

- * - *

The format of the String is '[min..max]'.

- * - * @return the {@code String} representation of this range - */ - @Override - public String toString() { - String result = toString; - if (result == null) { - StringBuilder buf = new StringBuilder(32); - buf.append('['); - buf.append(minimum); - buf.append(".."); - buf.append(maximum); - buf.append(']'); - result = buf.toString(); - toString = result; - } - return result; - } - - /** - *

Formats the receiver using the given format.

- * - *

This uses {@link java.util.Formattable} to perform the formatting. Three variables may - * be used to embed the minimum, maximum and comparator. - * Use {@code %1$s} for the minimum element, {@code %2$s} for the maximum element - * and {@code %3$s} for the comparator. - * The default format used by {@code toString()} is {@code [%1$s..%2$s]}.

- * - * @param format the format string, optionally containing {@code %1$s}, {@code %2$s} and {@code %3$s}, not null - * @return the formatted string, not null - */ - public String toString(String format) { - return String.format(format, minimum, maximum, comparator); - } - - //----------------------------------------------------------------------- - @SuppressWarnings({"rawtypes", "unchecked"}) - private enum ComparableComparator implements Comparator { - INSTANCE; - /** - * Comparable based compare implementation. - * - * @param obj1 left hand side of comparison - * @param obj2 right hand side of comparison - * @return negative, 0, positive comparison value - */ - public int compare(Object obj1, Object obj2) { - return ((Comparable) obj1).compareTo(obj2); - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationException.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationException.java deleted file mode 100644 index 9f4ee019..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationException.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -/** - *

Exception thrown when the Serialization process fails.

- * - *

The original error is wrapped within this one.

- * - *

#NotThreadSafe# because Throwable is not threadsafe

- * @since 1.0 - * @version $Id: SerializationException.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class SerializationException extends RuntimeException { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 4029025366392702726L; - - /** - *

Constructs a new {@code SerializationException} without specified - * detail message.

- */ - public SerializationException() { - super(); - } - - /** - *

Constructs a new {@code SerializationException} with specified - * detail message.

- * - * @param msg The error message. - */ - public SerializationException(String msg) { - super(msg); - } - - /** - *

Constructs a new {@code SerializationException} with specified - * nested {@code Throwable}.

- * - * @param cause The {@code Exception} or {@code Error} - * that caused this exception to be thrown. - */ - public SerializationException(Throwable cause) { - super(cause); - } - - /** - *

Constructs a new {@code SerializationException} with specified - * detail message and nested {@code Throwable}.

- * - * @param msg The error message. - * @param cause The {@code Exception} or {@code Error} - * that caused this exception to be thrown. - */ - public SerializationException(String msg, Throwable cause) { - super(msg, cause); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationUtils.java deleted file mode 100644 index 3d85b93b..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/SerializationUtils.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamClass; -import java.io.OutputStream; -import java.io.Serializable; - -/** - *

Assists with the serialization process and performs additional functionality based - * on serialization.

- *

- *

    - *
  • Deep clone using serialization - *
  • Serialize managing finally and IOException - *
  • Deserialize managing finally and IOException - *
- * - *

This class throws exceptions for invalid {@code null} inputs. - * Each method documents its behaviour in more detail.

- * - *

#ThreadSafe#

- * @since 1.0 - * @version $Id: SerializationUtils.java 1199718 2011-11-09 12:43:20Z sebb $ - */ -public class SerializationUtils { - - /** - *

SerializationUtils instances should NOT be constructed in standard programming. - * Instead, the class should be used as {@code SerializationUtils.clone(object)}.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- * @since 2.0 - */ - public SerializationUtils() { - super(); - } - - // Clone - //----------------------------------------------------------------------- - /** - *

Deep clone an {@code Object} using serialization.

- * - *

This is many times slower than writing clone methods by hand - * on all objects in your object graph. However, for complex object - * graphs, or for those that don't support deep cloning this can - * be a simple alternative implementation. Of course all the objects - * must be {@code Serializable}.

- * - * @param the type of the object involved - * @param object the {@code Serializable} object to clone - * @return the cloned object - * @throws SerializationException (runtime) if the serialization fails - */ - public static T clone(T object) { - if (object == null) { - return null; - } - byte[] objectData = serialize(object); - ByteArrayInputStream bais = new ByteArrayInputStream(objectData); - - ClassLoaderAwareObjectInputStream in = null; - try { - // stream closed in the finally - in = new ClassLoaderAwareObjectInputStream(bais, object.getClass().getClassLoader()); - /* - * when we serialize and deserialize an object, - * it is reasonable to assume the deserialized object - * is of the same type as the original serialized object - */ - @SuppressWarnings("unchecked") // see above - T readObject = (T) in.readObject(); - return readObject; - - } catch (ClassNotFoundException ex) { - throw new SerializationException("ClassNotFoundException while reading cloned object data", ex); - } catch (IOException ex) { - throw new SerializationException("IOException while reading cloned object data", ex); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (IOException ex) { - throw new SerializationException("IOException on closing cloned object data InputStream.", ex); - } - } - } - - // Serialize - //----------------------------------------------------------------------- - /** - *

Serializes an {@code Object} to the specified stream.

- * - *

The stream will be closed once the object is written. - * This avoids the need for a finally clause, and maybe also exception - * handling, in the application code.

- * - *

The stream passed in is not buffered internally within this method. - * This is the responsibility of your application if desired.

- * - * @param obj the object to serialize to bytes, may be null - * @param outputStream the stream to write to, must not be null - * @throws IllegalArgumentException if {@code outputStream} is {@code null} - * @throws SerializationException (runtime) if the serialization fails - */ - public static void serialize(Serializable obj, OutputStream outputStream) { - if (outputStream == null) { - throw new IllegalArgumentException("The OutputStream must not be null"); - } - ObjectOutputStream out = null; - try { - // stream closed in the finally - out = new ObjectOutputStream(outputStream); - out.writeObject(obj); - - } catch (IOException ex) { - throw new SerializationException(ex); - } finally { - try { - if (out != null) { - out.close(); - } - } catch (IOException ex) { // NOPMD - // ignore close exception - } - } - } - - /** - *

Serializes an {@code Object} to a byte array for - * storage/serialization.

- * - * @param obj the object to serialize to bytes - * @return a byte[] with the converted Serializable - * @throws SerializationException (runtime) if the serialization fails - */ - public static byte[] serialize(Serializable obj) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(512); - serialize(obj, baos); - return baos.toByteArray(); - } - - // Deserialize - //----------------------------------------------------------------------- - /** - *

Deserializes an {@code Object} from the specified stream.

- * - *

The stream will be closed once the object is written. This - * avoids the need for a finally clause, and maybe also exception - * handling, in the application code.

- * - *

The stream passed in is not buffered internally within this method. - * This is the responsibility of your application if desired.

- * - * @param inputStream the serialized object input stream, must not be null - * @return the deserialized object - * @throws IllegalArgumentException if {@code inputStream} is {@code null} - * @throws SerializationException (runtime) if the serialization fails - */ - public static Object deserialize(InputStream inputStream) { - if (inputStream == null) { - throw new IllegalArgumentException("The InputStream must not be null"); - } - ObjectInputStream in = null; - try { - // stream closed in the finally - in = new ObjectInputStream(inputStream); - return in.readObject(); - - } catch (ClassNotFoundException ex) { - throw new SerializationException(ex); - } catch (IOException ex) { - throw new SerializationException(ex); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (IOException ex) { // NOPMD - // ignore close exception - } - } - } - - /** - *

Deserializes a single {@code Object} from an array of bytes.

- * - * @param objectData the serialized object, must not be null - * @return the deserialized object - * @throws IllegalArgumentException if {@code objectData} is {@code null} - * @throws SerializationException (runtime) if the serialization fails - */ - public static Object deserialize(byte[] objectData) { - if (objectData == null) { - throw new IllegalArgumentException("The byte[] must not be null"); - } - ByteArrayInputStream bais = new ByteArrayInputStream(objectData); - return deserialize(bais); - } - - /** - *

Custom specialization of the standard JDK {@link java.io.ObjectInputStream} - * that uses a custom ClassLoader to resolve a class. - * If the specified ClassLoader is not able to resolve the class, - * the context classloader of the current thread will be used. - * This way, the standard deserialization work also in web-application - * containers and application servers, no matter in which of the - * ClassLoader the particular class that encapsulates - * serialization/deserialization lives.

- * - *

For more in-depth information about the problem for which this - * class here is a workaround, see the JIRA issue LANG-626.

- */ - static class ClassLoaderAwareObjectInputStream extends ObjectInputStream { - private ClassLoader classLoader; - - /** - * Constructor. - * @param in The InputStream. - * @param classLoader classloader to use - * @throws IOException if an I/O error occurs while reading stream header. - * @see java.io.ObjectInputStream - */ - public ClassLoaderAwareObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException { - super(in); - this.classLoader = classLoader; - } - - /** - * Overriden version that uses the parametrized ClassLoader or the ClassLoader - * of the current Thread to resolve the class. - * @param desc An instance of class ObjectStreamClass. - * @return A Class object corresponding to desc. - * @throws IOException Any of the usual Input/Output exceptions. - * @throws ClassNotFoundException If class of a serialized object cannot be found. - */ - @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { - String name = desc.getName(); - try { - return Class.forName(name, false, classLoader); - } catch (ClassNotFoundException ex) { - return Class.forName(name, false, Thread.currentThread().getContextClassLoader()); - } - } - - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/StringEscapeUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/StringEscapeUtils.java deleted file mode 100644 index 0524f923..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/StringEscapeUtils.java +++ /dev/null @@ -1,585 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3; - -import java.io.IOException; -import java.io.Writer; - -import external.org.apache.commons.lang3.text.translate.AggregateTranslator; -import external.org.apache.commons.lang3.text.translate.CharSequenceTranslator; -import external.org.apache.commons.lang3.text.translate.EntityArrays; -import external.org.apache.commons.lang3.text.translate.LookupTranslator; -import external.org.apache.commons.lang3.text.translate.NumericEntityUnescaper; -import external.org.apache.commons.lang3.text.translate.OctalUnescaper; -import external.org.apache.commons.lang3.text.translate.UnicodeEscaper; -import external.org.apache.commons.lang3.text.translate.UnicodeUnescaper; - -/** - *

Escapes and unescapes {@code String}s for - * Java, Java Script, HTML and XML.

- * - *

#ThreadSafe#

- * @since 2.0 - * @version $Id: StringEscapeUtils.java 1148520 2011-07-19 20:53:23Z ggregory $ - */ -public class StringEscapeUtils { - - /* ESCAPE TRANSLATORS */ - - /** - * Translator object for escaping Java. - * - * While {@link #escapeJava(String)} is the expected method of use, this - * object allows the Java escaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator ESCAPE_JAVA = - new LookupTranslator( - new String[][] { - {"\"", "\\\""}, - {"\\", "\\\\"}, - }).with( - new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()) - ).with( - UnicodeEscaper.outsideOf(32, 0x7f) - ); - - /** - * Translator object for escaping EcmaScript/JavaScript. - * - * While {@link #escapeEcmaScript(String)} is the expected method of use, this - * object allows the EcmaScript escaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator ESCAPE_ECMASCRIPT = - new AggregateTranslator( - new LookupTranslator( - new String[][] { - {"'", "\\'"}, - {"\"", "\\\""}, - {"\\", "\\\\"}, - {"/", "\\/"} - }), - new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()), - UnicodeEscaper.outsideOf(32, 0x7f) - ); - - /** - * Translator object for escaping XML. - * - * While {@link #escapeXml(String)} is the expected method of use, this - * object allows the XML escaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator ESCAPE_XML = - new AggregateTranslator( - new LookupTranslator(EntityArrays.BASIC_ESCAPE()), - new LookupTranslator(EntityArrays.APOS_ESCAPE()) - ); - - /** - * Translator object for escaping HTML version 3.0. - * - * While {@link #escapeHtml3(String)} is the expected method of use, this - * object allows the HTML escaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator ESCAPE_HTML3 = - new AggregateTranslator( - new LookupTranslator(EntityArrays.BASIC_ESCAPE()), - new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE()) - ); - - /** - * Translator object for escaping HTML version 4.0. - * - * While {@link #escapeHtml4(String)} is the expected method of use, this - * object allows the HTML escaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator ESCAPE_HTML4 = - new AggregateTranslator( - new LookupTranslator(EntityArrays.BASIC_ESCAPE()), - new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE()), - new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE()) - ); - - /** - * Translator object for escaping individual Comma Separated Values. - * - * While {@link #escapeCsv(String)} is the expected method of use, this - * object allows the CSV escaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator ESCAPE_CSV = new CsvEscaper(); - - // TODO: Create a parent class - 'SinglePassTranslator' ? - // It would handle the index checking + length returning, - // and could also have an optimization check method. - static class CsvEscaper extends CharSequenceTranslator { - - private static final char CSV_DELIMITER = ','; - private static final char CSV_QUOTE = '"'; - private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE); - private static final char[] CSV_SEARCH_CHARS = - new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF}; - - @Override - public int translate(CharSequence input, int index, Writer out) throws IOException { - - if(index != 0) { - throw new IllegalStateException("CsvEscaper should never reach the [1] index"); - } - - if (StringUtils.containsNone(input.toString(), CSV_SEARCH_CHARS)) { - out.write(input.toString()); - } else { - out.write(CSV_QUOTE); - out.write(StringUtils.replace(input.toString(), CSV_QUOTE_STR, CSV_QUOTE_STR + CSV_QUOTE_STR)); - out.write(CSV_QUOTE); - } - return input.length(); - } - } - - /* UNESCAPE TRANSLATORS */ - - /** - * Translator object for unescaping escaped Java. - * - * While {@link #unescapeJava(String)} is the expected method of use, this - * object allows the Java unescaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - // TODO: throw "illegal character: \92" as an Exception if a \ on the end of the Java (as per the compiler)? - public static final CharSequenceTranslator UNESCAPE_JAVA = - new AggregateTranslator( - new OctalUnescaper(), // .between('\1', '\377'), - new UnicodeUnescaper(), - new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_UNESCAPE()), - new LookupTranslator( - new String[][] { - {"\\\\", "\\"}, - {"\\\"", "\""}, - {"\\'", "'"}, - {"\\", ""} - }) - ); - - /** - * Translator object for unescaping escaped EcmaScript. - * - * While {@link #unescapeEcmaScript(String)} is the expected method of use, this - * object allows the EcmaScript unescaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator UNESCAPE_ECMASCRIPT = UNESCAPE_JAVA; - - /** - * Translator object for unescaping escaped HTML 3.0. - * - * While {@link #unescapeHtml3(String)} is the expected method of use, this - * object allows the HTML unescaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator UNESCAPE_HTML3 = - new AggregateTranslator( - new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), - new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), - new NumericEntityUnescaper() - ); - - /** - * Translator object for unescaping escaped HTML 4.0. - * - * While {@link #unescapeHtml4(String)} is the expected method of use, this - * object allows the HTML unescaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator UNESCAPE_HTML4 = - new AggregateTranslator( - new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), - new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), - new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE()), - new NumericEntityUnescaper() - ); - - /** - * Translator object for unescaping escaped XML. - * - * While {@link #unescapeXml(String)} is the expected method of use, this - * object allows the XML unescaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator UNESCAPE_XML = - new AggregateTranslator( - new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), - new LookupTranslator(EntityArrays.APOS_UNESCAPE()), - new NumericEntityUnescaper() - ); - - /** - * Translator object for unescaping escaped Comma Separated Value entries. - * - * While {@link #unescapeCsv(String)} is the expected method of use, this - * object allows the CSV unescaping functionality to be used - * as the foundation for a custom translator. - * - * @since 3.0 - */ - public static final CharSequenceTranslator UNESCAPE_CSV = new CsvUnescaper(); - - static class CsvUnescaper extends CharSequenceTranslator { - - private static final char CSV_DELIMITER = ','; - private static final char CSV_QUOTE = '"'; - private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE); - private static final char[] CSV_SEARCH_CHARS = - new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF}; - - @Override - public int translate(CharSequence input, int index, Writer out) throws IOException { - - if(index != 0) { - throw new IllegalStateException("CsvUnescaper should never reach the [1] index"); - } - - if ( input.charAt(0) != CSV_QUOTE || input.charAt(input.length() - 1) != CSV_QUOTE ) { - out.write(input.toString()); - return input.length(); - } - - // strip quotes - String quoteless = input.subSequence(1, input.length() - 1).toString(); - - if ( StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS) ) { - // deal with escaped quotes; ie) "" - out.write(StringUtils.replace(quoteless, CSV_QUOTE_STR + CSV_QUOTE_STR, CSV_QUOTE_STR)); - } else { - out.write(input.toString()); - } - return input.length(); - } - } - - /* Helper functions */ - - /** - *

{@code StringEscapeUtils} instances should NOT be constructed in - * standard programming.

- * - *

Instead, the class should be used as: - *

StringEscapeUtils.escapeJava("foo");

- * - *

This constructor is public to permit tools that require a JavaBean - * instance to operate.

- */ - public StringEscapeUtils() { - super(); - } - - // Java and JavaScript - //-------------------------------------------------------------------------- - /** - *

Escapes the characters in a {@code String} using Java String rules.

- * - *

Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

- * - *

So a tab becomes the characters {@code '\\'} and - * {@code 't'}.

- * - *

The only difference between Java strings and JavaScript strings - * is that in JavaScript, a single quote and forward-slash (/) are escaped.

- * - *

Example: - *

-     * input string: He didn't say, "Stop!"
-     * output string: He didn't say, \"Stop!\"
-     * 
- *

- * - * @param input String to escape values in, may be null - * @return String with escaped values, {@code null} if null string input - */ - public static final String escapeJava(String input) { - return ESCAPE_JAVA.translate(input); - } - - /** - *

Escapes the characters in a {@code String} using EcmaScript String rules.

- *

Escapes any values it finds into their EcmaScript String form. - * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

- * - *

So a tab becomes the characters {@code '\\'} and - * {@code 't'}.

- * - *

The only difference between Java strings and EcmaScript strings - * is that in EcmaScript, a single quote and forward-slash (/) are escaped.

- * - *

Note that EcmaScript is best known by the JavaScript and ActionScript dialects.

- * - *

Example: - *

-     * input string: He didn't say, "Stop!"
-     * output string: He didn\'t say, \"Stop!\"
-     * 
- *

- * - * @param input String to escape values in, may be null - * @return String with escaped values, {@code null} if null string input - * - * @since 3.0 - */ - public static final String escapeEcmaScript(String input) { - return ESCAPE_ECMASCRIPT.translate(input); - } - - /** - *

Unescapes any Java literals found in the {@code String}. - * For example, it will turn a sequence of {@code '\'} and - * {@code 'n'} into a newline character, unless the {@code '\'} - * is preceded by another {@code '\'}.

- * - * @param input the {@code String} to unescape, may be null - * @return a new unescaped {@code String}, {@code null} if null string input - */ - public static final String unescapeJava(String input) { - return UNESCAPE_JAVA.translate(input); - } - - /** - *

Unescapes any EcmaScript literals found in the {@code String}.

- * - *

For example, it will turn a sequence of {@code '\'} and {@code 'n'} - * into a newline character, unless the {@code '\'} is preceded by another - * {@code '\'}.

- * - * @see #unescapeJava(String) - * @param input the {@code String} to unescape, may be null - * @return A new unescaped {@code String}, {@code null} if null string input - * - * @since 3.0 - */ - public static final String unescapeEcmaScript(String input) { - return UNESCAPE_ECMASCRIPT.translate(input); - } - - // HTML and XML - //-------------------------------------------------------------------------- - /** - *

Escapes the characters in a {@code String} using HTML entities.

- * - *

- * For example: - *

- *

"bread" & "butter"

- * becomes: - *

- * &quot;bread&quot; &amp; &quot;butter&quot;. - *

- * - *

Supports all known HTML 4.0 entities, including funky accents. - * Note that the commonly used apostrophe escape character (&apos;) - * is not a legal entity and so is not supported).

- * - * @param input the {@code String} to escape, may be null - * @return a new escaped {@code String}, {@code null} if null string input - * - * @see ISO Entities - * @see HTML 3.2 Character Entities for ISO Latin-1 - * @see HTML 4.0 Character entity references - * @see HTML 4.01 Character References - * @see HTML 4.01 Code positions - * - * @since 3.0 - */ - public static final String escapeHtml4(String input) { - return ESCAPE_HTML4.translate(input); - } - - /** - *

Escapes the characters in a {@code String} using HTML entities.

- *

Supports only the HTML 3.0 entities.

- * - * @param input the {@code String} to escape, may be null - * @return a new escaped {@code String}, {@code null} if null string input - * - * @since 3.0 - */ - public static final String escapeHtml3(String input) { - return ESCAPE_HTML3.translate(input); - } - - //----------------------------------------------------------------------- - /** - *

Unescapes a string containing entity escapes to a string - * containing the actual Unicode characters corresponding to the - * escapes. Supports HTML 4.0 entities.

- * - *

For example, the string "&lt;Fran&ccedil;ais&gt;" - * will become "<Français>"

- * - *

If an entity is unrecognized, it is left alone, and inserted - * verbatim into the result string. e.g. "&gt;&zzzz;x" will - * become ">&zzzz;x".

- * - * @param input the {@code String} to unescape, may be null - * @return a new unescaped {@code String}, {@code null} if null string input - * - * @since 3.0 - */ - public static final String unescapeHtml4(String input) { - return UNESCAPE_HTML4.translate(input); - } - - /** - *

Unescapes a string containing entity escapes to a string - * containing the actual Unicode characters corresponding to the - * escapes. Supports only HTML 3.0 entities.

- * - * @param input the {@code String} to unescape, may be null - * @return a new unescaped {@code String}, {@code null} if null string input - * - * @since 3.0 - */ - public static final String unescapeHtml3(String input) { - return UNESCAPE_HTML3.translate(input); - } - - //----------------------------------------------------------------------- - /** - *

Escapes the characters in a {@code String} using XML entities.

- * - *

For example: "bread" & "butter" => - * &quot;bread&quot; &amp; &quot;butter&quot;. - *

- * - *

Supports only the five basic XML entities (gt, lt, quot, amp, apos). - * Does not support DTDs or external entities.

- * - *

Note that Unicode characters greater than 0x7f are as of 3.0, no longer - * escaped. If you still wish this functionality, you can achieve it - * via the following: - * {@code StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );}

- * - * @param input the {@code String} to escape, may be null - * @return a new escaped {@code String}, {@code null} if null string input - * @see #unescapeXml(java.lang.String) - */ - public static final String escapeXml(String input) { - return ESCAPE_XML.translate(input); - } - - - //----------------------------------------------------------------------- - /** - *

Unescapes a string containing XML entity escapes to a string - * containing the actual Unicode characters corresponding to the - * escapes.

- * - *

Supports only the five basic XML entities (gt, lt, quot, amp, apos). - * Does not support DTDs or external entities.

- * - *

Note that numerical \\u Unicode codes are unescaped to their respective - * Unicode characters. This may change in future releases.

- * - * @param input the {@code String} to unescape, may be null - * @return a new unescaped {@code String}, {@code null} if null string input - * @see #escapeXml(String) - */ - public static final String unescapeXml(String input) { - return UNESCAPE_XML.translate(input); - } - - - //----------------------------------------------------------------------- - - /** - *

Returns a {@code String} value for a CSV column enclosed in double quotes, - * if required.

- * - *

If the value contains a comma, newline or double quote, then the - * String value is returned enclosed in double quotes.

- *

- * - *

Any double quote characters in the value are escaped with another double quote.

- * - *

If the value does not contain a comma, newline or double quote, then the - * String value is returned unchanged.

- *

- * - * see Wikipedia and - * RFC 4180. - * - * @param input the input CSV column String, may be null - * @return the input String, enclosed in double quotes if the value contains a comma, - * newline or double quote, {@code null} if null string input - * @since 2.4 - */ - public static final String escapeCsv(String input) { - return ESCAPE_CSV.translate(input); - } - - /** - *

Returns a {@code String} value for an unescaped CSV column.

- * - *

If the value is enclosed in double quotes, and contains a comma, newline - * or double quote, then quotes are removed. - *

- * - *

Any double quote escaped characters (a pair of double quotes) are unescaped - * to just one double quote.

- * - *

If the value is not enclosed in double quotes, or is and does not contain a - * comma, newline or double quote, then the String value is returned unchanged.

- *

- * - * see Wikipedia and - * RFC 4180. - * - * @param input the input CSV column String, may be null - * @return the input String, with enclosing double quotes removed and embedded double - * quotes unescaped, {@code null} if null string input - * @since 2.4 - */ - public static final String unescapeCsv(String input) { - return UNESCAPE_CSV.translate(input); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/builder/StandardToStringStyle.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/builder/StandardToStringStyle.java deleted file mode 100644 index d55790a0..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/builder/StandardToStringStyle.java +++ /dev/null @@ -1,560 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.builder; - -/** - *

Works with {@link ToStringBuilder} to create a toString.

- * - *

This class is intended to be used as a singleton. - * There is no need to instantiate a new style each time. - * Simply instantiate the class once, customize the values as required, and - * store the result in a public static final variable for the rest of the - * program to access.

- * - * @since 1.0 - * @version $Id: StandardToStringStyle.java 1089740 2011-04-07 05:01:54Z bayard $ - */ -public class StandardToStringStyle extends ToStringStyle { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 1L; - - /** - *

Constructor.

- */ - public StandardToStringStyle() { - super(); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether to use the class name.

- * - * @return the current useClassName flag - */ - @Override - public boolean isUseClassName() { // NOPMD as this is implementing the abstract class - return super.isUseClassName(); - } - - /** - *

Sets whether to use the class name.

- * - * @param useClassName the new useClassName flag - */ - @Override - public void setUseClassName(boolean useClassName) { // NOPMD as this is implementing the abstract class - super.setUseClassName(useClassName); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether to output short or long class names.

- * - * @return the current useShortClassName flag - * @since 2.0 - */ - @Override - public boolean isUseShortClassName() { // NOPMD as this is implementing the abstract class - return super.isUseShortClassName(); - } - - /** - *

Sets whether to output short or long class names.

- * - * @param useShortClassName the new useShortClassName flag - * @since 2.0 - */ - @Override - public void setUseShortClassName(boolean useShortClassName) { // NOPMD as this is implementing the abstract class - super.setUseShortClassName(useShortClassName); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether to use the identity hash code.

- * @return the current useIdentityHashCode flag - */ - @Override - public boolean isUseIdentityHashCode() { // NOPMD as this is implementing the abstract class - return super.isUseIdentityHashCode(); - } - - /** - *

Sets whether to use the identity hash code.

- * - * @param useIdentityHashCode the new useIdentityHashCode flag - */ - @Override - public void setUseIdentityHashCode(boolean useIdentityHashCode) { // NOPMD as this is implementing the abstract class - super.setUseIdentityHashCode(useIdentityHashCode); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether to use the field names passed in.

- * - * @return the current useFieldNames flag - */ - @Override - public boolean isUseFieldNames() { // NOPMD as this is implementing the abstract class - return super.isUseFieldNames(); - } - - /** - *

Sets whether to use the field names passed in.

- * - * @param useFieldNames the new useFieldNames flag - */ - @Override - public void setUseFieldNames(boolean useFieldNames) { // NOPMD as this is implementing the abstract class - super.setUseFieldNames(useFieldNames); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether to use full detail when the caller doesn't - * specify.

- * - * @return the current defaultFullDetail flag - */ - @Override - public boolean isDefaultFullDetail() { // NOPMD as this is implementing the abstract class - return super.isDefaultFullDetail(); - } - - /** - *

Sets whether to use full detail when the caller doesn't - * specify.

- * - * @param defaultFullDetail the new defaultFullDetail flag - */ - @Override - public void setDefaultFullDetail(boolean defaultFullDetail) { // NOPMD as this is implementing the abstract class - super.setDefaultFullDetail(defaultFullDetail); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether to output array content detail.

- * - * @return the current array content detail setting - */ - @Override - public boolean isArrayContentDetail() { // NOPMD as this is implementing the abstract class - return super.isArrayContentDetail(); - } - - /** - *

Sets whether to output array content detail.

- * - * @param arrayContentDetail the new arrayContentDetail flag - */ - @Override - public void setArrayContentDetail(boolean arrayContentDetail) { // NOPMD as this is implementing the abstract class - super.setArrayContentDetail(arrayContentDetail); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the array start text.

- * - * @return the current array start text - */ - @Override - public String getArrayStart() { // NOPMD as this is implementing the abstract class - return super.getArrayStart(); - } - - /** - *

Sets the array start text.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param arrayStart the new array start text - */ - @Override - public void setArrayStart(String arrayStart) { // NOPMD as this is implementing the abstract class - super.setArrayStart(arrayStart); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the array end text.

- * - * @return the current array end text - */ - @Override - public String getArrayEnd() { // NOPMD as this is implementing the abstract class - return super.getArrayEnd(); - } - - /** - *

Sets the array end text.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param arrayEnd the new array end text - */ - @Override - public void setArrayEnd(String arrayEnd) { // NOPMD as this is implementing the abstract class - super.setArrayEnd(arrayEnd); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the array separator text.

- * - * @return the current array separator text - */ - @Override - public String getArraySeparator() { // NOPMD as this is implementing the abstract class - return super.getArraySeparator(); - } - - /** - *

Sets the array separator text.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param arraySeparator the new array separator text - */ - @Override - public void setArraySeparator(String arraySeparator) { // NOPMD as this is implementing the abstract class - super.setArraySeparator(arraySeparator); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the content start text.

- * - * @return the current content start text - */ - @Override - public String getContentStart() { // NOPMD as this is implementing the abstract class - return super.getContentStart(); - } - - /** - *

Sets the content start text.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param contentStart the new content start text - */ - @Override - public void setContentStart(String contentStart) { // NOPMD as this is implementing the abstract class - super.setContentStart(contentStart); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the content end text.

- * - * @return the current content end text - */ - @Override - public String getContentEnd() { // NOPMD as this is implementing the abstract class - return super.getContentEnd(); - } - - /** - *

Sets the content end text.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param contentEnd the new content end text - */ - @Override - public void setContentEnd(String contentEnd) { // NOPMD as this is implementing the abstract class - super.setContentEnd(contentEnd); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the field name value separator text.

- * - * @return the current field name value separator text - */ - @Override - public String getFieldNameValueSeparator() { // NOPMD as this is implementing the abstract class - return super.getFieldNameValueSeparator(); - } - - /** - *

Sets the field name value separator text.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param fieldNameValueSeparator the new field name value separator text - */ - @Override - public void setFieldNameValueSeparator(String fieldNameValueSeparator) { // NOPMD as this is implementing the abstract class - super.setFieldNameValueSeparator(fieldNameValueSeparator); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the field separator text.

- * - * @return the current field separator text - */ - @Override - public String getFieldSeparator() { // NOPMD as this is implementing the abstract class - return super.getFieldSeparator(); - } - - /** - *

Sets the field separator text.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param fieldSeparator the new field separator text - */ - @Override - public void setFieldSeparator(String fieldSeparator) { // NOPMD as this is implementing the abstract class - super.setFieldSeparator(fieldSeparator); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether the field separator should be added at the start - * of each buffer.

- * - * @return the fieldSeparatorAtStart flag - * @since 2.0 - */ - @Override - public boolean isFieldSeparatorAtStart() { // NOPMD as this is implementing the abstract class - return super.isFieldSeparatorAtStart(); - } - - /** - *

Sets whether the field separator should be added at the start - * of each buffer.

- * - * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag - * @since 2.0 - */ - @Override - public void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) { // NOPMD as this is implementing the abstract class - super.setFieldSeparatorAtStart(fieldSeparatorAtStart); - } - - //--------------------------------------------------------------------- - - /** - *

Gets whether the field separator should be added at the end - * of each buffer.

- * - * @return fieldSeparatorAtEnd flag - * @since 2.0 - */ - @Override - public boolean isFieldSeparatorAtEnd() { // NOPMD as this is implementing the abstract class - return super.isFieldSeparatorAtEnd(); - } - - /** - *

Sets whether the field separator should be added at the end - * of each buffer.

- * - * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag - * @since 2.0 - */ - @Override - public void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) { // NOPMD as this is implementing the abstract class - super.setFieldSeparatorAtEnd(fieldSeparatorAtEnd); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the text to output when null found.

- * - * @return the current text to output when null found - */ - @Override - public String getNullText() { // NOPMD as this is implementing the abstract class - return super.getNullText(); - } - - /** - *

Sets the text to output when null found.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param nullText the new text to output when null found - */ - @Override - public void setNullText(String nullText) { // NOPMD as this is implementing the abstract class - super.setNullText(nullText); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the text to output when a Collection, - * Map or Array size is output.

- * - *

This is output before the size value.

- * - * @return the current start of size text - */ - @Override - public String getSizeStartText() { // NOPMD as this is implementing the abstract class - return super.getSizeStartText(); - } - - /** - *

Sets the start text to output when a Collection, - * Map or Array size is output.

- * - *

This is output before the size value.

- * - *

null is accepted, but will be converted to - * an empty String.

- * - * @param sizeStartText the new start of size text - */ - @Override - public void setSizeStartText(String sizeStartText) { // NOPMD as this is implementing the abstract class - super.setSizeStartText(sizeStartText); - } - - //--------------------------------------------------------------------- - - /** - * Gets the end text to output when a Collection, - * Map or Array size is output.

- * - *

This is output after the size value.

- * - * @return the current end of size text - */ - @Override - public String getSizeEndText() { // NOPMD as this is implementing the abstract class - return super.getSizeEndText(); - } - - /** - *

Sets the end text to output when a Collection, - * Map or Array size is output.

- * - *

This is output after the size value.

- * - *

null is accepted, but will be converted - * to an empty String.

- * - * @param sizeEndText the new end of size text - */ - @Override - public void setSizeEndText(String sizeEndText) { // NOPMD as this is implementing the abstract class - super.setSizeEndText(sizeEndText); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the start text to output when an Object is - * output in summary mode.

- * - *

This is output before the size value.

- * - * @return the current start of summary text - */ - @Override - public String getSummaryObjectStartText() { // NOPMD as this is implementing the abstract class - return super.getSummaryObjectStartText(); - } - - /** - *

Sets the start text to output when an Object is - * output in summary mode.

- * - *

This is output before the size value.

- * - *

null is accepted, but will be converted to - * an empty String.

- * - * @param summaryObjectStartText the new start of summary text - */ - @Override - public void setSummaryObjectStartText(String summaryObjectStartText) { // NOPMD as this is implementing the abstract class - super.setSummaryObjectStartText(summaryObjectStartText); - } - - //--------------------------------------------------------------------- - - /** - *

Gets the end text to output when an Object is - * output in summary mode.

- * - *

This is output after the size value.

- * - * @return the current end of summary text - */ - @Override - public String getSummaryObjectEndText() { // NOPMD as this is implementing the abstract class - return super.getSummaryObjectEndText(); - } - - /** - *

Sets the end text to output when an Object is - * output in summary mode.

- * - *

This is output after the size value.

- * - *

null is accepted, but will be converted to - * an empty String.

- * - * @param summaryObjectEndText the new end of summary text - */ - @Override - public void setSummaryObjectEndText(String summaryObjectEndText) { // NOPMD as this is implementing the abstract class - super.setSummaryObjectEndText(summaryObjectEndText); - } - - //--------------------------------------------------------------------- - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicInitializer.java deleted file mode 100644 index 5359b2b9..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicInitializer.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.concurrent.atomic.AtomicReference; - -/** - *

- * A specialized implementation of the {@code ConcurrentInitializer} interface - * based on an {@link AtomicReference} variable. - *

- *

- * This class maintains a member field of type {@code AtomicReference}. It - * implements the following algorithm to create and initialize an object in its - * {@link #get()} method: - *

    - *
  • First it is checked whether the {@code AtomicReference} variable contains - * already a value. If this is the case, the value is directly returned.
  • - *
  • Otherwise the {@link #initialize()} method is called. This method must be - * defined in concrete subclasses to actually create the managed object.
  • - *
  • After the object was created by {@link #initialize()} it is checked - * whether the {@code AtomicReference} variable is still undefined. This has to - * be done because in the meantime another thread may have initialized the - * object. If the reference is still empty, the newly created object is stored - * in it and returned by this method.
  • - *
  • Otherwise the value stored in the {@code AtomicReference} is returned.
  • - *
- *

- *

- * Because atomic variables are used this class does not need any - * synchronization. So there is no danger of deadlock, and access to the managed - * object is efficient. However, if multiple threads access the {@code - * AtomicInitializer} object before it has been initialized almost at the same - * time, it can happen that {@link #initialize()} is called multiple times. The - * algorithm outlined above guarantees that {@link #get()} always returns the - * same object though. - *

- *

- * Compared with the {@link LazyInitializer} class, this class can be more - * efficient because it does not need synchronization. The drawback is that the - * {@link #initialize()} method can be called multiple times which may be - * problematic if the creation of the managed object is expensive. As a rule of - * thumb this initializer implementation is preferable if there are not too many - * threads involved and the probability that multiple threads access an - * uninitialized object is small. If there is high parallelism, - * {@link LazyInitializer} is more appropriate. - *

- * - * @since 3.0 - * @version $Id: AtomicInitializer.java 1088899 2011-04-05 05:31:27Z bayard $ - * @param the type of the object managed by this initializer class - */ -public abstract class AtomicInitializer implements ConcurrentInitializer { - /** Holds the reference to the managed object. */ - private final AtomicReference reference = new AtomicReference(); - - /** - * Returns the object managed by this initializer. The object is created if - * it is not available yet and stored internally. This method always returns - * the same object. - * - * @return the object created by this {@code AtomicInitializer} - * @throws ConcurrentException if an error occurred during initialization of - * the object - */ - public T get() throws ConcurrentException { - T result = reference.get(); - - if (result == null) { - result = initialize(); - if (!reference.compareAndSet(null, result)) { - // another thread has initialized the reference - result = reference.get(); - } - } - - return result; - } - - /** - * Creates and initializes the object managed by this {@code - * AtomicInitializer}. This method is called by {@link #get()} when the - * managed object is not available yet. An implementation can focus on the - * creation of the object. No synchronization is needed, as this is already - * handled by {@code get()}. As stated by the class comment, it is possible - * that this method is called multiple times. - * - * @return the managed data object - * @throws ConcurrentException if an error occurs during object creation - */ - protected abstract T initialize() throws ConcurrentException; -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java deleted file mode 100644 index a8c31c2d..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/AtomicSafeInitializer.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.concurrent.atomic.AtomicReference; - -/** - *

- * A specialized {@code ConcurrentInitializer} implementation which is similar - * to {@link AtomicInitializer}, but ensures that the {@link #initialize()} - * method is called only once. - *

- *

- * As {@link AtomicInitializer} this class is based on atomic variables, so it - * can create an object under concurrent access without synchronization. - * However, it implements an additional check to guarantee that the - * {@link #initialize()} method which actually creates the object cannot be - * called multiple times. - *

- *

- * Because of this additional check this implementation is slightly less - * efficient than {@link AtomicInitializer}, but if the object creation in the - * {@code initialize()} method is expensive or if multiple invocations of - * {@code initialize()} are problematic, it is the better alternative. - *

- *

- * From its semantics this class has the same properties as - * {@link LazyInitializer}. It is a "save" implementation of the lazy - * initializer pattern. Comparing both classes in terms of efficiency is - * difficult because which one is faster depends on multiple factors. Because - * {@code AtomicSafeInitializer} does not use synchronization at all it probably - * outruns {@link LazyInitializer}, at least under low or moderate concurrent - * access. Developers should run their own benchmarks on the expected target - * platform to decide which implementation is suitable for their specific use - * case. - *

- * - * @since 3.0 - * @version $Id: AtomicSafeInitializer.java 1088899 2011-04-05 05:31:27Z bayard $ - * @param the type of the object managed by this initializer class - */ -public abstract class AtomicSafeInitializer implements - ConcurrentInitializer { - /** A guard which ensures that initialize() is called only once. */ - private final AtomicReference> factory = - new AtomicReference>(); - - /** Holds the reference to the managed object. */ - private final AtomicReference reference = new AtomicReference(); - - /** - * Get (and initialize, if not initialized yet) the required object - * - * @return lazily initialized object - * @throws ConcurrentException if the initialization of the object causes an - * exception - */ - public final T get() throws ConcurrentException { - T result; - - while ((result = reference.get()) == null) { - if (factory.compareAndSet(null, this)) { - reference.set(initialize()); - } - } - - return result; - } - - /** - * Creates and initializes the object managed by this - * {@code AtomicInitializer}. This method is called by {@link #get()} when - * the managed object is not available yet. An implementation can focus on - * the creation of the object. No synchronization is needed, as this is - * already handled by {@code get()}. This method is guaranteed to be called - * only once. - * - * @return the managed data object - * @throws ConcurrentException if an error occurs during object creation - */ - protected abstract T initialize() throws ConcurrentException; -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BackgroundInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BackgroundInitializer.java deleted file mode 100644 index f43d06e0..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BackgroundInitializer.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -/** - *

- * A class that allows complex initialization operations in a background task. - *

- *

- * Applications often have to do some expensive initialization steps when they - * are started, e.g. constructing a connection to a database, reading a - * configuration file, etc. Doing these things in parallel can enhance - * performance as the CPU load can be improved. However, when access to the - * resources initialized in a background thread is actually required, - * synchronization has to be performed to ensure that their initialization is - * complete. - *

- *

- * This abstract base class provides support for this use case. A concrete - * subclass must implement the {@link #initialize()} method. Here an arbitrary - * initialization can be implemented, and a result object can be returned. With - * this method in place the basic usage of this class is as follows (where - * {@code MyBackgroundInitializer} is a concrete subclass): - * - *

- * MyBackgroundInitializer initializer = new MyBackgroundInitializer();
- * initializer.start();
- * // Now do some other things. Initialization runs in a parallel thread
- * ...
- * // Wait for the end of initialization and access the result object
- * Object result = initializer.get();
- * 
- * - *

- *

- * After the construction of a {@code BackgroundInitializer} object its - * {@link #start()} method has to be called. This starts the background - * processing. The application can now continue to do other things. When it - * needs access to the object produced by the {@code BackgroundInitializer} it - * calls its {@link #get()} method. If initialization is already complete, - * {@link #get()} returns the result object immediately. Otherwise it blocks - * until the result object is fully constructed. - *

- *

- * {@code BackgroundInitializer} is a thin wrapper around a {@code Future} - * object and uses an {@code ExecutorService} for running the background - * initialization task. It is possible to pass in an {@code ExecutorService} at - * construction time or set one using {@code setExternalExecutor()} before - * {@code start()} was called. Then this object is used to spawn the background - * task. If no {@code ExecutorService} has been provided, {@code - * BackgroundInitializer} creates a temporary {@code ExecutorService} and - * destroys it when initialization is complete. - *

- *

- * The methods provided by {@code BackgroundInitializer} provide for minimal - * interaction with the wrapped {@code Future} object. It is also possible to - * obtain the {@code Future} object directly. Then the enhanced functionality - * offered by {@code Future} can be used, e.g. to check whether the background - * operation is complete or to cancel the operation. - *

- * - * @since 3.0 - * @version $Id: BackgroundInitializer.java 1082044 2011-03-16 04:26:58Z bayard $ - * @param the type of the object managed by this initializer class - */ -public abstract class BackgroundInitializer implements - ConcurrentInitializer { - /** The external executor service for executing tasks. */ - private ExecutorService externalExecutor; - - /** A reference to the executor service that is actually used. */ - private ExecutorService executor; - - /** Stores the handle to the background task. */ - private Future future; - - /** - * Creates a new instance of {@code BackgroundInitializer}. No external - * {@code ExecutorService} is used. - */ - protected BackgroundInitializer() { - this(null); - } - - /** - * Creates a new instance of {@code BackgroundInitializer} and initializes - * it with the given {@code ExecutorService}. If the {@code ExecutorService} - * is not null, the background task for initializing this object will be - * scheduled at this service. Otherwise a new temporary {@code - * ExecutorService} is created. - * - * @param exec an external {@code ExecutorService} to be used for task - * execution - */ - protected BackgroundInitializer(ExecutorService exec) { - setExternalExecutor(exec); - } - - /** - * Returns the external {@code ExecutorService} to be used by this class. - * - * @return the {@code ExecutorService} - */ - public final synchronized ExecutorService getExternalExecutor() { - return externalExecutor; - } - - /** - * Returns a flag whether this {@code BackgroundInitializer} has already - * been started. - * - * @return a flag whether the {@link #start()} method has already been - * called - */ - public synchronized boolean isStarted() { - return future != null; - } - - /** - * Sets an {@code ExecutorService} to be used by this class. The {@code - * ExecutorService} passed to this method is used for executing the - * background task. Thus it is possible to re-use an already existing - * {@code ExecutorService} or to use a specially configured one. If no - * {@code ExecutorService} is set, this instance creates a temporary one and - * destroys it after background initialization is complete. Note that this - * method must be called before {@link #start()}; otherwise an exception is - * thrown. - * - * @param externalExecutor the {@code ExecutorService} to be used - * @throws IllegalStateException if this initializer has already been - * started - */ - public final synchronized void setExternalExecutor( - ExecutorService externalExecutor) { - if (isStarted()) { - throw new IllegalStateException( - "Cannot set ExecutorService after start()!"); - } - - this.externalExecutor = externalExecutor; - } - - /** - * Starts the background initialization. With this method the initializer - * becomes active and invokes the {@link #initialize()} method in a - * background task. A {@code BackgroundInitializer} can be started exactly - * once. The return value of this method determines whether the start was - * successful: only the first invocation of this method returns true, - * following invocations will return false. - * - * @return a flag whether the initializer could be started successfully - */ - public synchronized boolean start() { - // Not yet started? - if (!isStarted()) { - - // Determine the executor to use and whether a temporary one has to - // be created - ExecutorService tempExec; - executor = getExternalExecutor(); - if (executor == null) { - executor = tempExec = createExecutor(); - } else { - tempExec = null; - } - - future = executor.submit(createTask(tempExec)); - - return true; - } - - return false; - } - - /** - * Returns the result of the background initialization. This method blocks - * until initialization is complete. If the background processing caused a - * runtime exception, it is directly thrown by this method. Checked - * exceptions, including {@code InterruptedException} are wrapped in a - * {@link ConcurrentException}. Calling this method before {@link #start()} - * was called causes an {@code IllegalStateException} exception to be - * thrown. - * - * @return the object produced by this initializer - * @throws ConcurrentException if a checked exception occurred during - * background processing - * @throws IllegalStateException if {@link #start()} has not been called - */ - public T get() throws ConcurrentException { - try { - return getFuture().get(); - } catch (ExecutionException execex) { - ConcurrentUtils.handleCause(execex); - return null; // should not be reached - } catch (InterruptedException iex) { - // reset interrupted state - Thread.currentThread().interrupt(); - throw new ConcurrentException(iex); - } - } - - /** - * Returns the {@code Future} object that was created when {@link #start()} - * was called. Therefore this method can only be called after {@code - * start()}. - * - * @return the {@code Future} object wrapped by this initializer - * @throws IllegalStateException if {@link #start()} has not been called - */ - public synchronized Future getFuture() { - if (future == null) { - throw new IllegalStateException("start() must be called first!"); - } - - return future; - } - - /** - * Returns the {@code ExecutorService} that is actually used for executing - * the background task. This method can be called after {@link #start()} - * (before {@code start()} it returns null). If an external executor - * was set, this is also the active executor. Otherwise this method returns - * the temporary executor that was created by this object. - * - * @return the {@code ExecutorService} for executing the background task - */ - protected synchronized final ExecutorService getActiveExecutor() { - return executor; - } - - /** - * Returns the number of background tasks to be created for this - * initializer. This information is evaluated when a temporary {@code - * ExecutorService} is created. This base implementation returns 1. Derived - * classes that do more complex background processing can override it. This - * method is called from a synchronized block by the {@link #start()} - * method. Therefore overriding methods should be careful with obtaining - * other locks and return as fast as possible. - * - * @return the number of background tasks required by this initializer - */ - protected int getTaskCount() { - return 1; - } - - /** - * Performs the initialization. This method is called in a background task - * when this {@code BackgroundInitializer} is started. It must be - * implemented by a concrete subclass. An implementation is free to perform - * arbitrary initialization. The object returned by this method can be - * queried using the {@link #get()} method. - * - * @return a result object - * @throws Exception if an error occurs - */ - protected abstract T initialize() throws Exception; - - /** - * Creates a task for the background initialization. The {@code Callable} - * object returned by this method is passed to the {@code ExecutorService}. - * This implementation returns a task that invokes the {@link #initialize()} - * method. If a temporary {@code ExecutorService} is used, it is destroyed - * at the end of the task. - * - * @param execDestroy the {@code ExecutorService} to be destroyed by the - * task - * @return a task for the background initialization - */ - private Callable createTask(ExecutorService execDestroy) { - return new InitializationTask(execDestroy); - } - - /** - * Creates the {@code ExecutorService} to be used. This method is called if - * no {@code ExecutorService} was provided at construction time. - * - * @return the {@code ExecutorService} to be used - */ - private ExecutorService createExecutor() { - return Executors.newFixedThreadPool(getTaskCount()); - } - - private class InitializationTask implements Callable { - /** Stores the executor service to be destroyed at the end. */ - private final ExecutorService execFinally; - - /** - * Creates a new instance of {@code InitializationTask} and initializes - * it with the {@code ExecutorService} to be destroyed at the end. - * - * @param exec the {@code ExecutorService} - */ - public InitializationTask(ExecutorService exec) { - execFinally = exec; - } - - /** - * Initiates initialization and returns the result. - * - * @return the result object - * @throws Exception if an error occurs - */ - public T call() throws Exception { - try { - return initialize(); - } finally { - if (execFinally != null) { - execFinally.shutdown(); - } - } - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BasicThreadFactory.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BasicThreadFactory.java deleted file mode 100644 index 72fe8646..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/BasicThreadFactory.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicLong; - -/** - *

- * An implementation of the {@code ThreadFactory} interface that provides some - * configuration options for the threads it creates. - *

- *

- * A {@code ThreadFactory} is used for instance by an {@code ExecutorService} to - * create the threads it uses for executing tasks. In many cases users do not - * have to care about a {@code ThreadFactory} because the default one used by an - * {@code ExecutorService} will do. However, if there are special requirements - * for the threads, a custom {@code ThreadFactory} has to be created. - *

- *

- * This class provides some frequently needed configuration options for the - * threads it creates. These are the following: - *

    - *
  • A name pattern for the threads created by this factory can be specified. - * This is often useful if an application uses multiple executor services for - * different purposes. If the names of the threads used by these services have - * meaningful names, log output or exception traces can be much easier to read. - * Naming patterns are format strings as used by the {@code - * String.format()} method. The string can contain the place holder {@code %d} - * which will be replaced by the number of the current thread ({@code - * ThreadFactoryImpl} keeps a counter of the threads it has already created). - * For instance, the naming pattern {@code "My %d. worker thread"} will result - * in thread names like {@code "My 1. worker thread"}, {@code - * "My 2. worker thread"} and so on.
  • - *
  • A flag whether the threads created by this factory should be daemon - * threads. This can impact the exit behavior of the current Java application - * because the JVM shuts down if there are only daemon threads running.
  • - *
  • The priority of the thread. Here an integer value can be provided. The - * {@code java.lang.Thread} class defines constants for valid ranges of priority - * values.
  • - *
  • The {@code UncaughtExceptionHandler} for the thread. This handler is - * called if an uncaught exception occurs within the thread.
  • - *
- *

- *

- * {@code BasicThreadFactory} wraps another thread factory which actually - * creates new threads. The configuration options are set on the threads created - * by the wrapped thread factory. On construction time the factory to be wrapped - * can be specified. If none is provided, a default {@code ThreadFactory} is - * used. - *

- *

- * Instances of {@code BasicThreadFactory} are not created directly, but the - * nested {@code Builder} class is used for this purpose. Using the builder only - * the configuration options an application is interested in need to be set. The - * following example shows how a {@code BasicThreadFactory} is created and - * installed in an {@code ExecutorService}: - * - *

- * // Create a factory that produces daemon threads with a naming pattern and
- * // a priority
- * BasicThreadFactory factory = new BasicThreadFactory.Builder()
- *     .namingPattern("workerthread-%d")
- *     .daemon(true)
- *     .priority(Thread.MAX_PRIORITY)
- *     .build();
- * // Create an executor service for single-threaded execution
- * ExecutorService exec = Executors.newSingleThreadExecutor(factory);
- * 
- *

- * - * @since 3.0 - * @version $Id: BasicThreadFactory.java 1079423 2011-03-08 16:38:09Z sebb $ - */ -public class BasicThreadFactory implements ThreadFactory { - /** A counter for the threads created by this factory. */ - private final AtomicLong threadCounter; - - /** Stores the wrapped factory. */ - private final ThreadFactory wrappedFactory; - - /** Stores the uncaught exception handler. */ - private final Thread.UncaughtExceptionHandler uncaughtExceptionHandler; - - /** Stores the naming pattern for newly created threads. */ - private final String namingPattern; - - /** Stores the priority. */ - private final Integer priority; - - /** Stores the daemon status flag. */ - private final Boolean daemonFlag; - - /** - * Creates a new instance of {@code ThreadFactoryImpl} and configures it - * from the specified {@code Builder} object. - * - * @param builder the {@code Builder} object - */ - private BasicThreadFactory(Builder builder) { - if (builder.wrappedFactory == null) { - wrappedFactory = Executors.defaultThreadFactory(); - } else { - wrappedFactory = builder.wrappedFactory; - } - - namingPattern = builder.namingPattern; - priority = builder.priority; - daemonFlag = builder.daemonFlag; - uncaughtExceptionHandler = builder.exceptionHandler; - - threadCounter = new AtomicLong(); - } - - /** - * Returns the wrapped {@code ThreadFactory}. This factory is used for - * actually creating threads. This method never returns null. If no - * {@code ThreadFactory} was passed when this object was created, a default - * thread factory is returned. - * - * @return the wrapped {@code ThreadFactory} - */ - public final ThreadFactory getWrappedFactory() { - return wrappedFactory; - } - - /** - * Returns the naming pattern for naming newly created threads. Result can - * be null if no naming pattern was provided. - * - * @return the naming pattern - */ - public final String getNamingPattern() { - return namingPattern; - } - - /** - * Returns the daemon flag. This flag determines whether newly created - * threads should be daemon threads. If true, this factory object - * calls {@code setDaemon(true)} on the newly created threads. Result can be - * null if no daemon flag was provided at creation time. - * - * @return the daemon flag - */ - public final Boolean getDaemonFlag() { - return daemonFlag; - } - - /** - * Returns the priority of the threads created by this factory. Result can - * be null if no priority was specified. - * - * @return the priority for newly created threads - */ - public final Integer getPriority() { - return priority; - } - - /** - * Returns the {@code UncaughtExceptionHandler} for the threads created by - * this factory. Result can be null if no handler was provided. - * - * @return the {@code UncaughtExceptionHandler} - */ - public final Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { - return uncaughtExceptionHandler; - } - - /** - * Returns the number of threads this factory has already created. This - * class maintains an internal counter that is incremented each time the - * {@link #newThread(Runnable)} method is invoked. - * - * @return the number of threads created by this factory - */ - public long getThreadCount() { - return threadCounter.get(); - } - - /** - * Creates a new thread. This implementation delegates to the wrapped - * factory for creating the thread. Then, on the newly created thread the - * corresponding configuration options are set. - * - * @param r the {@code Runnable} to be executed by the new thread - * @return the newly created thread - */ - public Thread newThread(Runnable r) { - Thread t = getWrappedFactory().newThread(r); - initializeThread(t); - - return t; - } - - /** - * Initializes the specified thread. This method is called by - * {@link #newThread(Runnable)} after a new thread has been obtained from - * the wrapped thread factory. It initializes the thread according to the - * options set for this factory. - * - * @param t the thread to be initialized - */ - private void initializeThread(Thread t) { - - if (getNamingPattern() != null) { - Long count = Long.valueOf(threadCounter.incrementAndGet()); - t.setName(String.format(getNamingPattern(), count)); - } - - if (getUncaughtExceptionHandler() != null) { - t.setUncaughtExceptionHandler(getUncaughtExceptionHandler()); - } - - if (getPriority() != null) { - t.setPriority(getPriority().intValue()); - } - - if (getDaemonFlag() != null) { - t.setDaemon(getDaemonFlag().booleanValue()); - } - } - - /** - *

- * A builder class for creating instances of {@code - * BasicThreadFactory}. - *

- *

- * Using this builder class instances of {@code BasicThreadFactory} can be - * created and initialized. The class provides methods that correspond to - * the configuration options supported by {@code BasicThreadFactory}. Method - * chaining is supported. Refer to the documentation of {@code - * BasicThreadFactory} for a usage example. - *

- * - * @version $Id: BasicThreadFactory.java 1079423 2011-03-08 16:38:09Z sebb $ - */ - public static class Builder - implements external.org.apache.commons.lang3.builder.Builder { - - /** The wrapped factory. */ - private ThreadFactory wrappedFactory; - - /** The uncaught exception handler. */ - private Thread.UncaughtExceptionHandler exceptionHandler; - - /** The naming pattern. */ - private String namingPattern; - - /** The priority. */ - private Integer priority; - - /** The daemon flag. */ - private Boolean daemonFlag; - - /** - * Sets the {@code ThreadFactory} to be wrapped by the new {@code - * BasicThreadFactory}. - * - * @param factory the wrapped {@code ThreadFactory} (must not be - * null) - * @return a reference to this {@code Builder} - * @throws NullPointerException if the passed in {@code ThreadFactory} - * is null - */ - public Builder wrappedFactory(ThreadFactory factory) { - if (factory == null) { - throw new NullPointerException( - "Wrapped ThreadFactory must not be null!"); - } - - wrappedFactory = factory; - return this; - } - - /** - * Sets the naming pattern to be used by the new {@code - * BasicThreadFactory}. - * - * @param pattern the naming pattern (must not be null) - * @return a reference to this {@code Builder} - * @throws NullPointerException if the naming pattern is null - */ - public Builder namingPattern(String pattern) { - if (pattern == null) { - throw new NullPointerException( - "Naming pattern must not be null!"); - } - - namingPattern = pattern; - return this; - } - - /** - * Sets the daemon flag for the new {@code BasicThreadFactory}. If this - * flag is set to true the new thread factory will create daemon - * threads. - * - * @param f the value of the daemon flag - * @return a reference to this {@code Builder} - */ - public Builder daemon(boolean f) { - daemonFlag = Boolean.valueOf(f); - return this; - } - - /** - * Sets the priority for the threads created by the new {@code - * BasicThreadFactory}. - * - * @param prio the priority - * @return a reference to this {@code Builder} - */ - public Builder priority(int prio) { - priority = Integer.valueOf(prio); - return this; - } - - /** - * Sets the uncaught exception handler for the threads created by the - * new {@code BasicThreadFactory}. - * - * @param handler the {@code UncaughtExceptionHandler} (must not be - * null) - * @return a reference to this {@code Builder} - * @throws NullPointerException if the exception handler is null - */ - public Builder uncaughtExceptionHandler( - Thread.UncaughtExceptionHandler handler) { - if (handler == null) { - throw new NullPointerException( - "Uncaught exception handler must not be null!"); - } - - exceptionHandler = handler; - return this; - } - - /** - * Resets this builder. All configuration options are set to default - * values. Note: If the {@link #build()} method was called, it is not - * necessary to call {@code reset()} explicitly because this is done - * automatically. - */ - public void reset() { - wrappedFactory = null; - exceptionHandler = null; - namingPattern = null; - priority = null; - daemonFlag = null; - } - - /** - * Creates a new {@code BasicThreadFactory} with all configuration - * options that have been specified by calling methods on this builder. - * After creating the factory {@link #reset()} is called. - * - * @return the new {@code BasicThreadFactory} - */ - public BasicThreadFactory build() { - BasicThreadFactory factory = new BasicThreadFactory(this); - reset(); - return factory; - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java deleted file mode 100644 index eb6b7dda..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; - -/** - *

- * A specialized {@link BackgroundInitializer} implementation that wraps a - * {@code Callable} object. - *

- *

- * An instance of this class is initialized with a {@code Callable} object when - * it is constructed. The implementation of the {@link #initialize()} method - * defined in the super class delegates to this {@code Callable} so that the - * {@code Callable} is executed in the background thread. - *

- *

- * The {@code java.util.concurrent.Callable} interface is a standard mechanism - * of the JDK to define tasks to be executed by another thread. The {@code - * CallableBackgroundInitializer} class allows combining this standard interface - * with the background initializer API. - *

- *

- * Usage of this class is very similar to the default usage pattern of the - * {@link BackgroundInitializer} class: Just create an instance and provide the - * {@code Callable} object to be executed, then call the initializer's - * {@link #start()} method. This causes the {@code Callable} to be executed in - * another thread. When the results of the {@code Callable} are needed the - * initializer's {@link #get()} method can be called (which may block until - * background execution is complete). The following code fragment shows a - * typical usage example: - * - *

- * // a Callable that performs a complex computation
- * Callable<Integer> computationCallable = new MyComputationCallable();
- * // setup the background initializer
- * CallableBackgroundInitializer<Integer> initializer =
- *     new CallableBackgroundInitializer(computationCallable);
- * initializer.start();
- * // Now do some other things. Initialization runs in a parallel thread
- * ...
- * // Wait for the end of initialization and access the result
- * Integer result = initializer.get();
- * 
- * - *

- * - * @since 3.0 - * @version $Id: CallableBackgroundInitializer.java 1082044 2011-03-16 04:26:58Z bayard $ - * @param the type of the object managed by this initializer class - */ -public class CallableBackgroundInitializer extends BackgroundInitializer { - /** The Callable to be executed. */ - private final Callable callable; - - /** - * Creates a new instance of {@code CallableBackgroundInitializer} and sets - * the {@code Callable} to be executed in a background thread. - * - * @param call the {@code Callable} (must not be null) - * @throws IllegalArgumentException if the {@code Callable} is null - */ - public CallableBackgroundInitializer(Callable call) { - checkCallable(call); - callable = call; - } - - /** - * Creates a new instance of {@code CallableBackgroundInitializer} and - * initializes it with the {@code Callable} to be executed in a background - * thread and the {@code ExecutorService} for managing the background - * execution. - * - * @param call the {@code Callable} (must not be null) - * @param exec an external {@code ExecutorService} to be used for task - * execution - * @throws IllegalArgumentException if the {@code Callable} is null - */ - public CallableBackgroundInitializer(Callable call, ExecutorService exec) { - super(exec); - checkCallable(call); - callable = call; - } - - /** - * Performs initialization in a background thread. This implementation - * delegates to the {@code Callable} passed at construction time of this - * object. - * - * @return the result of the initialization - * @throws Exception if an error occurs - */ - @Override - protected T initialize() throws Exception { - return callable.call(); - } - - /** - * Tests the passed in {@code Callable} and throws an exception if it is - * undefined. - * - * @param call the object to check - * @throws IllegalArgumentException if the {@code Callable} is null - */ - private void checkCallable(Callable call) { - if (call == null) { - throw new IllegalArgumentException("Callable must not be null!"); - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentException.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentException.java deleted file mode 100644 index 999f851f..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentException.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -/** - *

- * An exception class used for reporting error conditions related to accessing - * data of background tasks. - *

- *

- * The purpose of this exception class is analogous to the default JDK exception - * class {@link java.util.concurrent.ExecutionException}, i.e. it wraps an - * exception that occurred during the execution of a task. However, in contrast - * to {@code ExecutionException}, it wraps only checked exceptions. Runtime - * exceptions are thrown directly. - *

- * - * @since 3.0 - * @version $Id: ConcurrentException.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class ConcurrentException extends Exception { - /** - * The serial version UID. - */ - private static final long serialVersionUID = 6622707671812226130L; - - /** - * Creates a new, uninitialized instance of {@code ConcurrentException}. - */ - protected ConcurrentException() { - super(); - } - - /** - * Creates a new instance of {@code ConcurrentException} and initializes it - * with the given cause. - * - * @param cause the cause of this exception - * @throws IllegalArgumentException if the cause is not a checked exception - */ - public ConcurrentException(Throwable cause) { - super(ConcurrentUtils.checkedException(cause)); - } - - /** - * Creates a new instance of {@code ConcurrentException} and initializes it - * with the given message and cause. - * - * @param msg the error message - * @param cause the cause of this exception - * @throws IllegalArgumentException if the cause is not a checked exception - */ - public ConcurrentException(String msg, Throwable cause) { - super(msg, ConcurrentUtils.checkedException(cause)); - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentInitializer.java deleted file mode 100644 index 95c4e637..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentInitializer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -/** - *

- * Definition of an interface for the thread-safe initialization of objects. - *

- *

- * The idea behind this interface is to provide access to an object in a - * thread-safe manner. A {@code ConcurrentInitializer} can be passed to multiple - * threads which can all access the object produced by the initializer. Through - * the {@link #get()} method the object can be queried. - *

- *

- * Concrete implementations of this interface will use different strategies for - * the creation of the managed object, e.g. lazy initialization or - * initialization in a background thread. This is completely transparent to - * client code, so it is possible to change the initialization strategy without - * affecting clients. - *

- * - * @since 3.0 - * @version $Id: ConcurrentInitializer.java 1088899 2011-04-05 05:31:27Z bayard $ - * @param the type of the object managed by this initializer class - */ -public interface ConcurrentInitializer { - /** - * Returns the fully initialized object produced by this {@code - * ConcurrentInitializer}. A concrete implementation here returns the - * results of the initialization process. This method may block until - * results are available. Typically, once created the result object is - * always the same. - * - * @return the object created by this {@code ConcurrentException} - * @throws ConcurrentException if an error occurred during initialization of - * the object - */ - T get() throws ConcurrentException; -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentRuntimeException.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentRuntimeException.java deleted file mode 100644 index 3d4bd85d..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentRuntimeException.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -/** - *

- * An exception class used for reporting runtime error conditions related to - * accessing data of background tasks. - *

- *

- * This class is an analogon of the {@link ConcurrentException} exception class. - * However, it is a runtime exception and thus does not need explicit catch - * clauses. Some methods of {@link ConcurrentUtils} throw {@code - * ConcurrentRuntimeException} exceptions rather than - * {@link ConcurrentException} exceptions. They can be used by client code that - * does not want to be bothered with checked exceptions. - *

- * - * @since 3.0 - * @version $Id: ConcurrentRuntimeException.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class ConcurrentRuntimeException extends RuntimeException { - /** - * The serial version UID. - */ - private static final long serialVersionUID = -6582182735562919670L; - - /** - * Creates a new, uninitialized instance of {@code - * ConcurrentRuntimeException}. - */ - protected ConcurrentRuntimeException() { - super(); - } - - /** - * Creates a new instance of {@code ConcurrentRuntimeException} and - * initializes it with the given cause. - * - * @param cause the cause of this exception - * @throws IllegalArgumentException if the cause is not a checked exception - */ - public ConcurrentRuntimeException(Throwable cause) { - super(ConcurrentUtils.checkedException(cause)); - } - - /** - * Creates a new instance of {@code ConcurrentRuntimeException} and - * initializes it with the given message and cause. - * - * @param msg the error message - * @param cause the cause of this exception - * @throws IllegalArgumentException if the cause is not a checked exception - */ - public ConcurrentRuntimeException(String msg, Throwable cause) { - super(msg, ConcurrentUtils.checkedException(cause)); - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentUtils.java deleted file mode 100644 index 1070fe3c..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConcurrentUtils.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -/** - *

- * An utility class providing functionality related to the {@code - * java.util.concurrent} package. - *

- * - * @since 3.0 - * @version $Id: ConcurrentUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class ConcurrentUtils { - - /** - * Private constructor so that no instances can be created. This class - * contains only static utility methods. - */ - private ConcurrentUtils() { - } - - /** - * Inspects the cause of the specified {@code ExecutionException} and - * creates a {@code ConcurrentException} with the checked cause if - * necessary. This method performs the following checks on the cause of the - * passed in exception: - *
    - *
  • If the passed in exception is null or the cause is - * null, this method returns null.
  • - *
  • If the cause is a runtime exception, it is directly thrown.
  • - *
  • If the cause is an error, it is directly thrown, too.
  • - *
  • In any other case the cause is a checked exception. The method then - * creates a {@link ConcurrentException}, initializes it with the cause, and - * returns it.
  • - *
- * - * @param ex the exception to be processed - * @return a {@code ConcurrentException} with the checked cause - */ - public static ConcurrentException extractCause(ExecutionException ex) { - if (ex == null || ex.getCause() == null) { - return null; - } - - throwCause(ex); - return new ConcurrentException(ex.getMessage(), ex.getCause()); - } - - /** - * Inspects the cause of the specified {@code ExecutionException} and - * creates a {@code ConcurrentRuntimeException} with the checked cause if - * necessary. This method works exactly like - * {@link #extractCause(ExecutionException)}. The only difference is that - * the cause of the specified {@code ExecutionException} is extracted as a - * runtime exception. This is an alternative for client code that does not - * want to deal with checked exceptions. - * - * @param ex the exception to be processed - * @return a {@code ConcurrentRuntimeException} with the checked cause - */ - public static ConcurrentRuntimeException extractCauseUnchecked( - ExecutionException ex) { - if (ex == null || ex.getCause() == null) { - return null; - } - - throwCause(ex); - return new ConcurrentRuntimeException(ex.getMessage(), ex.getCause()); - } - - /** - * Handles the specified {@code ExecutionException}. This method calls - * {@link #extractCause(ExecutionException)} for obtaining the cause of the - * exception - which might already cause an unchecked exception or an error - * being thrown. If the cause is a checked exception however, it is wrapped - * in a {@code ConcurrentException}, which is thrown. If the passed in - * exception is null or has no cause, the method simply returns - * without throwing an exception. - * - * @param ex the exception to be handled - * @throws ConcurrentException if the cause of the {@code - * ExecutionException} is a checked exception - */ - public static void handleCause(ExecutionException ex) - throws ConcurrentException { - ConcurrentException cex = extractCause(ex); - - if (cex != null) { - throw cex; - } - } - - /** - * Handles the specified {@code ExecutionException} and transforms it into a - * runtime exception. This method works exactly like - * {@link #handleCause(ExecutionException)}, but instead of a - * {@link ConcurrentException} it throws a - * {@link ConcurrentRuntimeException}. This is an alternative for client - * code that does not want to deal with checked exceptions. - * - * @param ex the exception to be handled - * @throws ConcurrentRuntimeException if the cause of the {@code - * ExecutionException} is a checked exception; this exception is then - * wrapped in the thrown runtime exception - */ - public static void handleCauseUnchecked(ExecutionException ex) { - ConcurrentRuntimeException crex = extractCauseUnchecked(ex); - - if (crex != null) { - throw crex; - } - } - - /** - * Tests whether the specified {@code Throwable} is a checked exception. If - * not, an exception is thrown. - * - * @param ex the {@code Throwable} to check - * @return a flag whether the passed in exception is a checked exception - * @throws IllegalArgumentException if the {@code Throwable} is not a - * checked exception - */ - static Throwable checkedException(Throwable ex) { - if (ex != null && !(ex instanceof RuntimeException) - && !(ex instanceof Error)) { - return ex; - } else { - throw new IllegalArgumentException("Not a checked exception: " + ex); - } - } - - /** - * Tests whether the cause of the specified {@code ExecutionException} - * should be thrown and does it if necessary. - * - * @param ex the exception in question - */ - private static void throwCause(ExecutionException ex) { - if (ex.getCause() instanceof RuntimeException) { - throw (RuntimeException) ex.getCause(); - } - - if (ex.getCause() instanceof Error) { - throw (Error) ex.getCause(); - } - } - - //----------------------------------------------------------------------- - /** - * Invokes the specified {@code ConcurrentInitializer} and returns the - * object produced by the initializer. This method just invokes the {@code - * get()} method of the given {@code ConcurrentInitializer}. It is - * null-safe: if the argument is null, result is also - * null. - * - * @param the type of the object produced by the initializer - * @param initializer the {@code ConcurrentInitializer} to be invoked - * @return the object managed by the {@code ConcurrentInitializer} - * @throws ConcurrentException if the {@code ConcurrentInitializer} throws - * an exception - */ - public static T initialize(ConcurrentInitializer initializer) - throws ConcurrentException { - return initializer != null ? initializer.get() : null; - } - - /** - * Invokes the specified {@code ConcurrentInitializer} and transforms - * occurring exceptions to runtime exceptions. This method works like - * {@link #initialize(ConcurrentInitializer)}, but if the {@code - * ConcurrentInitializer} throws a {@link ConcurrentException}, it is - * caught, and the cause is wrapped in a {@link ConcurrentRuntimeException}. - * So client code does not have to deal with checked exceptions. - * - * @param the type of the object produced by the initializer - * @param initializer the {@code ConcurrentInitializer} to be invoked - * @return the object managed by the {@code ConcurrentInitializer} - * @throws ConcurrentRuntimeException if the initializer throws an exception - */ - public static T initializeUnchecked(ConcurrentInitializer initializer) { - try { - return initialize(initializer); - } catch (ConcurrentException cex) { - throw new ConcurrentRuntimeException(cex.getCause()); - } - } - - //----------------------------------------------------------------------- - /** - *

- * Puts a value in the specified {@code ConcurrentMap} if the key is not yet - * present. This method works similar to the {@code putIfAbsent()} method of - * the {@code ConcurrentMap} interface, but the value returned is different. - * Basically, this method is equivalent to the following code fragment: - * - *

-     * if (!map.containsKey(key)) {
-     *     map.put(key, value);
-     *     return value;
-     * } else {
-     *     return map.get(key);
-     * }
-     * 
- * - * except that the action is performed atomically. So this method always - * returns the value which is stored in the map. - *

- *

- * This method is null-safe: It accepts a null map as input - * without throwing an exception. In this case the return value is - * null, too. - *

- * - * @param the type of the keys of the map - * @param the type of the values of the map - * @param map the map to be modified - * @param key the key of the value to be added - * @param value the value to be added - * @return the value stored in the map after this operation - */ - public static V putIfAbsent(ConcurrentMap map, K key, V value) { - if (map == null) { - return null; - } - - V result = map.putIfAbsent(key, value); - return result != null ? result : value; - } - - /** - * Checks if a concurrent map contains a key and creates a corresponding - * value if not. This method first checks the presence of the key in the - * given map. If it is already contained, its value is returned. Otherwise - * the {@code get()} method of the passed in {@link ConcurrentInitializer} - * is called. With the resulting object - * {@link #putIfAbsent(ConcurrentMap, Object, Object)} is called. This - * handles the case that in the meantime another thread has added the key to - * the map. Both the map and the initializer can be null; in this - * case this method simply returns null. - * - * @param the type of the keys of the map - * @param the type of the values of the map - * @param map the map to be modified - * @param key the key of the value to be added - * @param init the {@link ConcurrentInitializer} for creating the value - * @return the value stored in the map after this operation; this may or may - * not be the object created by the {@link ConcurrentInitializer} - * @throws ConcurrentException if the initializer throws an exception - */ - public static V createIfAbsent(ConcurrentMap map, K key, - ConcurrentInitializer init) throws ConcurrentException { - if (map == null || init == null) { - return null; - } - - V value = map.get(key); - if (value == null) { - return putIfAbsent(map, key, init.get()); - } - return value; - } - - /** - * Checks if a concurrent map contains a key and creates a corresponding - * value if not, suppressing checked exceptions. This method calls - * {@code createIfAbsent()}. If a {@link ConcurrentException} is thrown, it - * is caught and re-thrown as a {@link ConcurrentRuntimeException}. - * - * @param the type of the keys of the map - * @param the type of the values of the map - * @param map the map to be modified - * @param key the key of the value to be added - * @param init the {@link ConcurrentInitializer} for creating the value - * @return the value stored in the map after this operation; this may or may - * not be the object created by the {@link ConcurrentInitializer} - * @throws ConcurrentRuntimeException if the initializer throws an exception - */ - public static V createIfAbsentUnchecked(ConcurrentMap map, - K key, ConcurrentInitializer init) { - try { - return createIfAbsent(map, key, init); - } catch (ConcurrentException cex) { - throw new ConcurrentRuntimeException(cex.getCause()); - } - } - - //----------------------------------------------------------------------- - /** - *

- * Gets an implementation of Future that is immediately done - * and returns the specified constant value. - *

- *

- * This can be useful to return a simple constant immediately from the - * concurrent processing, perhaps as part of avoiding nulls. - * A constant future can also be useful in testing. - *

- * - * @param the type of the value used by this {@code Future} object - * @param value the constant value to return, may be null - * @return an instance of Future that will return the value, never null - */ - public static Future constantFuture(T value) { - return new ConstantFuture(value); - } - - /** - * A specialized {@code Future} implementation which wraps a constant value. - * @param the type of the value wrapped by this class - */ - static final class ConstantFuture implements Future { - /** The constant value. */ - private final T value; - - /** - * Creates a new instance of {@code ConstantFuture} and initializes it - * with the constant value. - * - * @param value the value (may be null) - */ - ConstantFuture(T value) { - this.value = value; - } - - /** - * {@inheritDoc} This implementation always returns true because - * the constant object managed by this {@code Future} implementation is - * always available. - */ - public boolean isDone() { - return true; - } - - /** - * {@inheritDoc} This implementation just returns the constant value. - */ - public T get() { - return value; - } - - /** - * {@inheritDoc} This implementation just returns the constant value; it - * does not block, therefore the timeout has no meaning. - */ - public T get(long timeout, TimeUnit unit) { - return value; - } - - /** - * {@inheritDoc} This implementation always returns false; there - * is no background process which could be cancelled. - */ - public boolean isCancelled() { - return false; - } - - /** - * {@inheritDoc} The cancel operation is not supported. This - * implementation always returns false. - */ - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConstantInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConstantInitializer.java deleted file mode 100644 index bc600e69..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/ConstantInitializer.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import external.org.apache.commons.lang3.ObjectUtils; - -/** - *

- * A very simple implementation of the {@link ConcurrentInitializer} interface - * which always returns the same object. - *

- *

- * An instance of this class is passed a reference to an object when it is - * constructed. The {@link #get()} method just returns this object. No - * synchronization is required. - *

- *

- * This class is useful for instance for unit testing or in cases where a - * specific object has to be passed to an object which expects a - * {@link ConcurrentInitializer}. - *

- * - * @since 3.0 - * @version $Id: ConstantInitializer.java 1199894 2011-11-09 17:53:59Z ggregory $ - * @param the type of the object managed by this initializer - */ -public class ConstantInitializer implements ConcurrentInitializer { - /** Constant for the format of the string representation. */ - private static final String FMT_TO_STRING = "ConstantInitializer@%d [ object = %s ]"; - - /** Stores the managed object. */ - private final T object; - - /** - * Creates a new instance of {@code ConstantInitializer} and initializes it - * with the object to be managed. The {@code get()} method will always - * return the object passed here. This class does not place any restrictions - * on the object. It may be null, then {@code get()} will return - * null, too. - * - * @param obj the object to be managed by this initializer - */ - public ConstantInitializer(T obj) { - object = obj; - } - - /** - * Directly returns the object that was passed to the constructor. This is - * the same object as returned by {@code get()}. However, this method does - * not declare that it throws an exception. - * - * @return the object managed by this initializer - */ - public final T getObject() { - return object; - } - - /** - * Returns the object managed by this initializer. This implementation just - * returns the object passed to the constructor. - * - * @return the object managed by this initializer - * @throws ConcurrentException if an error occurs - */ - public T get() throws ConcurrentException { - return getObject(); - } - - /** - * Returns a hash code for this object. This implementation returns the hash - * code of the managed object. - * - * @return a hash code for this object - */ - @Override - public int hashCode() { - return getObject() != null ? getObject().hashCode() : 0; - } - - /** - * Compares this object with another one. This implementation returns - * true if and only if the passed in object is an instance of - * {@code ConstantInitializer} which refers to an object equals to the - * object managed by this instance. - * - * @param obj the object to compare to - * @return a flag whether the objects are equal - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof ConstantInitializer)) { - return false; - } - - ConstantInitializer c = (ConstantInitializer) obj; - return ObjectUtils.equals(getObject(), c.getObject()); - } - - /** - * Returns a string representation for this object. This string also - * contains a string representation of the object managed by this - * initializer. - * - * @return a string for this object - */ - @Override - public String toString() { - return String.format(FMT_TO_STRING, Integer.valueOf(System.identityHashCode(this)), - String.valueOf(getObject())); - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/LazyInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/LazyInitializer.java deleted file mode 100644 index c99b644f..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/LazyInitializer.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -/** - *

- * This class provides a generic implementation of the lazy initialization - * pattern. - *

- *

- * Sometimes an application has to deal with an object only under certain - * circumstances, e.g. when the user selects a specific menu item or if a - * special event is received. If the creation of the object is costly or the - * consumption of memory or other system resources is significant, it may make - * sense to defer the creation of this object until it is really needed. This is - * a use case for the lazy initialization pattern. - *

- *

- * This abstract base class provides an implementation of the double-check idiom - * for an instance field as discussed in Joshua Bloch's "Effective Java", 2nd - * edition, item 71. The class already implements all necessary synchronization. - * A concrete subclass has to implement the {@code initialize()} method, which - * actually creates the wrapped data object. - *

- *

- * As an usage example consider that we have a class {@code ComplexObject} whose - * instantiation is a complex operation. In order to apply lazy initialization - * to this class, a subclass of {@code LazyInitializer} has to be created: - * - *

- * public class ComplexObjectInitializer extends LazyInitializer<ComplexObject> {
- *     @Override
- *     protected ComplexObject initialize() {
- *         return new ComplexObject();
- *     }
- * }
- * 
- * - * Access to the data object is provided through the {@code get()} method. So, - * code that wants to obtain the {@code ComplexObject} instance would simply - * look like this: - * - *
- * // Create an instance of the lazy initializer
- * ComplexObjectInitializer initializer = new ComplexObjectInitializer();
- * ...
- * // When the object is actually needed:
- * ComplexObject cobj = initializer.get();
- * 
- * - *

- *

- * If multiple threads call the {@code get()} method when the object has not yet - * been created, they are blocked until initialization completes. The algorithm - * guarantees that only a single instance of the wrapped object class is - * created, which is passed to all callers. Once initialized, calls to the - * {@code get()} method are pretty fast because no synchronization is needed - * (only an access to a volatile member field). - *

- * - * @since 3.0 - * @version $Id: LazyInitializer.java 1088899 2011-04-05 05:31:27Z bayard $ - * @param the type of the object managed by this initializer class - */ -public abstract class LazyInitializer implements ConcurrentInitializer { - /** Stores the managed object. */ - private volatile T object; - - /** - * Returns the object wrapped by this instance. On first access the object - * is created. After that it is cached and can be accessed pretty fast. - * - * @return the object initialized by this {@code LazyInitializer} - * @throws ConcurrentException if an error occurred during initialization of - * the object - */ - public T get() throws ConcurrentException { - // use a temporary variable to reduce the number of reads of the - // volatile field - T result = object; - - if (result == null) { - synchronized (this) { - result = object; - if (result == null) { - object = result = initialize(); - } - } - } - - return result; - } - - /** - * Creates and initializes the object managed by this {@code - * LazyInitializer}. This method is called by {@link #get()} when the object - * is accessed for the first time. An implementation can focus on the - * creation of the object. No synchronization is needed, as this is already - * handled by {@code get()}. - * - * @return the managed data object - * @throws ConcurrentException if an error occurs during object creation - */ - protected abstract T initialize() throws ConcurrentException; -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java deleted file mode 100644 index cea6e3f6..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.concurrent.ExecutorService; - -/** - *

- * A specialized {@link BackgroundInitializer} implementation that can deal with - * multiple background initialization tasks. - *

- *

- * This class has a similar purpose as {@link BackgroundInitializer}. However, - * it is not limited to a single background initialization task. Rather it - * manages an arbitrary number of {@code BackgroundInitializer} objects, - * executes them, and waits until they are completely initialized. This is - * useful for applications that have to perform multiple initialization tasks - * that can run in parallel (i.e. that do not depend on each other). This class - * takes care about the management of an {@code ExecutorService} and shares it - * with the {@code BackgroundInitializer} objects it is responsible for; so the - * using application need not bother with these details. - *

- *

- * The typical usage scenario for {@code MultiBackgroundInitializer} is as - * follows: - *

    - *
  • Create a new instance of the class. Optionally pass in a pre-configured - * {@code ExecutorService}. Alternatively {@code MultiBackgroundInitializer} can - * create a temporary {@code ExecutorService} and delete it after initialization - * is complete.
  • - *
  • Create specialized {@link BackgroundInitializer} objects for the - * initialization tasks to be performed and add them to the {@code - * MultiBackgroundInitializer} using the - * {@link #addInitializer(String, BackgroundInitializer)} method.
  • - *
  • After all initializers have been added, call the {@link #start()} method. - *
  • - *
  • When access to the result objects produced by the {@code - * BackgroundInitializer} objects is needed call the {@link #get()} method. The - * object returned here provides access to all result objects created during - * initialization. It also stores information about exceptions that have - * occurred.
  • - *
- *

- *

- * {@code MultiBackgroundInitializer} starts a special controller task that - * starts all {@code BackgroundInitializer} objects added to the instance. - * Before the an initializer is started it is checked whether this initializer - * already has an {@code ExecutorService} set. If this is the case, this {@code - * ExecutorService} is used for running the background task. Otherwise the - * current {@code ExecutorService} of this {@code MultiBackgroundInitializer} is - * shared with the initializer. - *

- *

- * The easiest way of using this class is to let it deal with the management of - * an {@code ExecutorService} itself: If no external {@code ExecutorService} is - * provided, the class creates a temporary {@code ExecutorService} (that is - * capable of executing all background tasks in parallel) and destroys it at the - * end of background processing. - *

- *

- * Alternatively an external {@code ExecutorService} can be provided - either at - * construction time or later by calling the - * {@link #setExternalExecutor(ExecutorService)} method. In this case all - * background tasks are scheduled at this external {@code ExecutorService}. - * Important note: When using an external {@code - * ExecutorService} be sure that the number of threads managed by the service is - * large enough. Otherwise a deadlock can happen! This is the case in the - * following scenario: {@code MultiBackgroundInitializer} starts a task that - * starts all registered {@code BackgroundInitializer} objects and waits for - * their completion. If for instance a single threaded {@code ExecutorService} - * is used, none of the background tasks can be executed, and the task created - * by {@code MultiBackgroundInitializer} waits forever. - *

- * - * @since 3.0 - * @version $Id: MultiBackgroundInitializer.java 1082301 2011-03-16 21:02:15Z oheger $ - */ -public class MultiBackgroundInitializer - extends - BackgroundInitializer { - /** A map with the child initializers. */ - private final Map> childInitializers = - new HashMap>(); - - /** - * Creates a new instance of {@code MultiBackgroundInitializer}. - */ - public MultiBackgroundInitializer() { - super(); - } - - /** - * Creates a new instance of {@code MultiBackgroundInitializer} and - * initializes it with the given external {@code ExecutorService}. - * - * @param exec the {@code ExecutorService} for executing the background - * tasks - */ - public MultiBackgroundInitializer(ExecutorService exec) { - super(exec); - } - - /** - * Adds a new {@code BackgroundInitializer} to this object. When this - * {@code MultiBackgroundInitializer} is started, the given initializer will - * be processed. This method must not be called after {@link #start()} has - * been invoked. - * - * @param name the name of the initializer (must not be null) - * @param init the {@code BackgroundInitializer} to add (must not be - * null) - * @throws IllegalArgumentException if a required parameter is missing - * @throws IllegalStateException if {@code start()} has already been called - */ - public void addInitializer(String name, BackgroundInitializer init) { - if (name == null) { - throw new IllegalArgumentException( - "Name of child initializer must not be null!"); - } - if (init == null) { - throw new IllegalArgumentException( - "Child initializer must not be null!"); - } - - synchronized (this) { - if (isStarted()) { - throw new IllegalStateException( - "addInitializer() must not be called after start()!"); - } - childInitializers.put(name, init); - } - } - - /** - * Returns the number of tasks needed for executing all child {@code - * BackgroundInitializer} objects in parallel. This implementation sums up - * the required tasks for all child initializers (which is necessary if one - * of the child initializers is itself a {@code MultiBackgroundInitializer} - * ). Then it adds 1 for the control task that waits for the completion of - * the children. - * - * @return the number of tasks required for background processing - */ - @Override - protected int getTaskCount() { - int result = 1; - - for (BackgroundInitializer bi : childInitializers.values()) { - result += bi.getTaskCount(); - } - - return result; - } - - /** - * Creates the results object. This implementation starts all child {@code - * BackgroundInitializer} objects. Then it collects their results and - * creates a {@code MultiBackgroundInitializerResults} object with this - * data. If a child initializer throws a checked exceptions, it is added to - * the results object. Unchecked exceptions are propagated. - * - * @return the results object - * @throws Exception if an error occurs - */ - @Override - protected MultiBackgroundInitializerResults initialize() throws Exception { - Map> inits; - synchronized (this) { - // create a snapshot to operate on - inits = new HashMap>( - childInitializers); - } - - // start the child initializers - ExecutorService exec = getActiveExecutor(); - for (BackgroundInitializer bi : inits.values()) { - if (bi.getExternalExecutor() == null) { - // share the executor service if necessary - bi.setExternalExecutor(exec); - } - bi.start(); - } - - // collect the results - Map results = new HashMap(); - Map excepts = new HashMap(); - for (Map.Entry> e : inits.entrySet()) { - try { - results.put(e.getKey(), e.getValue().get()); - } catch (ConcurrentException cex) { - excepts.put(e.getKey(), cex); - } - } - - return new MultiBackgroundInitializerResults(inits, results, excepts); - } - - /** - * A data class for storing the results of the background initialization - * performed by {@code MultiBackgroundInitializer}. Objects of this inner - * class are returned by {@link MultiBackgroundInitializer#initialize()}. - * They allow access to all result objects produced by the - * {@link BackgroundInitializer} objects managed by the owning instance. It - * is also possible to retrieve status information about single - * {@link BackgroundInitializer}s, i.e. whether they completed normally or - * caused an exception. - */ - public static class MultiBackgroundInitializerResults { - /** A map with the child initializers. */ - private final Map> initializers; - - /** A map with the result objects. */ - private final Map resultObjects; - - /** A map with the exceptions. */ - private final Map exceptions; - - /** - * Creates a new instance of {@code MultiBackgroundInitializerResults} - * and initializes it with maps for the {@code BackgroundInitializer} - * objects, their result objects and the exceptions thrown by them. - * - * @param inits the {@code BackgroundInitializer} objects - * @param results the result objects - * @param excepts the exceptions - */ - private MultiBackgroundInitializerResults( - Map> inits, - Map results, - Map excepts) { - initializers = inits; - resultObjects = results; - exceptions = excepts; - } - - /** - * Returns the {@code BackgroundInitializer} with the given name. If the - * name cannot be resolved, an exception is thrown. - * - * @param name the name of the {@code BackgroundInitializer} - * @return the {@code BackgroundInitializer} with this name - * @throws NoSuchElementException if the name cannot be resolved - */ - public BackgroundInitializer getInitializer(String name) { - return checkName(name); - } - - /** - * Returns the result object produced by the {@code - * BackgroundInitializer} with the given name. This is the object - * returned by the initializer's {@code initialize()} method. If this - * {@code BackgroundInitializer} caused an exception, null is - * returned. If the name cannot be resolved, an exception is thrown. - * - * @param name the name of the {@code BackgroundInitializer} - * @return the result object produced by this {@code - * BackgroundInitializer} - * @throws NoSuchElementException if the name cannot be resolved - */ - public Object getResultObject(String name) { - checkName(name); - return resultObjects.get(name); - } - - /** - * Returns a flag whether the {@code BackgroundInitializer} with the - * given name caused an exception. - * - * @param name the name of the {@code BackgroundInitializer} - * @return a flag whether this initializer caused an exception - * @throws NoSuchElementException if the name cannot be resolved - */ - public boolean isException(String name) { - checkName(name); - return exceptions.containsKey(name); - } - - /** - * Returns the {@code ConcurrentException} object that was thrown by the - * {@code BackgroundInitializer} with the given name. If this - * initializer did not throw an exception, the return value is - * null. If the name cannot be resolved, an exception is thrown. - * - * @param name the name of the {@code BackgroundInitializer} - * @return the exception thrown by this initializer - * @throws NoSuchElementException if the name cannot be resolved - */ - public ConcurrentException getException(String name) { - checkName(name); - return exceptions.get(name); - } - - /** - * Returns a set with the names of all {@code BackgroundInitializer} - * objects managed by the {@code MultiBackgroundInitializer}. - * - * @return an (unmodifiable) set with the names of the managed {@code - * BackgroundInitializer} objects - */ - public Set initializerNames() { - return Collections.unmodifiableSet(initializers.keySet()); - } - - /** - * Returns a flag whether the whole initialization was successful. This - * is the case if no child initializer has thrown an exception. - * - * @return a flag whether the initialization was successful - */ - public boolean isSuccessful() { - return exceptions.isEmpty(); - } - - /** - * Checks whether an initializer with the given name exists. If not, - * throws an exception. If it exists, the associated child initializer - * is returned. - * - * @param name the name to check - * @return the initializer with this name - * @throws NoSuchElementException if the name is unknown - */ - private BackgroundInitializer checkName(String name) { - BackgroundInitializer init = initializers.get(name); - if (init == null) { - throw new NoSuchElementException( - "No child initializer with name " + name); - } - - return init; - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/TimedSemaphore.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/TimedSemaphore.java deleted file mode 100644 index 2e859ee0..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/TimedSemaphore.java +++ /dev/null @@ -1,421 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.concurrent; - -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - *

- * A specialized semaphore implementation that provides a number of - * permits in a given time frame. - *

- *

- * This class is similar to the {@code java.util.concurrent.Semaphore} class - * provided by the JDK in that it manages a configurable number of permits. - * Using the {@link #acquire()} method a permit can be requested by a thread. - * However, there is an additional timing dimension: there is no {@code - * release()} method for freeing a permit, but all permits are automatically - * released at the end of a configurable time frame. If a thread calls - * {@link #acquire()} and the available permits are already exhausted for this - * time frame, the thread is blocked. When the time frame ends all permits - * requested so far are restored, and blocking threads are waked up again, so - * that they can try to acquire a new permit. This basically means that in the - * specified time frame only the given number of operations is possible. - *

- *

- * A use case for this class is to artificially limit the load produced by a - * process. As an example consider an application that issues database queries - * on a production system in a background process to gather statistical - * information. This background processing should not produce so much database - * load that the functionality and the performance of the production system are - * impacted. Here a {@code TimedSemaphore} could be installed to guarantee that - * only a given number of database queries are issued per second. - *

- *

- * A thread class for performing database queries could look as follows: - * - *

- * public class StatisticsThread extends Thread {
- *     // The semaphore for limiting database load.
- *     private final TimedSemaphore semaphore;
- *     // Create an instance and set the semaphore
- *     public StatisticsThread(TimedSemaphore timedSemaphore) {
- *         semaphore = timedSemaphore;
- *     }
- *     // Gather statistics
- *     public void run() {
- *         try {
- *             while(true) {
- *                 semaphore.acquire();   // limit database load
- *                 performQuery();        // issue a query
- *             }
- *         } catch(InterruptedException) {
- *             // fall through
- *         }
- *     }
- *     ...
- * }
- * 
- * - * The following code fragment shows how a {@code TimedSemaphore} is created - * that allows only 10 operations per second and passed to the statistics - * thread: - * - *
- * TimedSemaphore sem = new TimedSemaphore(1, TimeUnit.SECOND, 10);
- * StatisticsThread thread = new StatisticsThread(sem);
- * thread.start();
- * 
- * - *

- *

- * When creating an instance the time period for the semaphore must be - * specified. {@code TimedSemaphore} uses an executor service with a - * corresponding period to monitor this interval. The {@code - * ScheduledExecutorService} to be used for this purpose can be provided at - * construction time. Alternatively the class creates an internal executor - * service. - *

- *

- * Client code that uses {@code TimedSemaphore} has to call the - * {@link #acquire()} method in aach processing step. {@code TimedSemaphore} - * keeps track of the number of invocations of the {@link #acquire()} method and - * blocks the calling thread if the counter exceeds the limit specified. When - * the timer signals the end of the time period the counter is reset and all - * waiting threads are released. Then another cycle can start. - *

- *

- * It is possible to modify the limit at any time using the - * {@link #setLimit(int)} method. This is useful if the load produced by an - * operation has to be adapted dynamically. In the example scenario with the - * thread collecting statistics it may make sense to specify a low limit during - * day time while allowing a higher load in the night time. Reducing the limit - * takes effect immediately by blocking incoming callers. If the limit is - * increased, waiting threads are not released immediately, but wake up when the - * timer runs out. Then, in the next period more processing steps can be - * performed without blocking. By setting the limit to 0 the semaphore can be - * switched off: in this mode the {@link #acquire()} method never blocks, but - * lets all callers pass directly. - *

- *

- * When the {@code TimedSemaphore} is no more needed its {@link #shutdown()} - * method should be called. This causes the periodic task that monitors the time - * interval to be canceled. If the {@code ScheduledExecutorService} has been - * created by the semaphore at construction time, it is also shut down. - * resources. After that {@link #acquire()} must not be called any more. - *

- * - * @since 3.0 - * @version $Id: TimedSemaphore.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class TimedSemaphore { - /** - * Constant for a value representing no limit. If the limit is set to a - * value less or equal this constant, the {@code TimedSemaphore} will be - * effectively switched off. - */ - public static final int NO_LIMIT = 0; - - /** Constant for the thread pool size for the executor. */ - private static final int THREAD_POOL_SIZE = 1; - - /** The executor service for managing the timer thread. */ - private final ScheduledExecutorService executorService; - - /** Stores the period for this timed semaphore. */ - private final long period; - - /** The time unit for the period. */ - private final TimeUnit unit; - - /** A flag whether the executor service was created by this object. */ - private final boolean ownExecutor; - - /** A future object representing the timer task. */ - private ScheduledFuture task; - - /** Stores the total number of invocations of the acquire() method. */ - private long totalAcquireCount; - - /** - * The counter for the periods. This counter is increased every time a - * period ends. - */ - private long periodCount; - - /** The limit. */ - private int limit; - - /** The current counter. */ - private int acquireCount; - - /** The number of invocations of acquire() in the last period. */ - private int lastCallsPerPeriod; - - /** A flag whether shutdown() was called. */ - private boolean shutdown; - - /** - * Creates a new instance of {@link TimedSemaphore} and initializes it with - * the given time period and the limit. - * - * @param timePeriod the time period - * @param timeUnit the unit for the period - * @param limit the limit for the semaphore - * @throws IllegalArgumentException if the period is less or equals 0 - */ - public TimedSemaphore(long timePeriod, TimeUnit timeUnit, int limit) { - this(null, timePeriod, timeUnit, limit); - } - - /** - * Creates a new instance of {@link TimedSemaphore} and initializes it with - * an executor service, the given time period, and the limit. The executor - * service will be used for creating a periodic task for monitoring the time - * period. It can be null, then a default service will be created. - * - * @param service the executor service - * @param timePeriod the time period - * @param timeUnit the unit for the period - * @param limit the limit for the semaphore - * @throws IllegalArgumentException if the period is less or equals 0 - */ - public TimedSemaphore(ScheduledExecutorService service, long timePeriod, - TimeUnit timeUnit, int limit) { - if (timePeriod <= 0) { - throw new IllegalArgumentException("Time period must be greater 0!"); - } - - period = timePeriod; - unit = timeUnit; - - if (service != null) { - executorService = service; - ownExecutor = false; - } else { - ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor( - THREAD_POOL_SIZE); - s.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - s.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - executorService = s; - ownExecutor = true; - } - - setLimit(limit); - } - - /** - * Returns the limit enforced by this semaphore. The limit determines how - * many invocations of {@link #acquire()} are allowed within the monitored - * period. - * - * @return the limit - */ - public final synchronized int getLimit() { - return limit; - } - - /** - * Sets the limit. This is the number of times the {@link #acquire()} method - * can be called within the time period specified. If this limit is reached, - * further invocations of {@link #acquire()} will block. Setting the limit - * to a value <= {@link #NO_LIMIT} will cause the limit to be disabled, - * i.e. an arbitrary number of{@link #acquire()} invocations is allowed in - * the time period. - * - * @param limit the limit - */ - public final synchronized void setLimit(int limit) { - this.limit = limit; - } - - /** - * Initializes a shutdown. After that the object cannot be used any more. - * This method can be invoked an arbitrary number of times. All invocations - * after the first one do not have any effect. - */ - public synchronized void shutdown() { - if (!shutdown) { - - if (ownExecutor) { - // if the executor was created by this instance, it has - // to be shutdown - getExecutorService().shutdownNow(); - } - if (task != null) { - task.cancel(false); - } - - shutdown = true; - } - } - - /** - * Tests whether the {@link #shutdown()} method has been called on this - * object. If this method returns true, this instance cannot be used - * any longer. - * - * @return a flag whether a shutdown has been performed - */ - public synchronized boolean isShutdown() { - return shutdown; - } - - /** - * Tries to acquire a permit from this semaphore. This method will block if - * the limit for the current period has already been reached. If - * {@link #shutdown()} has already been invoked, calling this method will - * cause an exception. The very first call of this method starts the timer - * task which monitors the time period set for this {@code TimedSemaphore}. - * From now on the semaphore is active. - * - * @throws InterruptedException if the thread gets interrupted - * @throws IllegalStateException if this semaphore is already shut down - */ - public synchronized void acquire() throws InterruptedException { - if (isShutdown()) { - throw new IllegalStateException("TimedSemaphore is shut down!"); - } - - if (task == null) { - task = startTimer(); - } - - boolean canPass = false; - do { - canPass = getLimit() <= NO_LIMIT || acquireCount < getLimit(); - if (!canPass) { - wait(); - } else { - acquireCount++; - } - } while (!canPass); - } - - /** - * Returns the number of (successful) acquire invocations during the last - * period. This is the number of times the {@link #acquire()} method was - * called without blocking. This can be useful for testing or debugging - * purposes or to determine a meaningful threshold value. If a limit is set, - * the value returned by this method won't be greater than this limit. - * - * @return the number of non-blocking invocations of the {@link #acquire()} - * method - */ - public synchronized int getLastAcquiresPerPeriod() { - return lastCallsPerPeriod; - } - - /** - * Returns the number of invocations of the {@link #acquire()} method for - * the current period. This may be useful for testing or debugging purposes. - * - * @return the current number of {@link #acquire()} invocations - */ - public synchronized int getAcquireCount() { - return acquireCount; - } - - /** - * Returns the number of calls to the {@link #acquire()} method that can - * still be performed in the current period without blocking. This method - * can give an indication whether it is safe to call the {@link #acquire()} - * method without risking to be suspended. However, there is no guarantee - * that a subsequent call to {@link #acquire()} actually is not-blocking - * because in the mean time other threads may have invoked the semaphore. - * - * @return the current number of available {@link #acquire()} calls in the - * current period - */ - public synchronized int getAvailablePermits() { - return getLimit() - getAcquireCount(); - } - - /** - * Returns the average number of successful (i.e. non-blocking) - * {@link #acquire()} invocations for the entire life-time of this {@code - * TimedSemaphore}. This method can be used for instance for statistical - * calculations. - * - * @return the average number of {@link #acquire()} invocations per time - * unit - */ - public synchronized double getAverageCallsPerPeriod() { - return periodCount == 0 ? 0 : (double) totalAcquireCount - / (double) periodCount; - } - - /** - * Returns the time period. This is the time monitored by this semaphore. - * Only a given number of invocations of the {@link #acquire()} method is - * possible in this period. - * - * @return the time period - */ - public long getPeriod() { - return period; - } - - /** - * Returns the time unit. This is the unit used by {@link #getPeriod()}. - * - * @return the time unit - */ - public TimeUnit getUnit() { - return unit; - } - - /** - * Returns the executor service used by this instance. - * - * @return the executor service - */ - protected ScheduledExecutorService getExecutorService() { - return executorService; - } - - /** - * Starts the timer. This method is called when {@link #acquire()} is called - * for the first time. It schedules a task to be executed at fixed rate to - * monitor the time period specified. - * - * @return a future object representing the task scheduled - */ - protected ScheduledFuture startTimer() { - return getExecutorService().scheduleAtFixedRate(new Runnable() { - public void run() { - endOfPeriod(); - } - }, getPeriod(), getPeriod(), getUnit()); - } - - /** - * The current time period is finished. This method is called by the timer - * used internally to monitor the time period. It resets the counter and - * releases the threads waiting for this barrier. - */ - synchronized void endOfPeriod() { - lastCallsPerPeriod = acquireCount; - totalAcquireCount += acquireCount; - periodCount++; - acquireCount = 0; - notifyAll(); - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/package.html b/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/package.html deleted file mode 100644 index 0ab61e0e..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/concurrent/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - -Provides support classes for multi-threaded programming. This package is -intended to be an extension to java.util.concurrent. -

These classes are thread-safe.

- - diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventListenerSupport.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventListenerSupport.java deleted file mode 100644 index 4ece87d6..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventListenerSupport.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package external.org.apache.commons.lang3.event; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.lang.reflect.Array; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import external.org.apache.commons.lang3.Validate; - -/** - * An EventListenerSupport object can be used to manage a list of event - * listeners of a particular type. The class provides - * {@link #addListener(Object)} and {@link #removeListener(Object)} methods - * for registering listeners, as well as a {@link #fire()} method for firing - * events to the listeners. - * - *

- * To use this class, suppose you want to support ActionEvents. You would do: - *

- * public class MyActionEventSource
- * {
- *   private EventListenerSupport actionListeners =
- *       EventListenerSupport.create(ActionListener.class);
- *
- *   public void someMethodThatFiresAction()
- *   {
- *     ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "somethingCool");
- *     actionListeners.fire().actionPerformed(e);
- *   }
- * }
- * 
- * - * Serializing an {@link EventListenerSupport} instance will result in any - * non-{@link Serializable} listeners being silently dropped. - * - * @param the type of event listener that is supported by this proxy. - * - * @since 3.0 - * @version $Id: EventListenerSupport.java 1082302 2011-03-16 21:08:27Z oheger $ - */ -public class EventListenerSupport implements Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 3593265990380473632L; - - /** - * The list used to hold the registered listeners. This list is - * intentionally a thread-safe copy-on-write-array so that traversals over - * the list of listeners will be atomic. - */ - private List listeners = new CopyOnWriteArrayList(); - - /** - * The proxy representing the collection of listeners. Calls to this proxy - * object will sent to all registered listeners. - */ - private transient L proxy; - - /** - * Empty typed array for #getListeners(). - */ - private transient L[] prototypeArray; - - /** - * Creates an EventListenerSupport object which supports the specified - * listener type. - * - * @param the type of the listener interface - * @param listenerInterface the type of listener interface that will receive - * events posted using this class. - * - * @return an EventListenerSupport object which supports the specified - * listener type. - * - * @throws NullPointerException if listenerInterface is - * null. - * @throws IllegalArgumentException if listenerInterface is - * not an interface. - */ - public static EventListenerSupport create(Class listenerInterface) { - return new EventListenerSupport(listenerInterface); - } - - /** - * Creates an EventListenerSupport object which supports the provided - * listener interface. - * - * @param listenerInterface the type of listener interface that will receive - * events posted using this class. - * - * @throws NullPointerException if listenerInterface is - * null. - * @throws IllegalArgumentException if listenerInterface is - * not an interface. - */ - public EventListenerSupport(Class listenerInterface) { - this(listenerInterface, Thread.currentThread().getContextClassLoader()); - } - - /** - * Creates an EventListenerSupport object which supports the provided - * listener interface using the specified class loader to create the JDK - * dynamic proxy. - * - * @param listenerInterface the listener interface. - * @param classLoader the class loader. - * - * @throws NullPointerException if listenerInterface or - * classLoader is null. - * @throws IllegalArgumentException if listenerInterface is - * not an interface. - */ - public EventListenerSupport(Class listenerInterface, ClassLoader classLoader) { - this(); - Validate.notNull(listenerInterface, "Listener interface cannot be null."); - Validate.notNull(classLoader, "ClassLoader cannot be null."); - Validate.isTrue(listenerInterface.isInterface(), "Class {0} is not an interface", - listenerInterface.getName()); - initializeTransientFields(listenerInterface, classLoader); - } - - /** - * Create a new EventListenerSupport instance. - * Serialization-friendly constructor. - */ - private EventListenerSupport() { - } - - /** - * Returns a proxy object which can be used to call listener methods on all - * of the registered event listeners. All calls made to this proxy will be - * forwarded to all registered listeners. - * - * @return a proxy object which can be used to call listener methods on all - * of the registered event listeners - */ - public L fire() { - return proxy; - } - -//********************************************************************************************************************** -// Other Methods -//********************************************************************************************************************** - - /** - * Registers an event listener. - * - * @param listener the event listener (may not be null). - * - * @throws NullPointerException if listener is - * null. - */ - public void addListener(L listener) { - Validate.notNull(listener, "Listener object cannot be null."); - listeners.add(listener); - } - - /** - * Returns the number of registered listeners. - * - * @return the number of registered listeners. - */ - int getListenerCount() { - return listeners.size(); - } - - /** - * Unregisters an event listener. - * - * @param listener the event listener (may not be null). - * - * @throws NullPointerException if listener is - * null. - */ - public void removeListener(L listener) { - Validate.notNull(listener, "Listener object cannot be null."); - listeners.remove(listener); - } - - /** - * Get an array containing the currently registered listeners. - * Modification to this array's elements will have no effect on the - * {@link EventListenerSupport} instance. - * @return L[] - */ - public L[] getListeners() { - return listeners.toArray(prototypeArray); - } - - /** - * Serialize. - * @param objectOutputStream the output stream - * @throws IOException if an IO error occurs - */ - private void writeObject(ObjectOutputStream objectOutputStream) throws IOException { - ArrayList serializableListeners = new ArrayList(); - - // don't just rely on instanceof Serializable: - ObjectOutputStream testObjectOutputStream = new ObjectOutputStream(new ByteArrayOutputStream()); - for (L listener : listeners) { - try { - testObjectOutputStream.writeObject(listener); - serializableListeners.add(listener); - } catch (IOException exception) { - //recreate test stream in case of indeterminate state - testObjectOutputStream = new ObjectOutputStream(new ByteArrayOutputStream()); - } - } - /* - * we can reconstitute everything we need from an array of our listeners, - * which has the additional advantage of typically requiring less storage than a list: - */ - objectOutputStream.writeObject(serializableListeners.toArray(prototypeArray)); - } - - /** - * Deserialize. - * @param objectInputStream the input stream - * @throws IOException if an IO error occurs - * @throws ClassNotFoundException if the class cannot be resolved - */ - private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException { - @SuppressWarnings("unchecked") - L[] listeners = (L[]) objectInputStream.readObject(); - - this.listeners = new CopyOnWriteArrayList(listeners); - - @SuppressWarnings("unchecked") - Class listenerInterface = (Class) listeners.getClass().getComponentType(); - - initializeTransientFields(listenerInterface, Thread.currentThread().getContextClassLoader()); - } - - /** - * Initialize transient fields. - * @param listenerInterface the class of the listener interface - * @param classLoader the class loader to be used - */ - private void initializeTransientFields(Class listenerInterface, ClassLoader classLoader) { - @SuppressWarnings("unchecked") - L[] array = (L[]) Array.newInstance(listenerInterface, 0); - this.prototypeArray = array; - createProxy(listenerInterface, classLoader); - } - - /** - * Create the proxy object. - * @param listenerInterface the class of the listener interface - * @param classLoader the class loader to be used - */ - private void createProxy(Class listenerInterface, ClassLoader classLoader) { - proxy = listenerInterface.cast(Proxy.newProxyInstance(classLoader, - new Class[] { listenerInterface }, createInvocationHandler())); - } - - /** - * Create the {@link InvocationHandler} responsible for broadcasting calls - * to the managed listeners. Subclasses can override to provide custom behavior. - * @return ProxyInvocationHandler - */ - protected InvocationHandler createInvocationHandler() { - return new ProxyInvocationHandler(); - } - - /** - * An invocation handler used to dispatch the event(s) to all the listeners. - */ - protected class ProxyInvocationHandler implements InvocationHandler { - /** Serialization version */ - private static final long serialVersionUID = 1L; - - /** - * Propagates the method call to all registered listeners in place of - * the proxy listener object. - * - * @param proxy the proxy object representing a listener on which the - * invocation was called. - * @param method the listener method that will be called on all of the - * listeners. - * @param args event arguments to propagate to the listeners. - * @return the result of the method call - * @throws Throwable if an error occurs - */ - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - for (L listener : listeners) { - method.invoke(listener, args); - } - return null; - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventUtils.java deleted file mode 100644 index 0cfcb8b4..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/event/EventUtils.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package external.org.apache.commons.lang3.event; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import external.org.apache.commons.lang3.reflect.MethodUtils; - -/** - * Provides some useful event-based utility methods. - * - * @since 3.0 - * @version $Id: EventUtils.java 1091072 2011-04-11 13:42:03Z mbenson $ - */ -public class EventUtils { - - /** - * Adds an event listener to the specified source. This looks for an "add" method corresponding to the event - * type (addActionListener, for example). - * @param eventSource the event source - * @param listenerType the event listener type - * @param listener the listener - * @param the event listener type - * - * @throws IllegalArgumentException if the object doesn't support the listener type - */ - public static void addEventListener(Object eventSource, Class listenerType, L listener) { - try { - MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException("Class " + eventSource.getClass().getName() - + " does not have a public add" + listenerType.getSimpleName() - + " method which takes a parameter of type " + listenerType.getName() + "."); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException("Class " + eventSource.getClass().getName() - + " does not have an accessible add" + listenerType.getSimpleName () - + " method which takes a parameter of type " + listenerType.getName() + "."); - } catch (InvocationTargetException e) { - throw new RuntimeException("Unable to add listener.", e.getCause()); - } - } - - /** - * Binds an event listener to a specific method on a specific object. - * - * @param the event listener type - * @param target the target object - * @param methodName the name of the method to be called - * @param eventSource the object which is generating events (JButton, JList, etc.) - * @param listenerType the listener interface (ActionListener.class, SelectionListener.class, etc.) - * @param eventTypes the event types (method names) from the listener interface (if none specified, all will be - * supported) - */ - public static void bindEventsToMethod(Object target, String methodName, Object eventSource, - Class listenerType, String... eventTypes) { - final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(), - new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes))); - addEventListener(eventSource, listenerType, listener); - } - - private static class EventBindingInvocationHandler implements InvocationHandler { - private final Object target; - private final String methodName; - private final Set eventTypes; - - /** - * Creates a new instance of {@code EventBindingInvocationHandler}. - * - * @param target the target object for method invocations - * @param methodName the name of the method to be invoked - * @param eventTypes the names of the supported event types - */ - EventBindingInvocationHandler(final Object target, final String methodName, String[] eventTypes) { - this.target = target; - this.methodName = methodName; - this.eventTypes = new HashSet(Arrays.asList(eventTypes)); - } - - /** - * Handles a method invocation on the proxy object. - * - * @param proxy the proxy instance - * @param method the method to be invoked - * @param parameters the parameters for the method invocation - * @return the result of the method call - * @throws Throwable if an error occurs - */ - public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable { - if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) { - if (hasMatchingParametersMethod(method)) { - return MethodUtils.invokeMethod(target, methodName, parameters); - } else { - return MethodUtils.invokeMethod(target, methodName); - } - } - return null; - } - - /** - * Checks whether a method for the passed in parameters can be found. - * - * @param method the listener method invoked - * @return a flag whether the parameters could be matched - */ - private boolean hasMatchingParametersMethod(final Method method) { - return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null; - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/event/package.html b/lib/apache-commons-lang/external/org/apache/commons/lang3/event/package.html deleted file mode 100644 index c5d95f67..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/event/package.html +++ /dev/null @@ -1,22 +0,0 @@ - - - -Provides some useful event-based utilities. -@since 3.0 - - diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedException.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedException.java deleted file mode 100644 index 477af842..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedException.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.exception; - -import java.util.List; -import java.util.Set; - -import external.org.apache.commons.lang3.tuple.Pair; - -/** - *

- * An exception that provides an easy and safe way to add contextual information. - *

- * An exception trace itself is often insufficient to provide rapid diagnosis of the issue. - * Frequently what is needed is a select few pieces of local contextual data. - * Providing this data is tricky however, due to concerns over formatting and nulls. - *

- * The contexted exception approach allows the exception to be created together with a - * list of context label-value pairs. This additional information is automatically included in - * the message and printed stack trace. - *

- * An unchecked version of this exception is provided by ContextedRuntimeException. - *

- *

- * To use this class write code as follows: - *

- *
- *   try {
- *     ...
- *   } catch (Exception e) {
- *     throw new ContextedException("Error posting account transaction", e)
- *          .addContextValue("Account Number", accountNumber)
- *          .addContextValue("Amount Posted", amountPosted)
- *          .addContextValue("Previous Balance", previousBalance)
- *   }
- * }
- * 
or improve diagnose data at a higher level: - *
- *   try {
- *     ...
- *   } catch (ContextedException e) {
- *     throw e.setContextValue("Transaction Id", transactionId);
- *   } catch (Exception e) {
- *     if (e instanceof ExceptionContext) {
- *       e.setContextValue("Transaction Id", transactionId);
- *     }
- *     throw e;
- *   }
- * }
- * 
- *

- * The output in a printStacktrace() (which often is written to a log) would look something like the following: - *

- * org.apache.commons.lang3.exception.ContextedException: java.lang.Exception: Error posting account transaction
- *  Exception Context:
- *  [1:Account Number=null]
- *  [2:Amount Posted=100.00]
- *  [3:Previous Balance=-2.17]
- *  [4:Transaction Id=94ef1d15-d443-46c4-822b-637f26244899]
- *
- *  ---------------------------------
- *  at org.apache.commons.lang3.exception.ContextedExceptionTest.testAddValue(ContextedExceptionTest.java:88)
- *  ..... (rest of trace)
- * 
- *

- * - * @see ContextedRuntimeException - * @since 3.0 - */ -public class ContextedException extends Exception implements ExceptionContext { - - /** The serialization version. */ - private static final long serialVersionUID = 20110706L; - /** The context where the data is stored. */ - private final ExceptionContext exceptionContext; - - /** - * Instantiates ContextedException without message or cause. - *

- * The context information is stored using a default implementation. - */ - public ContextedException() { - super(); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedException with message, but without cause. - *

- * The context information is stored using a default implementation. - * - * @param message the exception message, may be null - */ - public ContextedException(String message) { - super(message); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedException with cause, but without message. - *

- * The context information is stored using a default implementation. - * - * @param cause the underlying cause of the exception, may be null - */ - public ContextedException(Throwable cause) { - super(cause); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedException with cause and message. - *

- * The context information is stored using a default implementation. - * - * @param message the exception message, may be null - * @param cause the underlying cause of the exception, may be null - */ - public ContextedException(String message, Throwable cause) { - super(message, cause); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedException with cause, message, and ExceptionContext. - * - * @param message the exception message, may be null - * @param cause the underlying cause of the exception, may be null - * @param context the context used to store the additional information, null uses default implementation - */ - public ContextedException(String message, Throwable cause, ExceptionContext context) { - super(message, cause); - if (context == null) { - context = new DefaultExceptionContext(); - } - exceptionContext = context; - } - - //----------------------------------------------------------------------- - /** - * Adds information helpful to a developer in diagnosing and correcting the problem. - * For the information to be meaningful, the value passed should have a reasonable - * toString() implementation. - * Different values can be added with the same label multiple times. - *

- * Note: This exception is only serializable if the object added is serializable. - *

- * - * @param label a textual label associated with information, {@code null} not recommended - * @param value information needed to understand exception, may be {@code null} - * @return {@code this}, for method chaining, not {@code null} - */ - public ContextedException addContextValue(String label, Object value) { - exceptionContext.addContextValue(label, value); - return this; - } - - /** - * Sets information helpful to a developer in diagnosing and correcting the problem. - * For the information to be meaningful, the value passed should have a reasonable - * toString() implementation. - * Any existing values with the same labels are removed before the new one is added. - *

- * Note: This exception is only serializable if the object added as value is serializable. - *

- * - * @param label a textual label associated with information, {@code null} not recommended - * @param value information needed to understand exception, may be {@code null} - * @return {@code this}, for method chaining, not {@code null} - */ - public ContextedException setContextValue(String label, Object value) { - exceptionContext.setContextValue(label, value); - return this; - } - - /** - * {@inheritDoc} - */ - public List getContextValues(String label) { - return this.exceptionContext.getContextValues(label); - } - - /** - * {@inheritDoc} - */ - public Object getFirstContextValue(String label) { - return this.exceptionContext.getFirstContextValue(label); - } - - /** - * {@inheritDoc} - */ - public List> getContextEntries() { - return this.exceptionContext.getContextEntries(); - } - - /** - * {@inheritDoc} - */ - public Set getContextLabels() { - return exceptionContext.getContextLabels(); - } - - /** - * Provides the message explaining the exception, including the contextual data. - * - * @see java.lang.Throwable#getMessage() - * @return the message, never null - */ - @Override - public String getMessage(){ - return getFormattedExceptionMessage(super.getMessage()); - } - - /** - * Provides the message explaining the exception without the contextual data. - * - * @see java.lang.Throwable#getMessage() - * @return the message - * @since 3.0.1 - */ - public String getRawMessage() { - return super.getMessage(); - } - - /** - * {@inheritDoc} - */ - public String getFormattedExceptionMessage(String baseMessage) { - return exceptionContext.getFormattedExceptionMessage(baseMessage); - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedRuntimeException.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedRuntimeException.java deleted file mode 100644 index 07308ab9..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ContextedRuntimeException.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.exception; - -import java.util.List; -import java.util.Set; - -import external.org.apache.commons.lang3.tuple.Pair; - -/** - *

- * A runtime exception that provides an easy and safe way to add contextual information. - *

- * An exception trace itself is often insufficient to provide rapid diagnosis of the issue. - * Frequently what is needed is a select few pieces of local contextual data. - * Providing this data is tricky however, due to concerns over formatting and nulls. - *

- * The contexted exception approach allows the exception to be created together with a - * list of context label-value pairs. This additional information is automatically included in - * the message and printed stack trace. - *

- * A checked version of this exception is provided by ContextedException. - *

- *

- * To use this class write code as follows: - *

- *
- *   try {
- *     ...
- *   } catch (Exception e) {
- *     throw new ContextedRuntimeException("Error posting account transaction", e)
- *          .addContextValue("Account Number", accountNumber)
- *          .addContextValue("Amount Posted", amountPosted)
- *          .addContextValue("Previous Balance", previousBalance)
- *   }
- * }
- * 
or improve diagnose data at a higher level: - *
- *   try {
- *     ...
- *   } catch (ContextedRuntimeException e) {
- *     throw e.setContextValue("Transaction Id", transactionId);
- *   } catch (Exception e) {
- *     if (e instanceof ExceptionContext) {
- *       e.setContextValue("Transaction Id", transactionId);
- *     }
- *     throw e;
- *   }
- * }
- * 
- *

- * The output in a printStacktrace() (which often is written to a log) would look something like the following: - *

- * org.apache.commons.lang3.exception.ContextedRuntimeException: java.lang.Exception: Error posting account transaction
- *  Exception Context:
- *  [1:Account Number=null]
- *  [2:Amount Posted=100.00]
- *  [3:Previous Balance=-2.17]
- *  [4:Transaction Id=94ef1d15-d443-46c4-822b-637f26244899]
- *
- *  ---------------------------------
- *  at org.apache.commons.lang3.exception.ContextedRuntimeExceptionTest.testAddValue(ContextedExceptionTest.java:88)
- *  ..... (rest of trace)
- * 
- *

- * - * @see ContextedException - * @since 3.0 - */ -public class ContextedRuntimeException extends RuntimeException implements ExceptionContext { - - /** The serialization version. */ - private static final long serialVersionUID = 20110706L; - /** The context where the data is stored. */ - private final ExceptionContext exceptionContext; - - /** - * Instantiates ContextedRuntimeException without message or cause. - *

- * The context information is stored using a default implementation. - */ - public ContextedRuntimeException() { - super(); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedRuntimeException with message, but without cause. - *

- * The context information is stored using a default implementation. - * - * @param message the exception message, may be null - */ - public ContextedRuntimeException(String message) { - super(message); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedRuntimeException with cause, but without message. - *

- * The context information is stored using a default implementation. - * - * @param cause the underlying cause of the exception, may be null - */ - public ContextedRuntimeException(Throwable cause) { - super(cause); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedRuntimeException with cause and message. - *

- * The context information is stored using a default implementation. - * - * @param message the exception message, may be null - * @param cause the underlying cause of the exception, may be null - */ - public ContextedRuntimeException(String message, Throwable cause) { - super(message, cause); - exceptionContext = new DefaultExceptionContext(); - } - - /** - * Instantiates ContextedRuntimeException with cause, message, and ExceptionContext. - * - * @param message the exception message, may be null - * @param cause the underlying cause of the exception, may be null - * @param context the context used to store the additional information, null uses default implementation - */ - public ContextedRuntimeException(String message, Throwable cause, ExceptionContext context) { - super(message, cause); - if (context == null) { - context = new DefaultExceptionContext(); - } - exceptionContext = context; - } - - //----------------------------------------------------------------------- - /** - * Adds information helpful to a developer in diagnosing and correcting the problem. - * For the information to be meaningful, the value passed should have a reasonable - * toString() implementation. - * Different values can be added with the same label multiple times. - *

- * Note: This exception is only serializable if the object added is serializable. - *

- * - * @param label a textual label associated with information, {@code null} not recommended - * @param value information needed to understand exception, may be {@code null} - * @return {@code this}, for method chaining, not {@code null} - */ - public ContextedRuntimeException addContextValue(String label, Object value) { - exceptionContext.addContextValue(label, value); - return this; - } - - /** - * Sets information helpful to a developer in diagnosing and correcting the problem. - * For the information to be meaningful, the value passed should have a reasonable - * toString() implementation. - * Any existing values with the same labels are removed before the new one is added. - *

- * Note: This exception is only serializable if the object added as value is serializable. - *

- * - * @param label a textual label associated with information, {@code null} not recommended - * @param value information needed to understand exception, may be {@code null} - * @return {@code this}, for method chaining, not {@code null} - */ - public ContextedRuntimeException setContextValue(String label, Object value) { - exceptionContext.setContextValue(label, value); - return this; - } - - /** - * {@inheritDoc} - */ - public List getContextValues(String label) { - return this.exceptionContext.getContextValues(label); - } - - /** - * {@inheritDoc} - */ - public Object getFirstContextValue(String label) { - return this.exceptionContext.getFirstContextValue(label); - } - - /** - * {@inheritDoc} - */ - public List> getContextEntries() { - return this.exceptionContext.getContextEntries(); - } - - /** - * {@inheritDoc} - */ - public Set getContextLabels() { - return exceptionContext.getContextLabels(); - } - - /** - * Provides the message explaining the exception, including the contextual data. - * - * @see java.lang.Throwable#getMessage() - * @return the message, never null - */ - @Override - public String getMessage(){ - return getFormattedExceptionMessage(super.getMessage()); - } - - /** - * Provides the message explaining the exception without the contextual data. - * - * @see java.lang.Throwable#getMessage() - * @return the message - * @since 3.0.1 - */ - public String getRawMessage() { - return super.getMessage(); - } - - /** - * {@inheritDoc} - */ - public String getFormattedExceptionMessage(String baseMessage) { - return exceptionContext.getFormattedExceptionMessage(baseMessage); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/DefaultExceptionContext.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/DefaultExceptionContext.java deleted file mode 100644 index 70e83ee4..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/DefaultExceptionContext.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.exception; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - - -import external.org.apache.commons.lang3.StringUtils; -import external.org.apache.commons.lang3.tuple.ImmutablePair; -import external.org.apache.commons.lang3.tuple.Pair; - -/** - * Default implementation of the context storing the label-value pairs for contexted exceptions. - *

- * This implementation is serializable, however this is dependent on the values that - * are added also being serializable. - *

- * - * @see ContextedException - * @see ContextedRuntimeException - * @since 3.0 - */ -public class DefaultExceptionContext implements ExceptionContext, Serializable { - - /** The serialization version. */ - private static final long serialVersionUID = 20110706L; - - /** The list storing the label-data pairs. */ - private final List> contextValues = new ArrayList>(); - - /** - * {@inheritDoc} - */ - public DefaultExceptionContext addContextValue(String label, Object value) { - contextValues.add(new ImmutablePair(label, value)); - return this; - } - - /** - * {@inheritDoc} - */ - public DefaultExceptionContext setContextValue(String label, Object value) { - for (final Iterator> iter = contextValues.iterator(); iter.hasNext();) { - final Pair p = iter.next(); - if (StringUtils.equals(label, p.getKey())) { - iter.remove(); - } - } - addContextValue(label, value); - return this; - } - - /** - * {@inheritDoc} - */ - public List getContextValues(String label) { - final List values = new ArrayList(); - for (final Pair pair : contextValues) { - if (StringUtils.equals(label, pair.getKey())) { - values.add(pair.getValue()); - } - } - return values; - } - - /** - * {@inheritDoc} - */ - public Object getFirstContextValue(String label) { - for (final Pair pair : contextValues) { - if (StringUtils.equals(label, pair.getKey())) { - return pair.getValue(); - } - } - return null; - } - - /** - * {@inheritDoc} - */ - public Set getContextLabels() { - final Set labels = new HashSet(); - for (final Pair pair : contextValues) { - labels.add(pair.getKey()); - } - return labels; - } - - /** - * {@inheritDoc} - */ - public List> getContextEntries() { - return contextValues; - } - - /** - * Builds the message containing the contextual information. - * - * @param baseMessage the base exception message without context information appended - * @return the exception message with context information appended, never null - */ - public String getFormattedExceptionMessage(String baseMessage){ - StringBuilder buffer = new StringBuilder(256); - if (baseMessage != null) { - buffer.append(baseMessage); - } - - if (contextValues.size() > 0) { - if (buffer.length() > 0) { - buffer.append('\n'); - } - buffer.append("Exception Context:\n"); - - int i = 0; - for (final Pair pair : contextValues) { - buffer.append("\t["); - buffer.append(++i); - buffer.append(':'); - buffer.append(pair.getKey()); - buffer.append("="); - final Object value = pair.getValue(); - if (value == null) { - buffer.append("null"); - } else { - String valueStr; - try { - valueStr = value.toString(); - } catch (Exception e) { - valueStr = "Exception thrown on toString(): " + ExceptionUtils.getStackTrace(e); - } - buffer.append(valueStr); - } - buffer.append("]\n"); - } - buffer.append("---------------------------------"); - } - return buffer.toString(); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionContext.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionContext.java deleted file mode 100644 index 8a27640b..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionContext.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.exception; - -import java.util.List; -import java.util.Set; - -import external.org.apache.commons.lang3.tuple.Pair; - -/** - * Allows the storage and retrieval of contextual information based on label-value - * pairs for exceptions. - *

- * Implementations are expected to manage the pairs in a list-style collection - * that keeps the pairs in the sequence of their addition. - *

- * - * @see ContextedException - * @see ContextedRuntimeException - * @since 3.0 - */ -public interface ExceptionContext { - - /** - * Adds a contextual label-value pair into this context. - *

- * The pair will be added to the context, independently of an already - * existing pair with the same label. - *

- * - * @param label the label of the item to add, {@code null} not recommended - * @param value the value of item to add, may be {@code null} - * @return {@code this}, for method chaining, not {@code null} - */ - public ExceptionContext addContextValue(String label, Object value); - - /** - * Sets a contextual label-value pair into this context. - *

- * The pair will be added normally, but any existing label-value pair with - * the same label is removed from the context. - *

- * - * @param label the label of the item to add, {@code null} not recommended - * @param value the value of item to add, may be {@code null} - * @return {@code this}, for method chaining, not {@code null} - */ - public ExceptionContext setContextValue(String label, Object value); - - /** - * Retrieves all the contextual data values associated with the label. - * - * @param label the label to get the contextual values for, may be {@code null} - * @return the contextual values associated with the label, never {@code null} - */ - public List getContextValues(String label); - - /** - * Retrieves the first available contextual data value associated with the label. - * - * @param label the label to get the contextual value for, may be {@code null} - * @return the first contextual value associated with the label, may be {@code null} - */ - public Object getFirstContextValue(String label); - - /** - * Retrieves the full set of labels defined in the contextual data. - * - * @return the set of labels, not {@code null} - */ - public Set getContextLabels(); - - /** - * Retrieves the full list of label-value pairs defined in the contextual data. - * - * @return the list of pairs, not {@code null} - */ - public List> getContextEntries(); - - /** - * Gets the contextualized error message based on a base message. - * This will add the context label-value pairs to the message. - * - * @param baseMessage the base exception message without context information appended - * @return the exception message with context information appended, not {@code null} - */ - public String getFormattedExceptionMessage(String baseMessage); - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionUtils.java deleted file mode 100644 index dc4dd012..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/exception/ExceptionUtils.java +++ /dev/null @@ -1,697 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.exception; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import external.org.apache.commons.lang3.ArrayUtils; -import external.org.apache.commons.lang3.ClassUtils; -import external.org.apache.commons.lang3.StringUtils; -import external.org.apache.commons.lang3.SystemUtils; - -/** - *

Provides utilities for manipulating and examining - * Throwable objects.

- * - * @since 1.0 - * @version $Id: ExceptionUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class ExceptionUtils { - - /** - *

Used when printing stack frames to denote the start of a - * wrapped exception.

- * - *

Package private for accessibility by test suite.

- */ - static final String WRAPPED_MARKER = " [wrapped] "; - - /** - *

The names of methods commonly used to access a wrapped exception.

- */ - // TODO: Remove in Lang 4.0 - private static final String[] CAUSE_METHOD_NAMES = { - "getCause", - "getNextException", - "getTargetException", - "getException", - "getSourceException", - "getRootCause", - "getCausedByException", - "getNested", - "getLinkedException", - "getNestedException", - "getLinkedCause", - "getThrowable", - }; - - /** - *

- * Public constructor allows an instance of ExceptionUtils to be created, although that is not - * normally necessary. - *

- */ - public ExceptionUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - *

Returns the default names used when searching for the cause of an exception.

- * - *

This may be modified and used in the overloaded getCause(Throwable, String[]) method.

- * - * @return cloned array of the default method names - * @since 3.0 - * @deprecated This feature will be removed in Lang 4.0 - */ - @Deprecated - public static String[] getDefaultCauseMethodNames() { - return ArrayUtils.clone(CAUSE_METHOD_NAMES); - } - - //----------------------------------------------------------------------- - /** - *

Introspects the Throwable to obtain the cause.

- * - *

The method searches for methods with specific names that return a - * Throwable object. This will pick up most wrapping exceptions, - * including those from JDK 1.4. - * - *

The default list searched for are:

- *
    - *
  • getCause()
  • - *
  • getNextException()
  • - *
  • getTargetException()
  • - *
  • getException()
  • - *
  • getSourceException()
  • - *
  • getRootCause()
  • - *
  • getCausedByException()
  • - *
  • getNested()
  • - *
- * - *

If none of the above is found, returns null.

- * - * @param throwable the throwable to introspect for a cause, may be null - * @return the cause of the Throwable, - * null if none found or null throwable input - * @since 1.0 - * @deprecated This feature will be removed in Lang 4.0 - */ - @Deprecated - public static Throwable getCause(Throwable throwable) { - return getCause(throwable, CAUSE_METHOD_NAMES); - } - - /** - *

Introspects the Throwable to obtain the cause.

- * - *

A null set of method names means use the default set. - * A null in the set of method names will be ignored.

- * - * @param throwable the throwable to introspect for a cause, may be null - * @param methodNames the method names, null treated as default set - * @return the cause of the Throwable, - * null if none found or null throwable input - * @since 1.0 - * @deprecated This feature will be removed in Lang 4.0 - */ - @Deprecated - public static Throwable getCause(Throwable throwable, String[] methodNames) { - if (throwable == null) { - return null; - } - - if (methodNames == null) { - methodNames = CAUSE_METHOD_NAMES; - } - - for (String methodName : methodNames) { - if (methodName != null) { - Throwable cause = getCauseUsingMethodName(throwable, methodName); - if (cause != null) { - return cause; - } - } - } - - return null; - } - - /** - *

Introspects the Throwable to obtain the root cause.

- * - *

This method walks through the exception chain to the last element, - * "root" of the tree, using {@link #getCause(Throwable)}, and - * returns that exception.

- * - *

From version 2.2, this method handles recursive cause structures - * that might otherwise cause infinite loops. If the throwable parameter - * has a cause of itself, then null will be returned. If the throwable - * parameter cause chain loops, the last element in the chain before the - * loop is returned.

- * - * @param throwable the throwable to get the root cause for, may be null - * @return the root cause of the Throwable, - * null if none found or null throwable input - */ - public static Throwable getRootCause(Throwable throwable) { - List list = getThrowableList(throwable); - return list.size() < 2 ? null : (Throwable)list.get(list.size() - 1); - } - - /** - *

Finds a Throwable by method name.

- * - * @param throwable the exception to examine - * @param methodName the name of the method to find and invoke - * @return the wrapped exception, or null if not found - */ - // TODO: Remove in Lang 4.0 - private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) { - Method method = null; - try { - method = throwable.getClass().getMethod(methodName); - } catch (NoSuchMethodException ignored) { // NOPMD - // exception ignored - } catch (SecurityException ignored) { // NOPMD - // exception ignored - } - - if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { - try { - return (Throwable) method.invoke(throwable); - } catch (IllegalAccessException ignored) { // NOPMD - // exception ignored - } catch (IllegalArgumentException ignored) { // NOPMD - // exception ignored - } catch (InvocationTargetException ignored) { // NOPMD - // exception ignored - } - } - return null; - } - - //----------------------------------------------------------------------- - /** - *

Counts the number of Throwable objects in the - * exception chain.

- * - *

A throwable without cause will return 1. - * A throwable with one cause will return 2 and so on. - * A null throwable will return 0.

- * - *

From version 2.2, this method handles recursive cause structures - * that might otherwise cause infinite loops. The cause chain is - * processed until the end is reached, or until the next item in the - * chain is already in the result set.

- * - * @param throwable the throwable to inspect, may be null - * @return the count of throwables, zero if null input - */ - public static int getThrowableCount(Throwable throwable) { - return getThrowableList(throwable).size(); - } - - /** - *

Returns the list of Throwable objects in the - * exception chain.

- * - *

A throwable without cause will return an array containing - * one element - the input throwable. - * A throwable with one cause will return an array containing - * two elements. - the input throwable and the cause throwable. - * A null throwable will return an array of size zero.

- * - *

From version 2.2, this method handles recursive cause structures - * that might otherwise cause infinite loops. The cause chain is - * processed until the end is reached, or until the next item in the - * chain is already in the result set.

- * - * @see #getThrowableList(Throwable) - * @param throwable the throwable to inspect, may be null - * @return the array of throwables, never null - */ - public static Throwable[] getThrowables(Throwable throwable) { - List list = getThrowableList(throwable); - return list.toArray(new Throwable[list.size()]); - } - - /** - *

Returns the list of Throwable objects in the - * exception chain.

- * - *

A throwable without cause will return a list containing - * one element - the input throwable. - * A throwable with one cause will return a list containing - * two elements. - the input throwable and the cause throwable. - * A null throwable will return a list of size zero.

- * - *

This method handles recursive cause structures that might - * otherwise cause infinite loops. The cause chain is processed until - * the end is reached, or until the next item in the chain is already - * in the result set.

- * - * @param throwable the throwable to inspect, may be null - * @return the list of throwables, never null - * @since Commons Lang 2.2 - */ - public static List getThrowableList(Throwable throwable) { - List list = new ArrayList(); - while (throwable != null && list.contains(throwable) == false) { - list.add(throwable); - throwable = ExceptionUtils.getCause(throwable); - } - return list; - } - - //----------------------------------------------------------------------- - /** - *

Returns the (zero based) index of the first Throwable - * that matches the specified class (exactly) in the exception chain. - * Subclasses of the specified class do not match - see - * {@link #indexOfType(Throwable, Class)} for the opposite.

- * - *

A null throwable returns -1. - * A null type returns -1. - * No match in the chain returns -1.

- * - * @param throwable the throwable to inspect, may be null - * @param clazz the class to search for, subclasses do not match, null returns -1 - * @return the index into the throwable chain, -1 if no match or null input - */ - public static int indexOfThrowable(Throwable throwable, Class clazz) { - return indexOf(throwable, clazz, 0, false); - } - - /** - *

Returns the (zero based) index of the first Throwable - * that matches the specified type in the exception chain from - * a specified index. - * Subclasses of the specified class do not match - see - * {@link #indexOfType(Throwable, Class, int)} for the opposite.

- * - *

A null throwable returns -1. - * A null type returns -1. - * No match in the chain returns -1. - * A negative start index is treated as zero. - * A start index greater than the number of throwables returns -1.

- * - * @param throwable the throwable to inspect, may be null - * @param clazz the class to search for, subclasses do not match, null returns -1 - * @param fromIndex the (zero based) index of the starting position, - * negative treated as zero, larger than chain size returns -1 - * @return the index into the throwable chain, -1 if no match or null input - */ - public static int indexOfThrowable(Throwable throwable, Class clazz, int fromIndex) { - return indexOf(throwable, clazz, fromIndex, false); - } - - //----------------------------------------------------------------------- - /** - *

Returns the (zero based) index of the first Throwable - * that matches the specified class or subclass in the exception chain. - * Subclasses of the specified class do match - see - * {@link #indexOfThrowable(Throwable, Class)} for the opposite.

- * - *

A null throwable returns -1. - * A null type returns -1. - * No match in the chain returns -1.

- * - * @param throwable the throwable to inspect, may be null - * @param type the type to search for, subclasses match, null returns -1 - * @return the index into the throwable chain, -1 if no match or null input - * @since 2.1 - */ - public static int indexOfType(Throwable throwable, Class type) { - return indexOf(throwable, type, 0, true); - } - - /** - *

Returns the (zero based) index of the first Throwable - * that matches the specified type in the exception chain from - * a specified index. - * Subclasses of the specified class do match - see - * {@link #indexOfThrowable(Throwable, Class)} for the opposite.

- * - *

A null throwable returns -1. - * A null type returns -1. - * No match in the chain returns -1. - * A negative start index is treated as zero. - * A start index greater than the number of throwables returns -1.

- * - * @param throwable the throwable to inspect, may be null - * @param type the type to search for, subclasses match, null returns -1 - * @param fromIndex the (zero based) index of the starting position, - * negative treated as zero, larger than chain size returns -1 - * @return the index into the throwable chain, -1 if no match or null input - * @since 2.1 - */ - public static int indexOfType(Throwable throwable, Class type, int fromIndex) { - return indexOf(throwable, type, fromIndex, true); - } - - /** - *

Worker method for the indexOfType methods.

- * - * @param throwable the throwable to inspect, may be null - * @param type the type to search for, subclasses match, null returns -1 - * @param fromIndex the (zero based) index of the starting position, - * negative treated as zero, larger than chain size returns -1 - * @param subclass if true, compares with {@link Class#isAssignableFrom(Class)}, otherwise compares - * using references - * @return index of the type within throwables nested withing the specified throwable - */ - private static int indexOf(Throwable throwable, Class type, int fromIndex, boolean subclass) { - if (throwable == null || type == null) { - return -1; - } - if (fromIndex < 0) { - fromIndex = 0; - } - Throwable[] throwables = ExceptionUtils.getThrowables(throwable); - if (fromIndex >= throwables.length) { - return -1; - } - if (subclass) { - for (int i = fromIndex; i < throwables.length; i++) { - if (type.isAssignableFrom(throwables[i].getClass())) { - return i; - } - } - } else { - for (int i = fromIndex; i < throwables.length; i++) { - if (type.equals(throwables[i].getClass())) { - return i; - } - } - } - return -1; - } - - //----------------------------------------------------------------------- - /** - *

Prints a compact stack trace for the root cause of a throwable - * to System.err.

- * - *

The compact stack trace starts with the root cause and prints - * stack frames up to the place where it was caught and wrapped. - * Then it prints the wrapped exception and continues with stack frames - * until the wrapper exception is caught and wrapped again, etc.

- * - *

The output of this method is consistent across JDK versions. - * Note that this is the opposite order to the JDK1.4 display.

- * - *

The method is equivalent to printStackTrace for throwables - * that don't have nested causes.

- * - * @param throwable the throwable to output - * @since 2.0 - */ - public static void printRootCauseStackTrace(Throwable throwable) { - printRootCauseStackTrace(throwable, System.err); - } - - /** - *

Prints a compact stack trace for the root cause of a throwable.

- * - *

The compact stack trace starts with the root cause and prints - * stack frames up to the place where it was caught and wrapped. - * Then it prints the wrapped exception and continues with stack frames - * until the wrapper exception is caught and wrapped again, etc.

- * - *

The output of this method is consistent across JDK versions. - * Note that this is the opposite order to the JDK1.4 display.

- * - *

The method is equivalent to printStackTrace for throwables - * that don't have nested causes.

- * - * @param throwable the throwable to output, may be null - * @param stream the stream to output to, may not be null - * @throws IllegalArgumentException if the stream is null - * @since 2.0 - */ - public static void printRootCauseStackTrace(Throwable throwable, PrintStream stream) { - if (throwable == null) { - return; - } - if (stream == null) { - throw new IllegalArgumentException("The PrintStream must not be null"); - } - String trace[] = getRootCauseStackTrace(throwable); - for (String element : trace) { - stream.println(element); - } - stream.flush(); - } - - /** - *

Prints a compact stack trace for the root cause of a throwable.

- * - *

The compact stack trace starts with the root cause and prints - * stack frames up to the place where it was caught and wrapped. - * Then it prints the wrapped exception and continues with stack frames - * until the wrapper exception is caught and wrapped again, etc.

- * - *

The output of this method is consistent across JDK versions. - * Note that this is the opposite order to the JDK1.4 display.

- * - *

The method is equivalent to printStackTrace for throwables - * that don't have nested causes.

- * - * @param throwable the throwable to output, may be null - * @param writer the writer to output to, may not be null - * @throws IllegalArgumentException if the writer is null - * @since 2.0 - */ - public static void printRootCauseStackTrace(Throwable throwable, PrintWriter writer) { - if (throwable == null) { - return; - } - if (writer == null) { - throw new IllegalArgumentException("The PrintWriter must not be null"); - } - String trace[] = getRootCauseStackTrace(throwable); - for (String element : trace) { - writer.println(element); - } - writer.flush(); - } - - //----------------------------------------------------------------------- - /** - *

Creates a compact stack trace for the root cause of the supplied - * Throwable.

- * - *

The output of this method is consistent across JDK versions. - * It consists of the root exception followed by each of its wrapping - * exceptions separated by '[wrapped]'. Note that this is the opposite - * order to the JDK1.4 display.

- * - * @param throwable the throwable to examine, may be null - * @return an array of stack trace frames, never null - * @since 2.0 - */ - public static String[] getRootCauseStackTrace(Throwable throwable) { - if (throwable == null) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - Throwable throwables[] = getThrowables(throwable); - int count = throwables.length; - List frames = new ArrayList(); - List nextTrace = getStackFrameList(throwables[count - 1]); - for (int i = count; --i >= 0;) { - List trace = nextTrace; - if (i != 0) { - nextTrace = getStackFrameList(throwables[i - 1]); - removeCommonFrames(trace, nextTrace); - } - if (i == count - 1) { - frames.add(throwables[i].toString()); - } else { - frames.add(WRAPPED_MARKER + throwables[i].toString()); - } - for (int j = 0; j < trace.size(); j++) { - frames.add(trace.get(j)); - } - } - return frames.toArray(new String[frames.size()]); - } - - /** - *

Removes common frames from the cause trace given the two stack traces.

- * - * @param causeFrames stack trace of a cause throwable - * @param wrapperFrames stack trace of a wrapper throwable - * @throws IllegalArgumentException if either argument is null - * @since 2.0 - */ - public static void removeCommonFrames(List causeFrames, List wrapperFrames) { - if (causeFrames == null || wrapperFrames == null) { - throw new IllegalArgumentException("The List must not be null"); - } - int causeFrameIndex = causeFrames.size() - 1; - int wrapperFrameIndex = wrapperFrames.size() - 1; - while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) { - // Remove the frame from the cause trace if it is the same - // as in the wrapper trace - String causeFrame = causeFrames.get(causeFrameIndex); - String wrapperFrame = wrapperFrames.get(wrapperFrameIndex); - if (causeFrame.equals(wrapperFrame)) { - causeFrames.remove(causeFrameIndex); - } - causeFrameIndex--; - wrapperFrameIndex--; - } - } - - //----------------------------------------------------------------------- - /** - *

Gets the stack trace from a Throwable as a String.

- * - *

The result of this method vary by JDK version as this method - * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}. - * On JDK1.3 and earlier, the cause exception will not be shown - * unless the specified throwable alters printStackTrace.

- * - * @param throwable the Throwable to be examined - * @return the stack trace as generated by the exception's - * printStackTrace(PrintWriter) method - */ - public static String getStackTrace(Throwable throwable) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw, true); - throwable.printStackTrace(pw); - return sw.getBuffer().toString(); - } - - /** - *

Captures the stack trace associated with the specified - * Throwable object, decomposing it into a list of - * stack frames.

- * - *

The result of this method vary by JDK version as this method - * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}. - * On JDK1.3 and earlier, the cause exception will not be shown - * unless the specified throwable alters printStackTrace.

- * - * @param throwable the Throwable to examine, may be null - * @return an array of strings describing each stack frame, never null - */ - public static String[] getStackFrames(Throwable throwable) { - if (throwable == null) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - return getStackFrames(getStackTrace(throwable)); - } - - //----------------------------------------------------------------------- - /** - *

Returns an array where each element is a line from the argument.

- * - *

The end of line is determined by the value of {@link SystemUtils#LINE_SEPARATOR}.

- * - * @param stackTrace a stack trace String - * @return an array where each element is a line from the argument - */ - static String[] getStackFrames(String stackTrace) { - String linebreak = SystemUtils.LINE_SEPARATOR; - StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); - List list = new ArrayList(); - while (frames.hasMoreTokens()) { - list.add(frames.nextToken()); - } - return list.toArray(new String[list.size()]); - } - - /** - *

Produces a List of stack frames - the message - * is not included. Only the trace of the specified exception is - * returned, any caused by trace is stripped.

- * - *

This works in most cases - it will only fail if the exception - * message contains a line that starts with: - * "   at".

- * - * @param t is any throwable - * @return List of stack frames - */ - static List getStackFrameList(Throwable t) { - String stackTrace = getStackTrace(t); - String linebreak = SystemUtils.LINE_SEPARATOR; - StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); - List list = new ArrayList(); - boolean traceStarted = false; - while (frames.hasMoreTokens()) { - String token = frames.nextToken(); - // Determine if the line starts with at - int at = token.indexOf("at"); - if (at != -1 && token.substring(0, at).trim().length() == 0) { - traceStarted = true; - list.add(token); - } else if (traceStarted) { - break; - } - } - return list; - } - - //----------------------------------------------------------------------- - /** - * Gets a short message summarising the exception. - *

- * The message returned is of the form - * {ClassNameWithoutPackage}: {ThrowableMessage} - * - * @param th the throwable to get a message for, null returns empty string - * @return the message, non-null - * @since Commons Lang 2.2 - */ - public static String getMessage(Throwable th) { - if (th == null) { - return ""; - } - String clsName = ClassUtils.getShortClassName(th, null); - String msg = th.getMessage(); - return clsName + ": " + StringUtils.defaultString(msg); - } - - //----------------------------------------------------------------------- - /** - * Gets a short message summarising the root cause exception. - *

- * The message returned is of the form - * {ClassNameWithoutPackage}: {ThrowableMessage} - * - * @param th the throwable to get a message for, null returns empty string - * @return the message, non-null - * @since Commons Lang 2.2 - */ - public static String getRootCauseMessage(Throwable th) { - Throwable root = ExceptionUtils.getRootCause(th); - root = root == null ? th : root; - return getMessage(root); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/Fraction.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/math/Fraction.java deleted file mode 100644 index ddb81965..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/Fraction.java +++ /dev/null @@ -1,959 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.math; - -import java.math.BigInteger; - -/** - *

Fraction is a Number implementation that - * stores fractions accurately.

- * - *

This class is immutable, and interoperable with most methods that accept - * a Number.

- * - *

Note that this class is intended for common use cases, it is int - * based and thus suffers from various overflow issues. For a BigInteger based - * equivalent, please see the Commons Math BigFraction class.

- * - * @since 2.0 - * @version $Id: Fraction.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public final class Fraction extends Number implements Comparable { - - /** - * Required for serialization support. Lang version 2.0. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 65382027393090L; - - /** - * Fraction representation of 0. - */ - public static final Fraction ZERO = new Fraction(0, 1); - /** - * Fraction representation of 1. - */ - public static final Fraction ONE = new Fraction(1, 1); - /** - * Fraction representation of 1/2. - */ - public static final Fraction ONE_HALF = new Fraction(1, 2); - /** - * Fraction representation of 1/3. - */ - public static final Fraction ONE_THIRD = new Fraction(1, 3); - /** - * Fraction representation of 2/3. - */ - public static final Fraction TWO_THIRDS = new Fraction(2, 3); - /** - * Fraction representation of 1/4. - */ - public static final Fraction ONE_QUARTER = new Fraction(1, 4); - /** - * Fraction representation of 2/4. - */ - public static final Fraction TWO_QUARTERS = new Fraction(2, 4); - /** - * Fraction representation of 3/4. - */ - public static final Fraction THREE_QUARTERS = new Fraction(3, 4); - /** - * Fraction representation of 1/5. - */ - public static final Fraction ONE_FIFTH = new Fraction(1, 5); - /** - * Fraction representation of 2/5. - */ - public static final Fraction TWO_FIFTHS = new Fraction(2, 5); - /** - * Fraction representation of 3/5. - */ - public static final Fraction THREE_FIFTHS = new Fraction(3, 5); - /** - * Fraction representation of 4/5. - */ - public static final Fraction FOUR_FIFTHS = new Fraction(4, 5); - - - /** - * The numerator number part of the fraction (the three in three sevenths). - */ - private final int numerator; - /** - * The denominator number part of the fraction (the seven in three sevenths). - */ - private final int denominator; - - /** - * Cached output hashCode (class is immutable). - */ - private transient int hashCode = 0; - /** - * Cached output toString (class is immutable). - */ - private transient String toString = null; - /** - * Cached output toProperString (class is immutable). - */ - private transient String toProperString = null; - - /** - *

Constructs a Fraction instance with the 2 parts - * of a fraction Y/Z.

- * - * @param numerator the numerator, for example the three in 'three sevenths' - * @param denominator the denominator, for example the seven in 'three sevenths' - */ - private Fraction(int numerator, int denominator) { - super(); - this.numerator = numerator; - this.denominator = denominator; - } - - /** - *

Creates a Fraction instance with the 2 parts - * of a fraction Y/Z.

- * - *

Any negative signs are resolved to be on the numerator.

- * - * @param numerator the numerator, for example the three in 'three sevenths' - * @param denominator the denominator, for example the seven in 'three sevenths' - * @return a new fraction instance - * @throws ArithmeticException if the denominator is zero - * or the denominator is {@code negative} and the numerator is {@code Integer#MIN_VALUE} - */ - public static Fraction getFraction(int numerator, int denominator) { - if (denominator == 0) { - throw new ArithmeticException("The denominator must not be zero"); - } - if (denominator < 0) { - if (numerator==Integer.MIN_VALUE || - denominator==Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: can't negate"); - } - numerator = -numerator; - denominator = -denominator; - } - return new Fraction(numerator, denominator); - } - - /** - *

Creates a Fraction instance with the 3 parts - * of a fraction X Y/Z.

- * - *

The negative sign must be passed in on the whole number part.

- * - * @param whole the whole number, for example the one in 'one and three sevenths' - * @param numerator the numerator, for example the three in 'one and three sevenths' - * @param denominator the denominator, for example the seven in 'one and three sevenths' - * @return a new fraction instance - * @throws ArithmeticException if the denominator is zero - * @throws ArithmeticException if the denominator is negative - * @throws ArithmeticException if the numerator is negative - * @throws ArithmeticException if the resulting numerator exceeds - * Integer.MAX_VALUE - */ - public static Fraction getFraction(int whole, int numerator, int denominator) { - if (denominator == 0) { - throw new ArithmeticException("The denominator must not be zero"); - } - if (denominator < 0) { - throw new ArithmeticException("The denominator must not be negative"); - } - if (numerator < 0) { - throw new ArithmeticException("The numerator must not be negative"); - } - long numeratorValue; - if (whole < 0) { - numeratorValue = whole * (long)denominator - numerator; - } else { - numeratorValue = whole * (long)denominator + numerator; - } - if (numeratorValue < Integer.MIN_VALUE || - numeratorValue > Integer.MAX_VALUE) { - throw new ArithmeticException("Numerator too large to represent as an Integer."); - } - return new Fraction((int) numeratorValue, denominator); - } - - /** - *

Creates a reduced Fraction instance with the 2 parts - * of a fraction Y/Z.

- * - *

For example, if the input parameters represent 2/4, then the created - * fraction will be 1/2.

- * - *

Any negative signs are resolved to be on the numerator.

- * - * @param numerator the numerator, for example the three in 'three sevenths' - * @param denominator the denominator, for example the seven in 'three sevenths' - * @return a new fraction instance, with the numerator and denominator reduced - * @throws ArithmeticException if the denominator is zero - */ - public static Fraction getReducedFraction(int numerator, int denominator) { - if (denominator == 0) { - throw new ArithmeticException("The denominator must not be zero"); - } - if (numerator==0) { - return ZERO; // normalize zero. - } - // allow 2^k/-2^31 as a valid fraction (where k>0) - if (denominator==Integer.MIN_VALUE && (numerator&1)==0) { - numerator/=2; denominator/=2; - } - if (denominator < 0) { - if (numerator==Integer.MIN_VALUE || - denominator==Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: can't negate"); - } - numerator = -numerator; - denominator = -denominator; - } - // simplify fraction. - int gcd = greatestCommonDivisor(numerator, denominator); - numerator /= gcd; - denominator /= gcd; - return new Fraction(numerator, denominator); - } - - /** - *

Creates a Fraction instance from a double value.

- * - *

This method uses the - * continued fraction algorithm, computing a maximum of - * 25 convergents and bounding the denominator by 10,000.

- * - * @param value the double value to convert - * @return a new fraction instance that is close to the value - * @throws ArithmeticException if |value| > Integer.MAX_VALUE - * or value = NaN - * @throws ArithmeticException if the calculated denominator is zero - * @throws ArithmeticException if the the algorithm does not converge - */ - public static Fraction getFraction(double value) { - int sign = value < 0 ? -1 : 1; - value = Math.abs(value); - if (value > Integer.MAX_VALUE || Double.isNaN(value)) { - throw new ArithmeticException - ("The value must not be greater than Integer.MAX_VALUE or NaN"); - } - int wholeNumber = (int) value; - value -= wholeNumber; - - int numer0 = 0; // the pre-previous - int denom0 = 1; // the pre-previous - int numer1 = 1; // the previous - int denom1 = 0; // the previous - int numer2 = 0; // the current, setup in calculation - int denom2 = 0; // the current, setup in calculation - int a1 = (int) value; - int a2 = 0; - double x1 = 1; - double x2 = 0; - double y1 = value - a1; - double y2 = 0; - double delta1, delta2 = Double.MAX_VALUE; - double fraction; - int i = 1; -// System.out.println("---"); - do { - delta1 = delta2; - a2 = (int) (x1 / y1); - x2 = y1; - y2 = x1 - a2 * y1; - numer2 = a1 * numer1 + numer0; - denom2 = a1 * denom1 + denom0; - fraction = (double) numer2 / (double) denom2; - delta2 = Math.abs(value - fraction); -// System.out.println(numer2 + " " + denom2 + " " + fraction + " " + delta2 + " " + y1); - a1 = a2; - x1 = x2; - y1 = y2; - numer0 = numer1; - denom0 = denom1; - numer1 = numer2; - denom1 = denom2; - i++; -// System.out.println(">>" + delta1 +" "+ delta2+" "+(delta1 > delta2)+" "+i+" "+denom2); - } while (delta1 > delta2 && denom2 <= 10000 && denom2 > 0 && i < 25); - if (i == 25) { - throw new ArithmeticException("Unable to convert double to fraction"); - } - return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0); - } - - /** - *

Creates a Fraction from a String.

- * - *

The formats accepted are:

- * - *
    - *
  1. double String containing a dot
  2. - *
  3. 'X Y/Z'
  4. - *
  5. 'Y/Z'
  6. - *
  7. 'X' (a simple whole number)
  8. - *
- * and a .

- * - * @param str the string to parse, must not be null - * @return the new Fraction instance - * @throws IllegalArgumentException if the string is null - * @throws NumberFormatException if the number format is invalid - */ - public static Fraction getFraction(String str) { - if (str == null) { - throw new IllegalArgumentException("The string must not be null"); - } - // parse double format - int pos = str.indexOf('.'); - if (pos >= 0) { - return getFraction(Double.parseDouble(str)); - } - - // parse X Y/Z format - pos = str.indexOf(' '); - if (pos > 0) { - int whole = Integer.parseInt(str.substring(0, pos)); - str = str.substring(pos + 1); - pos = str.indexOf('/'); - if (pos < 0) { - throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z"); - } else { - int numer = Integer.parseInt(str.substring(0, pos)); - int denom = Integer.parseInt(str.substring(pos + 1)); - return getFraction(whole, numer, denom); - } - } - - // parse Y/Z format - pos = str.indexOf('/'); - if (pos < 0) { - // simple whole number - return getFraction(Integer.parseInt(str), 1); - } else { - int numer = Integer.parseInt(str.substring(0, pos)); - int denom = Integer.parseInt(str.substring(pos + 1)); - return getFraction(numer, denom); - } - } - - // Accessors - //------------------------------------------------------------------- - - /** - *

Gets the numerator part of the fraction.

- * - *

This method may return a value greater than the denominator, an - * improper fraction, such as the seven in 7/4.

- * - * @return the numerator fraction part - */ - public int getNumerator() { - return numerator; - } - - /** - *

Gets the denominator part of the fraction.

- * - * @return the denominator fraction part - */ - public int getDenominator() { - return denominator; - } - - /** - *

Gets the proper numerator, always positive.

- * - *

An improper fraction 7/4 can be resolved into a proper one, 1 3/4. - * This method returns the 3 from the proper fraction.

- * - *

If the fraction is negative such as -7/4, it can be resolved into - * -1 3/4, so this method returns the positive proper numerator, 3.

- * - * @return the numerator fraction part of a proper fraction, always positive - */ - public int getProperNumerator() { - return Math.abs(numerator % denominator); - } - - /** - *

Gets the proper whole part of the fraction.

- * - *

An improper fraction 7/4 can be resolved into a proper one, 1 3/4. - * This method returns the 1 from the proper fraction.

- * - *

If the fraction is negative such as -7/4, it can be resolved into - * -1 3/4, so this method returns the positive whole part -1.

- * - * @return the whole fraction part of a proper fraction, that includes the sign - */ - public int getProperWhole() { - return numerator / denominator; - } - - // Number methods - //------------------------------------------------------------------- - - /** - *

Gets the fraction as an int. This returns the whole number - * part of the fraction.

- * - * @return the whole number fraction part - */ - @Override - public int intValue() { - return numerator / denominator; - } - - /** - *

Gets the fraction as a long. This returns the whole number - * part of the fraction.

- * - * @return the whole number fraction part - */ - @Override - public long longValue() { - return (long) numerator / denominator; - } - - /** - *

Gets the fraction as a float. This calculates the fraction - * as the numerator divided by denominator.

- * - * @return the fraction as a float - */ - @Override - public float floatValue() { - return (float) numerator / (float) denominator; - } - - /** - *

Gets the fraction as a double. This calculates the fraction - * as the numerator divided by denominator.

- * - * @return the fraction as a double - */ - @Override - public double doubleValue() { - return (double) numerator / (double) denominator; - } - - // Calculations - //------------------------------------------------------------------- - - /** - *

Reduce the fraction to the smallest values for the numerator and - * denominator, returning the result.

- * - *

For example, if this fraction represents 2/4, then the result - * will be 1/2.

- * - * @return a new reduced fraction instance, or this if no simplification possible - */ - public Fraction reduce() { - if (numerator == 0) { - return equals(ZERO) ? this : ZERO; - } - int gcd = greatestCommonDivisor(Math.abs(numerator), denominator); - if (gcd == 1) { - return this; - } - return Fraction.getFraction(numerator / gcd, denominator / gcd); - } - - /** - *

Gets a fraction that is the inverse (1/fraction) of this one.

- * - *

The returned fraction is not reduced.

- * - * @return a new fraction instance with the numerator and denominator - * inverted. - * @throws ArithmeticException if the fraction represents zero. - */ - public Fraction invert() { - if (numerator == 0) { - throw new ArithmeticException("Unable to invert zero."); - } - if (numerator==Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: can't negate numerator"); - } - if (numerator<0) { - return new Fraction(-denominator, -numerator); - } else { - return new Fraction(denominator, numerator); - } - } - - /** - *

Gets a fraction that is the negative (-fraction) of this one.

- * - *

The returned fraction is not reduced.

- * - * @return a new fraction instance with the opposite signed numerator - */ - public Fraction negate() { - // the positive range is one smaller than the negative range of an int. - if (numerator==Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: too large to negate"); - } - return new Fraction(-numerator, denominator); - } - - /** - *

Gets a fraction that is the positive equivalent of this one.

- *

More precisely: (fraction >= 0 ? this : -fraction)

- * - *

The returned fraction is not reduced.

- * - * @return this if it is positive, or a new positive fraction - * instance with the opposite signed numerator - */ - public Fraction abs() { - if (numerator >= 0) { - return this; - } - return negate(); - } - - /** - *

Gets a fraction that is raised to the passed in power.

- * - *

The returned fraction is in reduced form.

- * - * @param power the power to raise the fraction to - * @return this if the power is one, ONE if the power - * is zero (even if the fraction equals ZERO) or a new fraction instance - * raised to the appropriate power - * @throws ArithmeticException if the resulting numerator or denominator exceeds - * Integer.MAX_VALUE - */ - public Fraction pow(int power) { - if (power == 1) { - return this; - } else if (power == 0) { - return ONE; - } else if (power < 0) { - if (power==Integer.MIN_VALUE) { // MIN_VALUE can't be negated. - return this.invert().pow(2).pow(-(power/2)); - } - return this.invert().pow(-power); - } else { - Fraction f = this.multiplyBy(this); - if (power % 2 == 0) { // if even... - return f.pow(power/2); - } else { // if odd... - return f.pow(power/2).multiplyBy(this); - } - } - } - - /** - *

Gets the greatest common divisor of the absolute value of - * two numbers, using the "binary gcd" method which avoids - * division and modulo operations. See Knuth 4.5.2 algorithm B. - * This algorithm is due to Josef Stein (1961).

- * - * @param u a non-zero number - * @param v a non-zero number - * @return the greatest common divisor, never zero - */ - private static int greatestCommonDivisor(int u, int v) { - // From Commons Math: - if (u == 0 || v == 0) { - if (u == Integer.MIN_VALUE || v == Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: gcd is 2^31"); - } - return Math.abs(u) + Math.abs(v); - } - //if either operand is abs 1, return 1: - if (Math.abs(u) == 1 || Math.abs(v) == 1) { - return 1; - } - // keep u and v negative, as negative integers range down to - // -2^31, while positive numbers can only be as large as 2^31-1 - // (i.e. we can't necessarily negate a negative number without - // overflow) - if (u>0) { u=-u; } // make u negative - if (v>0) { v=-v; } // make v negative - // B1. [Find power of 2] - int k=0; - while ((u&1)==0 && (v&1)==0 && k<31) { // while u and v are both even... - u/=2; v/=2; k++; // cast out twos. - } - if (k==31) { - throw new ArithmeticException("overflow: gcd is 2^31"); - } - // B2. Initialize: u and v have been divided by 2^k and at least - // one is odd. - int t = (u&1)==1 ? v : -(u/2)/*B3*/; - // t negative: u was odd, v may be even (t replaces v) - // t positive: u was even, v is odd (t replaces u) - do { - /* assert u<0 && v<0; */ - // B4/B3: cast out twos from t. - while ((t&1)==0) { // while t is even.. - t/=2; // cast out twos - } - // B5 [reset max(u,v)] - if (t>0) { - u = -t; - } else { - v = t; - } - // B6/B3. at this point both u and v should be odd. - t = (v - u)/2; - // |u| larger: t positive (replace u) - // |v| larger: t negative (replace v) - } while (t!=0); - return -u*(1<x*y - * @throws ArithmeticException if the result can not be represented as - * an int - */ - private static int mulAndCheck(int x, int y) { - long m = (long)x*(long)y; - if (m < Integer.MIN_VALUE || - m > Integer.MAX_VALUE) { - throw new ArithmeticException("overflow: mul"); - } - return (int)m; - } - - /** - * Multiply two non-negative integers, checking for overflow. - * - * @param x a non-negative factor - * @param y a non-negative factor - * @return the product x*y - * @throws ArithmeticException if the result can not be represented as - * an int - */ - private static int mulPosAndCheck(int x, int y) { - /* assert x>=0 && y>=0; */ - long m = (long)x*(long)y; - if (m > Integer.MAX_VALUE) { - throw new ArithmeticException("overflow: mulPos"); - } - return (int)m; - } - - /** - * Add two integers, checking for overflow. - * - * @param x an addend - * @param y an addend - * @return the sum x+y - * @throws ArithmeticException if the result can not be represented as - * an int - */ - private static int addAndCheck(int x, int y) { - long s = (long)x+(long)y; - if (s < Integer.MIN_VALUE || - s > Integer.MAX_VALUE) { - throw new ArithmeticException("overflow: add"); - } - return (int)s; - } - - /** - * Subtract two integers, checking for overflow. - * - * @param x the minuend - * @param y the subtrahend - * @return the difference x-y - * @throws ArithmeticException if the result can not be represented as - * an int - */ - private static int subAndCheck(int x, int y) { - long s = (long)x-(long)y; - if (s < Integer.MIN_VALUE || - s > Integer.MAX_VALUE) { - throw new ArithmeticException("overflow: add"); - } - return (int)s; - } - - /** - *

Adds the value of this fraction to another, returning the result in reduced form. - * The algorithm follows Knuth, 4.5.1.

- * - * @param fraction the fraction to add, must not be null - * @return a Fraction instance with the resulting values - * @throws IllegalArgumentException if the fraction is null - * @throws ArithmeticException if the resulting numerator or denominator exceeds - * Integer.MAX_VALUE - */ - public Fraction add(Fraction fraction) { - return addSub(fraction, true /* add */); - } - - /** - *

Subtracts the value of another fraction from the value of this one, - * returning the result in reduced form.

- * - * @param fraction the fraction to subtract, must not be null - * @return a Fraction instance with the resulting values - * @throws IllegalArgumentException if the fraction is null - * @throws ArithmeticException if the resulting numerator or denominator - * cannot be represented in an int. - */ - public Fraction subtract(Fraction fraction) { - return addSub(fraction, false /* subtract */); - } - - /** - * Implement add and subtract using algorithm described in Knuth 4.5.1. - * - * @param fraction the fraction to subtract, must not be null - * @param isAdd true to add, false to subtract - * @return a Fraction instance with the resulting values - * @throws IllegalArgumentException if the fraction is null - * @throws ArithmeticException if the resulting numerator or denominator - * cannot be represented in an int. - */ - private Fraction addSub(Fraction fraction, boolean isAdd) { - if (fraction == null) { - throw new IllegalArgumentException("The fraction must not be null"); - } - // zero is identity for addition. - if (numerator == 0) { - return isAdd ? fraction : fraction.negate(); - } - if (fraction.numerator == 0) { - return this; - } - // if denominators are randomly distributed, d1 will be 1 about 61% - // of the time. - int d1 = greatestCommonDivisor(denominator, fraction.denominator); - if (d1==1) { - // result is ( (u*v' +/- u'v) / u'v') - int uvp = mulAndCheck(numerator, fraction.denominator); - int upv = mulAndCheck(fraction.numerator, denominator); - return new Fraction - (isAdd ? addAndCheck(uvp, upv) : subAndCheck(uvp, upv), - mulPosAndCheck(denominator, fraction.denominator)); - } - // the quantity 't' requires 65 bits of precision; see knuth 4.5.1 - // exercise 7. we're going to use a BigInteger. - // t = u(v'/d1) +/- v(u'/d1) - BigInteger uvp = BigInteger.valueOf(numerator) - .multiply(BigInteger.valueOf(fraction.denominator/d1)); - BigInteger upv = BigInteger.valueOf(fraction.numerator) - .multiply(BigInteger.valueOf(denominator/d1)); - BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv); - // but d2 doesn't need extra precision because - // d2 = gcd(t,d1) = gcd(t mod d1, d1) - int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue(); - int d2 = tmodd1==0?d1:greatestCommonDivisor(tmodd1, d1); - - // result is (t/d2) / (u'/d1)(v'/d2) - BigInteger w = t.divide(BigInteger.valueOf(d2)); - if (w.bitLength() > 31) { - throw new ArithmeticException - ("overflow: numerator too large after multiply"); - } - return new Fraction - (w.intValue(), - mulPosAndCheck(denominator/d1, fraction.denominator/d2)); - } - - /** - *

Multiplies the value of this fraction by another, returning the - * result in reduced form.

- * - * @param fraction the fraction to multiply by, must not be null - * @return a Fraction instance with the resulting values - * @throws IllegalArgumentException if the fraction is null - * @throws ArithmeticException if the resulting numerator or denominator exceeds - * Integer.MAX_VALUE - */ - public Fraction multiplyBy(Fraction fraction) { - if (fraction == null) { - throw new IllegalArgumentException("The fraction must not be null"); - } - if (numerator == 0 || fraction.numerator == 0) { - return ZERO; - } - // knuth 4.5.1 - // make sure we don't overflow unless the result *must* overflow. - int d1 = greatestCommonDivisor(numerator, fraction.denominator); - int d2 = greatestCommonDivisor(fraction.numerator, denominator); - return getReducedFraction - (mulAndCheck(numerator/d1, fraction.numerator/d2), - mulPosAndCheck(denominator/d2, fraction.denominator/d1)); - } - - /** - *

Divide the value of this fraction by another.

- * - * @param fraction the fraction to divide by, must not be null - * @return a Fraction instance with the resulting values - * @throws IllegalArgumentException if the fraction is null - * @throws ArithmeticException if the fraction to divide by is zero - * @throws ArithmeticException if the resulting numerator or denominator exceeds - * Integer.MAX_VALUE - */ - public Fraction divideBy(Fraction fraction) { - if (fraction == null) { - throw new IllegalArgumentException("The fraction must not be null"); - } - if (fraction.numerator == 0) { - throw new ArithmeticException("The fraction to divide by must not be zero"); - } - return multiplyBy(fraction.invert()); - } - - // Basics - //------------------------------------------------------------------- - - /** - *

Compares this fraction to another object to test if they are equal.

. - * - *

To be equal, both values must be equal. Thus 2/4 is not equal to 1/2.

- * - * @param obj the reference object with which to compare - * @return true if this object is equal - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof Fraction == false) { - return false; - } - Fraction other = (Fraction) obj; - return getNumerator() == other.getNumerator() && - getDenominator() == other.getDenominator(); - } - - /** - *

Gets a hashCode for the fraction.

- * - * @return a hash code value for this object - */ - @Override - public int hashCode() { - if (hashCode == 0) { - // hashcode update should be atomic. - hashCode = 37 * (37 * 17 + getNumerator()) + getDenominator(); - } - return hashCode; - } - - /** - *

Compares this object to another based on size.

- * - *

Note: this class has a natural ordering that is inconsistent - * with equals, because, for example, equals treats 1/2 and 2/4 as - * different, whereas compareTo treats them as equal. - * - * @param other the object to compare to - * @return -1 if this is less, 0 if equal, +1 if greater - * @throws ClassCastException if the object is not a Fraction - * @throws NullPointerException if the object is null - */ - public int compareTo(Fraction other) { - if (this==other) { - return 0; - } - if (numerator == other.numerator && denominator == other.denominator) { - return 0; - } - - // otherwise see which is less - long first = (long) numerator * (long) other.denominator; - long second = (long) other.numerator * (long) denominator; - if (first == second) { - return 0; - } else if (first < second) { - return -1; - } else { - return 1; - } - } - - /** - *

Gets the fraction as a String.

- * - *

The format used is 'numerator/denominator' always. - * - * @return a String form of the fraction - */ - @Override - public String toString() { - if (toString == null) { - toString = new StringBuilder(32) - .append(getNumerator()) - .append('/') - .append(getDenominator()).toString(); - } - return toString; - } - - /** - *

Gets the fraction as a proper String in the format X Y/Z.

- * - *

The format used in 'wholeNumber numerator/denominator'. - * If the whole number is zero it will be ommitted. If the numerator is zero, - * only the whole number is returned.

- * - * @return a String form of the fraction - */ - public String toProperString() { - if (toProperString == null) { - if (numerator == 0) { - toProperString = "0"; - } else if (numerator == denominator) { - toProperString = "1"; - } else if (numerator == -1 * denominator) { - toProperString = "-1"; - } else if ((numerator>0?-numerator:numerator) < -denominator) { - // note that we do the magnitude comparison test above with - // NEGATIVE (not positive) numbers, since negative numbers - // have a larger range. otherwise numerator==Integer.MIN_VALUE - // is handled incorrectly. - int properNumerator = getProperNumerator(); - if (properNumerator == 0) { - toProperString = Integer.toString(getProperWhole()); - } else { - toProperString = new StringBuilder(32) - .append(getProperWhole()).append(' ') - .append(properNumerator).append('/') - .append(getDenominator()).toString(); - } - } else { - toProperString = new StringBuilder(32) - .append(getNumerator()).append('/') - .append(getDenominator()).toString(); - } - } - return toProperString; - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/IEEE754rUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/math/IEEE754rUtils.java deleted file mode 100644 index 08cba77e..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/IEEE754rUtils.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.math; - -/** - *

Provides IEEE-754r variants of NumberUtils methods.

- * - *

See: http://en.wikipedia.org/wiki/IEEE_754r

- * - * @since 2.4 - * @version $Id: IEEE754rUtils.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class IEEE754rUtils { - - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static double min(double[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - double min = array[0]; - for (int i = 1; i < array.length; i++) { - min = min(array[i], min); - } - - return min; - } - - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static float min(float[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - float min = array[0]; - for (int i = 1; i < array.length; i++) { - min = min(array[i], min); - } - - return min; - } - - /** - *

Gets the minimum of three double values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static double min(double a, double b, double c) { - return min(min(a, b), c); - } - - /** - *

Gets the minimum of two double values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @return the smallest of the values - */ - public static double min(double a, double b) { - if(Double.isNaN(a)) { - return b; - } else - if(Double.isNaN(b)) { - return a; - } else { - return Math.min(a, b); - } - } - - /** - *

Gets the minimum of three float values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static float min(float a, float b, float c) { - return min(min(a, b), c); - } - - /** - *

Gets the minimum of two float values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @return the smallest of the values - */ - public static float min(float a, float b) { - if(Float.isNaN(a)) { - return b; - } else - if(Float.isNaN(b)) { - return a; - } else { - return Math.min(a, b); - } - } - - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static double max(double[] array) { - // Validates input - if (array== null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - double max = array[0]; - for (int j = 1; j < array.length; j++) { - max = max(array[j], max); - } - - return max; - } - - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static float max(float[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - float max = array[0]; - for (int j = 1; j < array.length; j++) { - max = max(array[j], max); - } - - return max; - } - - /** - *

Gets the maximum of three double values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static double max(double a, double b, double c) { - return max(max(a, b), c); - } - - /** - *

Gets the maximum of two double values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @return the largest of the values - */ - public static double max(double a, double b) { - if(Double.isNaN(a)) { - return b; - } else - if(Double.isNaN(b)) { - return a; - } else { - return Math.max(a, b); - } - } - - /** - *

Gets the maximum of three float values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static float max(float a, float b, float c) { - return max(max(a, b), c); - } - - /** - *

Gets the maximum of two float values.

- * - *

NaN is only returned if all numbers are NaN as per IEEE-754r.

- * - * @param a value 1 - * @param b value 2 - * @return the largest of the values - */ - public static float max(float a, float b) { - if(Float.isNaN(a)) { - return b; - } else - if(Float.isNaN(b)) { - return a; - } else { - return Math.max(a, b); - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/NumberUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/math/NumberUtils.java deleted file mode 100644 index feaad96f..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/NumberUtils.java +++ /dev/null @@ -1,1414 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.math; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import external.org.apache.commons.lang3.StringUtils; - -/** - *

Provides extra functionality for Java Number classes.

- * - * @since 2.0 - * @version $Id: NumberUtils.java 1199816 2011-11-09 16:11:34Z bayard $ - */ -public class NumberUtils { - - /** Reusable Long constant for zero. */ - public static final Long LONG_ZERO = Long.valueOf(0L); - /** Reusable Long constant for one. */ - public static final Long LONG_ONE = Long.valueOf(1L); - /** Reusable Long constant for minus one. */ - public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); - /** Reusable Integer constant for zero. */ - public static final Integer INTEGER_ZERO = Integer.valueOf(0); - /** Reusable Integer constant for one. */ - public static final Integer INTEGER_ONE = Integer.valueOf(1); - /** Reusable Integer constant for minus one. */ - public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); - /** Reusable Short constant for zero. */ - public static final Short SHORT_ZERO = Short.valueOf((short) 0); - /** Reusable Short constant for one. */ - public static final Short SHORT_ONE = Short.valueOf((short) 1); - /** Reusable Short constant for minus one. */ - public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); - /** Reusable Byte constant for zero. */ - public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); - /** Reusable Byte constant for one. */ - public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); - /** Reusable Byte constant for minus one. */ - public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); - /** Reusable Double constant for zero. */ - public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); - /** Reusable Double constant for one. */ - public static final Double DOUBLE_ONE = Double.valueOf(1.0d); - /** Reusable Double constant for minus one. */ - public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); - /** Reusable Float constant for zero. */ - public static final Float FLOAT_ZERO = Float.valueOf(0.0f); - /** Reusable Float constant for one. */ - public static final Float FLOAT_ONE = Float.valueOf(1.0f); - /** Reusable Float constant for minus one. */ - public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); - - /** - *

NumberUtils instances should NOT be constructed in standard programming. - * Instead, the class should be used as NumberUtils.toInt("6");.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- */ - public NumberUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - *

Convert a String to an int, returning - * zero if the conversion fails.

- * - *

If the string is null, zero is returned.

- * - *
-     *   NumberUtils.toInt(null) = 0
-     *   NumberUtils.toInt("")   = 0
-     *   NumberUtils.toInt("1")  = 1
-     * 
- * - * @param str the string to convert, may be null - * @return the int represented by the string, or zero if - * conversion fails - * @since 2.1 - */ - public static int toInt(String str) { - return toInt(str, 0); - } - - /** - *

Convert a String to an int, returning a - * default value if the conversion fails.

- * - *

If the string is null, the default value is returned.

- * - *
-     *   NumberUtils.toInt(null, 1) = 1
-     *   NumberUtils.toInt("", 1)   = 1
-     *   NumberUtils.toInt("1", 0)  = 1
-     * 
- * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the int represented by the string, or the default if conversion fails - * @since 2.1 - */ - public static int toInt(String str, int defaultValue) { - if(str == null) { - return defaultValue; - } - try { - return Integer.parseInt(str); - } catch (NumberFormatException nfe) { - return defaultValue; - } - } - - /** - *

Convert a String to a long, returning - * zero if the conversion fails.

- * - *

If the string is null, zero is returned.

- * - *
-     *   NumberUtils.toLong(null) = 0L
-     *   NumberUtils.toLong("")   = 0L
-     *   NumberUtils.toLong("1")  = 1L
-     * 
- * - * @param str the string to convert, may be null - * @return the long represented by the string, or 0 if - * conversion fails - * @since 2.1 - */ - public static long toLong(String str) { - return toLong(str, 0L); - } - - /** - *

Convert a String to a long, returning a - * default value if the conversion fails.

- * - *

If the string is null, the default value is returned.

- * - *
-     *   NumberUtils.toLong(null, 1L) = 1L
-     *   NumberUtils.toLong("", 1L)   = 1L
-     *   NumberUtils.toLong("1", 0L)  = 1L
-     * 
- * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the long represented by the string, or the default if conversion fails - * @since 2.1 - */ - public static long toLong(String str, long defaultValue) { - if (str == null) { - return defaultValue; - } - try { - return Long.parseLong(str); - } catch (NumberFormatException nfe) { - return defaultValue; - } - } - - /** - *

Convert a String to a float, returning - * 0.0f if the conversion fails.

- * - *

If the string str is null, - * 0.0f is returned.

- * - *
-     *   NumberUtils.toFloat(null)   = 0.0f
-     *   NumberUtils.toFloat("")     = 0.0f
-     *   NumberUtils.toFloat("1.5")  = 1.5f
-     * 
- * - * @param str the string to convert, may be null - * @return the float represented by the string, or 0.0f - * if conversion fails - * @since 2.1 - */ - public static float toFloat(String str) { - return toFloat(str, 0.0f); - } - - /** - *

Convert a String to a float, returning a - * default value if the conversion fails.

- * - *

If the string str is null, the default - * value is returned.

- * - *
-     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
-     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
-     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
-     * 
- * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the float represented by the string, or defaultValue - * if conversion fails - * @since 2.1 - */ - public static float toFloat(String str, float defaultValue) { - if (str == null) { - return defaultValue; - } - try { - return Float.parseFloat(str); - } catch (NumberFormatException nfe) { - return defaultValue; - } - } - - /** - *

Convert a String to a double, returning - * 0.0d if the conversion fails.

- * - *

If the string str is null, - * 0.0d is returned.

- * - *
-     *   NumberUtils.toDouble(null)   = 0.0d
-     *   NumberUtils.toDouble("")     = 0.0d
-     *   NumberUtils.toDouble("1.5")  = 1.5d
-     * 
- * - * @param str the string to convert, may be null - * @return the double represented by the string, or 0.0d - * if conversion fails - * @since 2.1 - */ - public static double toDouble(String str) { - return toDouble(str, 0.0d); - } - - /** - *

Convert a String to a double, returning a - * default value if the conversion fails.

- * - *

If the string str is null, the default - * value is returned.

- * - *
-     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
-     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
-     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
-     * 
- * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the double represented by the string, or defaultValue - * if conversion fails - * @since 2.1 - */ - public static double toDouble(String str, double defaultValue) { - if (str == null) { - return defaultValue; - } - try { - return Double.parseDouble(str); - } catch (NumberFormatException nfe) { - return defaultValue; - } - } - - //----------------------------------------------------------------------- - /** - *

Convert a String to a byte, returning - * zero if the conversion fails.

- * - *

If the string is null, zero is returned.

- * - *
-     *   NumberUtils.toByte(null) = 0
-     *   NumberUtils.toByte("")   = 0
-     *   NumberUtils.toByte("1")  = 1
-     * 
- * - * @param str the string to convert, may be null - * @return the byte represented by the string, or zero if - * conversion fails - * @since 2.5 - */ - public static byte toByte(String str) { - return toByte(str, (byte) 0); - } - - /** - *

Convert a String to a byte, returning a - * default value if the conversion fails.

- * - *

If the string is null, the default value is returned.

- * - *
-     *   NumberUtils.toByte(null, 1) = 1
-     *   NumberUtils.toByte("", 1)   = 1
-     *   NumberUtils.toByte("1", 0)  = 1
-     * 
- * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the byte represented by the string, or the default if conversion fails - * @since 2.5 - */ - public static byte toByte(String str, byte defaultValue) { - if(str == null) { - return defaultValue; - } - try { - return Byte.parseByte(str); - } catch (NumberFormatException nfe) { - return defaultValue; - } - } - - /** - *

Convert a String to a short, returning - * zero if the conversion fails.

- * - *

If the string is null, zero is returned.

- * - *
-     *   NumberUtils.toShort(null) = 0
-     *   NumberUtils.toShort("")   = 0
-     *   NumberUtils.toShort("1")  = 1
-     * 
- * - * @param str the string to convert, may be null - * @return the short represented by the string, or zero if - * conversion fails - * @since 2.5 - */ - public static short toShort(String str) { - return toShort(str, (short) 0); - } - - /** - *

Convert a String to an short, returning a - * default value if the conversion fails.

- * - *

If the string is null, the default value is returned.

- * - *
-     *   NumberUtils.toShort(null, 1) = 1
-     *   NumberUtils.toShort("", 1)   = 1
-     *   NumberUtils.toShort("1", 0)  = 1
-     * 
- * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the short represented by the string, or the default if conversion fails - * @since 2.5 - */ - public static short toShort(String str, short defaultValue) { - if(str == null) { - return defaultValue; - } - try { - return Short.parseShort(str); - } catch (NumberFormatException nfe) { - return defaultValue; - } - } - - //----------------------------------------------------------------------- - // must handle Long, Float, Integer, Float, Short, - // BigDecimal, BigInteger and Byte - // useful methods: - // Byte.decode(String) - // Byte.valueOf(String,int radix) - // Byte.valueOf(String) - // Double.valueOf(String) - // Float.valueOf(String) - // Float.valueOf(String) - // Integer.valueOf(String,int radix) - // Integer.valueOf(String) - // Integer.decode(String) - // Integer.getInteger(String) - // Integer.getInteger(String,int val) - // Integer.getInteger(String,Integer val) - // Integer.valueOf(String) - // Double.valueOf(String) - // new Byte(String) - // Long.valueOf(String) - // Long.getLong(String) - // Long.getLong(String,int) - // Long.getLong(String,Integer) - // Long.valueOf(String,int) - // Long.valueOf(String) - // Short.valueOf(String) - // Short.decode(String) - // Short.valueOf(String,int) - // Short.valueOf(String) - // new BigDecimal(String) - // new BigInteger(String) - // new BigInteger(String,int radix) - // Possible inputs: - // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd - // plus minus everything. Prolly more. A lot are not separable. - - /** - *

Turns a string value into a java.lang.Number.

- * - *

First, the value is examined for a type qualifier on the end - * ('f','F','d','D','l','L'). If it is found, it starts - * trying to create successively larger types from the type specified - * until one is found that can represent the value.

- * - *

If a type specifier is not found, it will check for a decimal point - * and then try successively larger types from Integer to - * BigInteger and from Float to - * BigDecimal.

- * - *

If the string starts with 0x or -0x (lower or upper case), it - * will be interpreted as a hexadecimal integer. Values with leading - * 0's will not be interpreted as octal.

- * - *

Returns null if the string is null.

- * - *

This method does not trim the input string, i.e., strings with leading - * or trailing spaces will generate NumberFormatExceptions.

- * - * @param str String containing a number, may be null - * @return Number created from the string (or null if the input is null) - * @throws NumberFormatException if the value cannot be converted - */ - public static Number createNumber(String str) throws NumberFormatException { - if (str == null) { - return null; - } - if (StringUtils.isBlank(str)) { - throw new NumberFormatException("A blank string is not a valid number"); - } - if (str.startsWith("--")) { - // this is protection for poorness in java.lang.BigDecimal. - // it accepts this as a legal value, but it does not appear - // to be in specification of class. OS X Java parses it to - // a wrong value. - return null; - } - if (str.startsWith("0x") || str.startsWith("-0x") || str.startsWith("0X") || str.startsWith("-0X")) { - return createInteger(str); - } - char lastChar = str.charAt(str.length() - 1); - String mant; - String dec; - String exp; - int decPos = str.indexOf('.'); - int expPos = str.indexOf('e') + str.indexOf('E') + 1; - - if (decPos > -1) { - - if (expPos > -1) { - if (expPos < decPos || expPos > str.length()) { - throw new NumberFormatException(str + " is not a valid number."); - } - dec = str.substring(decPos + 1, expPos); - } else { - dec = str.substring(decPos + 1); - } - mant = str.substring(0, decPos); - } else { - if (expPos > -1) { - if (expPos > str.length()) { - throw new NumberFormatException(str + " is not a valid number."); - } - mant = str.substring(0, expPos); - } else { - mant = str; - } - dec = null; - } - if (!Character.isDigit(lastChar) && lastChar != '.') { - if (expPos > -1 && expPos < str.length() - 1) { - exp = str.substring(expPos + 1, str.length() - 1); - } else { - exp = null; - } - //Requesting a specific type.. - String numeric = str.substring(0, str.length() - 1); - boolean allZeros = isAllZeros(mant) && isAllZeros(exp); - switch (lastChar) { - case 'l' : - case 'L' : - if (dec == null - && exp == null - && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { - try { - return createLong(numeric); - } catch (NumberFormatException nfe) { // NOPMD - // Too big for a long - } - return createBigInteger(numeric); - - } - throw new NumberFormatException(str + " is not a valid number."); - case 'f' : - case 'F' : - try { - Float f = NumberUtils.createFloat(numeric); - if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { - //If it's too big for a float or the float value = 0 and the string - //has non-zeros in it, then float does not have the precision we want - return f; - } - - } catch (NumberFormatException nfe) { // NOPMD - // ignore the bad number - } - //$FALL-THROUGH$ - case 'd' : - case 'D' : - try { - Double d = NumberUtils.createDouble(numeric); - if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { - return d; - } - } catch (NumberFormatException nfe) { // NOPMD - // ignore the bad number - } - try { - return createBigDecimal(numeric); - } catch (NumberFormatException e) { // NOPMD - // ignore the bad number - } - //$FALL-THROUGH$ - default : - throw new NumberFormatException(str + " is not a valid number."); - - } - } else { - //User doesn't have a preference on the return type, so let's start - //small and go from there... - if (expPos > -1 && expPos < str.length() - 1) { - exp = str.substring(expPos + 1, str.length()); - } else { - exp = null; - } - if (dec == null && exp == null) { - //Must be an int,long,bigint - try { - return createInteger(str); - } catch (NumberFormatException nfe) { // NOPMD - // ignore the bad number - } - try { - return createLong(str); - } catch (NumberFormatException nfe) { // NOPMD - // ignore the bad number - } - return createBigInteger(str); - - } else { - //Must be a float,double,BigDec - boolean allZeros = isAllZeros(mant) && isAllZeros(exp); - try { - Float f = createFloat(str); - if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { - return f; - } - } catch (NumberFormatException nfe) { // NOPMD - // ignore the bad number - } - try { - Double d = createDouble(str); - if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { - return d; - } - } catch (NumberFormatException nfe) { // NOPMD - // ignore the bad number - } - - return createBigDecimal(str); - - } - } - } - - /** - *

Utility method for {@link #createNumber(java.lang.String)}.

- * - *

Returns true if s is null.

- * - * @param str the String to check - * @return if it is all zeros or null - */ - private static boolean isAllZeros(String str) { - if (str == null) { - return true; - } - for (int i = str.length() - 1; i >= 0; i--) { - if (str.charAt(i) != '0') { - return false; - } - } - return str.length() > 0; - } - - //----------------------------------------------------------------------- - /** - *

Convert a String to a Float.

- * - *

Returns null if the string is null.

- * - * @param str a String to convert, may be null - * @return converted Float - * @throws NumberFormatException if the value cannot be converted - */ - public static Float createFloat(String str) { - if (str == null) { - return null; - } - return Float.valueOf(str); - } - - /** - *

Convert a String to a Double.

- * - *

Returns null if the string is null.

- * - * @param str a String to convert, may be null - * @return converted Double - * @throws NumberFormatException if the value cannot be converted - */ - public static Double createDouble(String str) { - if (str == null) { - return null; - } - return Double.valueOf(str); - } - - /** - *

Convert a String to a Integer, handling - * hex and octal notations.

- * - *

Returns null if the string is null.

- * - * @param str a String to convert, may be null - * @return converted Integer - * @throws NumberFormatException if the value cannot be converted - */ - public static Integer createInteger(String str) { - if (str == null) { - return null; - } - // decode() handles 0xAABD and 0777 (hex and octal) as well. - return Integer.decode(str); - } - - /** - *

Convert a String to a Long; - * since 3.1 it handles hex and octal notations.

- * - *

Returns null if the string is null.

- * - * @param str a String to convert, may be null - * @return converted Long - * @throws NumberFormatException if the value cannot be converted - */ - public static Long createLong(String str) { - if (str == null) { - return null; - } - return Long.decode(str); - } - - /** - *

Convert a String to a BigInteger.

- * - *

Returns null if the string is null.

- * - * @param str a String to convert, may be null - * @return converted BigInteger - * @throws NumberFormatException if the value cannot be converted - */ - public static BigInteger createBigInteger(String str) { - if (str == null) { - return null; - } - return new BigInteger(str); - } - - /** - *

Convert a String to a BigDecimal.

- * - *

Returns null if the string is null.

- * - * @param str a String to convert, may be null - * @return converted BigDecimal - * @throws NumberFormatException if the value cannot be converted - */ - public static BigDecimal createBigDecimal(String str) { - if (str == null) { - return null; - } - // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException - if (StringUtils.isBlank(str)) { - throw new NumberFormatException("A blank string is not a valid number"); - } - return new BigDecimal(str); - } - - // Min in array - //-------------------------------------------------------------------- - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static long min(long[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - long min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static int min(int[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - int min = array[0]; - for (int j = 1; j < array.length; j++) { - if (array[j] < min) { - min = array[j]; - } - } - - return min; - } - - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static short min(short[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - short min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static byte min(byte[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - byte min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently - */ - public static double min(double[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - double min = array[0]; - for (int i = 1; i < array.length; i++) { - if (Double.isNaN(array[i])) { - return Double.NaN; - } - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

Returns the minimum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently - */ - public static float min(float[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns min - float min = array[0]; - for (int i = 1; i < array.length; i++) { - if (Float.isNaN(array[i])) { - return Float.NaN; - } - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - // Max in array - //-------------------------------------------------------------------- - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static long max(long[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - long max = array[0]; - for (int j = 1; j < array.length; j++) { - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static int max(int[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - int max = array[0]; - for (int j = 1; j < array.length; j++) { - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static short max(short[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - short max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - - return max; - } - - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - */ - public static byte max(byte[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - byte max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - - return max; - } - - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently - */ - public static double max(double[] array) { - // Validates input - if (array== null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - double max = array[0]; - for (int j = 1; j < array.length; j++) { - if (Double.isNaN(array[j])) { - return Double.NaN; - } - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - /** - *

Returns the maximum value in an array.

- * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if array is null - * @throws IllegalArgumentException if array is empty - * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently - */ - public static float max(float[] array) { - // Validates input - if (array == null) { - throw new IllegalArgumentException("The Array must not be null"); - } else if (array.length == 0) { - throw new IllegalArgumentException("Array cannot be empty."); - } - - // Finds and returns max - float max = array[0]; - for (int j = 1; j < array.length; j++) { - if (Float.isNaN(array[j])) { - return Float.NaN; - } - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - // 3 param min - //----------------------------------------------------------------------- - /** - *

Gets the minimum of three long values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static long min(long a, long b, long c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

Gets the minimum of three int values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static int min(int a, int b, int c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

Gets the minimum of three short values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static short min(short a, short b, short c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

Gets the minimum of three byte values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static byte min(byte a, byte b, byte c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

Gets the minimum of three double values.

- * - *

If any value is NaN, NaN is - * returned. Infinity is handled.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently - */ - public static double min(double a, double b, double c) { - return Math.min(Math.min(a, b), c); - } - - /** - *

Gets the minimum of three float values.

- * - *

If any value is NaN, NaN is - * returned. Infinity is handled.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently - */ - public static float min(float a, float b, float c) { - return Math.min(Math.min(a, b), c); - } - - // 3 param max - //----------------------------------------------------------------------- - /** - *

Gets the maximum of three long values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static long max(long a, long b, long c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

Gets the maximum of three int values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static int max(int a, int b, int c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

Gets the maximum of three short values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static short max(short a, short b, short c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

Gets the maximum of three byte values.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static byte max(byte a, byte b, byte c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

Gets the maximum of three double values.

- * - *

If any value is NaN, NaN is - * returned. Infinity is handled.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently - */ - public static double max(double a, double b, double c) { - return Math.max(Math.max(a, b), c); - } - - /** - *

Gets the maximum of three float values.

- * - *

If any value is NaN, NaN is - * returned. Infinity is handled.

- * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently - */ - public static float max(float a, float b, float c) { - return Math.max(Math.max(a, b), c); - } - - //----------------------------------------------------------------------- - /** - *

Checks whether the String contains only - * digit characters.

- * - *

Null and empty String will return - * false.

- * - * @param str the String to check - * @return true if str contains only Unicode numeric - */ - public static boolean isDigits(String str) { - if (StringUtils.isEmpty(str)) { - return false; - } - for (int i = 0; i < str.length(); i++) { - if (!Character.isDigit(str.charAt(i))) { - return false; - } - } - return true; - } - - /** - *

Checks whether the String a valid Java number.

- * - *

Valid numbers include hexadecimal marked with the 0x - * qualifier, scientific notation and numbers marked with a type - * qualifier (e.g. 123L).

- * - *

Null and empty String will return - * false.

- * - * @param str the String to check - * @return true if the string is a correctly formatted number - */ - public static boolean isNumber(String str) { - if (StringUtils.isEmpty(str)) { - return false; - } - char[] chars = str.toCharArray(); - int sz = chars.length; - boolean hasExp = false; - boolean hasDecPoint = false; - boolean allowSigns = false; - boolean foundDigit = false; - // deal with any possible sign up front - int start = (chars[0] == '-') ? 1 : 0; - if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') { - int i = start + 2; - if (i == sz) { - return false; // str == "0x" - } - // checking hex (it can't be anything else) - for (; i < chars.length; i++) { - if ((chars[i] < '0' || chars[i] > '9') - && (chars[i] < 'a' || chars[i] > 'f') - && (chars[i] < 'A' || chars[i] > 'F')) { - return false; - } - } - return true; - } - sz--; // don't want to loop to the last char, check it afterwords - // for type qualifiers - int i = start; - // loop to the next to last char or to the last char if we need another digit to - // make a valid number (e.g. chars[0..5] = "1234E") - while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { - if (chars[i] >= '0' && chars[i] <= '9') { - foundDigit = true; - allowSigns = false; - - } else if (chars[i] == '.') { - if (hasDecPoint || hasExp) { - // two decimal points or dec in exponent - return false; - } - hasDecPoint = true; - } else if (chars[i] == 'e' || chars[i] == 'E') { - // we've already taken care of hex. - if (hasExp) { - // two E's - return false; - } - if (!foundDigit) { - return false; - } - hasExp = true; - allowSigns = true; - } else if (chars[i] == '+' || chars[i] == '-') { - if (!allowSigns) { - return false; - } - allowSigns = false; - foundDigit = false; // we need a digit after the E - } else { - return false; - } - i++; - } - if (i < chars.length) { - if (chars[i] >= '0' && chars[i] <= '9') { - // no type qualifier, OK - return true; - } - if (chars[i] == 'e' || chars[i] == 'E') { - // can't have an E at the last byte - return false; - } - if (chars[i] == '.') { - if (hasDecPoint || hasExp) { - // two decimal points or dec in exponent - return false; - } - // single trailing decimal point after non-exponent is ok - return foundDigit; - } - if (!allowSigns - && (chars[i] == 'd' - || chars[i] == 'D' - || chars[i] == 'f' - || chars[i] == 'F')) { - return foundDigit; - } - if (chars[i] == 'l' - || chars[i] == 'L') { - // not allowing L with an exponent or decimal point - return foundDigit && !hasExp && !hasDecPoint; - } - // last character is illegal - return false; - } - // allowSigns is true iff the val ends in 'E' - // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass - return !allowSigns && foundDigit; - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/package.html b/lib/apache-commons-lang/external/org/apache/commons/lang3/math/package.html deleted file mode 100644 index 7f629119..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/math/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - -Extends {@link java.math} for business mathematical classes. This package is intended for business -mathematical use, not scientific use. See Commons Math -for a more complete set of mathematical classes. -@since 2.0 -

These classes are immutable, and therefore thread-safe.

- - diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableBoolean.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableBoolean.java deleted file mode 100644 index 8b7243a2..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableBoolean.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package external.org.apache.commons.lang3.mutable; - -import java.io.Serializable; - -/** - * A mutable boolean wrapper. - *

- * Note that as MutableBoolean does not extend Boolean, it is not treated by String.format as a Boolean parameter. - * - * @see Boolean - * @since 2.2 - * @version $Id: MutableBoolean.java 1160571 2011-08-23 07:36:08Z bayard $ - */ -public class MutableBoolean implements Mutable, Serializable, Comparable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = -4830728138360036487L; - - /** The mutable value. */ - private boolean value; - - /** - * Constructs a new MutableBoolean with the default value of false. - */ - public MutableBoolean() { - super(); - } - - /** - * Constructs a new MutableBoolean with the specified value. - * - * @param value the initial value to store - */ - public MutableBoolean(boolean value) { - super(); - this.value = value; - } - - /** - * Constructs a new MutableBoolean with the specified value. - * - * @param value the initial value to store, not null - * @throws NullPointerException if the object is null - */ - public MutableBoolean(Boolean value) { - super(); - this.value = value.booleanValue(); - } - - //----------------------------------------------------------------------- - /** - * Gets the value as a Boolean instance. - * - * @return the value as a Boolean, never null - */ - public Boolean getValue() { - return Boolean.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(boolean value) { - this.value = value; - } - - /** - * Sets the value from any Boolean instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - public void setValue(Boolean value) { - this.value = value.booleanValue(); - } - - //----------------------------------------------------------------------- - /** - * Checks if the current value is true. - * - * @return true if the current value is true - * @since 2.5 - */ - public boolean isTrue() { - return value == true; - } - - /** - * Checks if the current value is false. - * - * @return true if the current value is false - * @since 2.5 - */ - public boolean isFalse() { - return value == false; - } - - //----------------------------------------------------------------------- - /** - * Returns the value of this MutableBoolean as a boolean. - * - * @return the boolean value represented by this object. - */ - public boolean booleanValue() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Boolean. - * - * @return a Boolean instance containing the value from this mutable, never null - * @since 2.5 - */ - public Boolean toBoolean() { - return Boolean.valueOf(booleanValue()); - } - - //----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is true if and only if the argument is - * not null and is an MutableBoolean object that contains the same - * boolean value as this object. - * - * @param obj the object to compare with, null returns false - * @return true if the objects are the same; false otherwise. - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof MutableBoolean) { - return value == ((MutableBoolean) obj).booleanValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return the hash code returned by Boolean.TRUE or Boolean.FALSE - */ - @Override - public int hashCode() { - return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode(); - } - - //----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - * where false is less than true - */ - public int compareTo(MutableBoolean other) { - boolean anotherVal = other.value; - return value == anotherVal ? 0 : (value ? 1 : -1); - } - - //----------------------------------------------------------------------- - /** - * Returns the String value of this mutable. - * - * @return the mutable value as a string - */ - @Override - public String toString() { - return String.valueOf(value); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableByte.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableByte.java deleted file mode 100644 index 911230fb..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableByte.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.mutable; - -/** - * A mutable byte wrapper. - *

- * Note that as MutableByte does not extend Byte, it is not treated by String.format as a Byte parameter. - * - * @see Byte - * @since 2.1 - * @version $Id: MutableByte.java 1160571 2011-08-23 07:36:08Z bayard $ - */ -public class MutableByte extends Number implements Comparable, Mutable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = -1585823265L; - - /** The mutable value. */ - private byte value; - - /** - * Constructs a new MutableByte with the default value of zero. - */ - public MutableByte() { - super(); - } - - /** - * Constructs a new MutableByte with the specified value. - * - * @param value the initial value to store - */ - public MutableByte(byte value) { - super(); - this.value = value; - } - - /** - * Constructs a new MutableByte with the specified value. - * - * @param value the initial value to store, not null - * @throws NullPointerException if the object is null - */ - public MutableByte(Number value) { - super(); - this.value = value.byteValue(); - } - - /** - * Constructs a new MutableByte parsing the given string. - * - * @param value the string to parse, not null - * @throws NumberFormatException if the string cannot be parsed into a byte - * @since 2.5 - */ - public MutableByte(String value) throws NumberFormatException { - super(); - this.value = Byte.parseByte(value); - } - - //----------------------------------------------------------------------- - /** - * Gets the value as a Byte instance. - * - * @return the value as a Byte, never null - */ - public Byte getValue() { - return Byte.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(byte value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - public void setValue(Number value) { - this.value = value.byteValue(); - } - - //----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since Commons Lang 2.2 - */ - public void increment() { - value++; - } - - /** - * Decrements the value. - * - * @since Commons Lang 2.2 - */ - public void decrement() { - value--; - } - - //----------------------------------------------------------------------- - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @since Commons Lang 2.2 - */ - public void add(byte operand) { - this.value += operand; - } - - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void add(Number operand) { - this.value += operand.byteValue(); - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since Commons Lang 2.2 - */ - public void subtract(byte operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void subtract(Number operand) { - this.value -= operand.byteValue(); - } - - //----------------------------------------------------------------------- - // shortValue relies on Number implementation - /** - * Returns the value of this MutableByte as a byte. - * - * @return the numeric value represented by this object after conversion to type byte. - */ - @Override - public byte byteValue() { - return value; - } - - /** - * Returns the value of this MutableByte as an int. - * - * @return the numeric value represented by this object after conversion to type int. - */ - @Override - public int intValue() { - return value; - } - - /** - * Returns the value of this MutableByte as a long. - * - * @return the numeric value represented by this object after conversion to type long. - */ - @Override - public long longValue() { - return value; - } - - /** - * Returns the value of this MutableByte as a float. - * - * @return the numeric value represented by this object after conversion to type float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value of this MutableByte as a double. - * - * @return the numeric value represented by this object after conversion to type double. - */ - @Override - public double doubleValue() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Byte. - * - * @return a Byte instance containing the value from this mutable - */ - public Byte toByte() { - return Byte.valueOf(byteValue()); - } - - //----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is true if and only if the argument is - * not null and is a MutableByte object that contains the same byte value - * as this object. - * - * @param obj the object to compare with, null returns false - * @return true if the objects are the same; false otherwise. - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof MutableByte) { - return value == ((MutableByte) obj).byteValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - public int compareTo(MutableByte other) { - byte anotherVal = other.value; - return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1); - } - - //----------------------------------------------------------------------- - /** - * Returns the String value of this mutable. - * - * @return the mutable value as a string - */ - @Override - public String toString() { - return String.valueOf(value); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableDouble.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableDouble.java deleted file mode 100644 index 414c7e97..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableDouble.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.mutable; - -/** - * A mutable double wrapper. - *

- * Note that as MutableDouble does not extend Double, it is not treated by String.format as a Double parameter. - * - * @see Double - * @since 2.1 - * @version $Id: MutableDouble.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class MutableDouble extends Number implements Comparable, Mutable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 1587163916L; - - /** The mutable value. */ - private double value; - - /** - * Constructs a new MutableDouble with the default value of zero. - */ - public MutableDouble() { - super(); - } - - /** - * Constructs a new MutableDouble with the specified value. - * - * @param value the initial value to store - */ - public MutableDouble(double value) { - super(); - this.value = value; - } - - /** - * Constructs a new MutableDouble with the specified value. - * - * @param value the initial value to store, not null - * @throws NullPointerException if the object is null - */ - public MutableDouble(Number value) { - super(); - this.value = value.doubleValue(); - } - - /** - * Constructs a new MutableDouble parsing the given string. - * - * @param value the string to parse, not null - * @throws NumberFormatException if the string cannot be parsed into a double - * @since 2.5 - */ - public MutableDouble(String value) throws NumberFormatException { - super(); - this.value = Double.parseDouble(value); - } - - //----------------------------------------------------------------------- - /** - * Gets the value as a Double instance. - * - * @return the value as a Double, never null - */ - public Double getValue() { - return Double.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(double value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - public void setValue(Number value) { - this.value = value.doubleValue(); - } - - //----------------------------------------------------------------------- - /** - * Checks whether the double value is the special NaN value. - * - * @return true if NaN - */ - public boolean isNaN() { - return Double.isNaN(value); - } - - /** - * Checks whether the double value is infinite. - * - * @return true if infinite - */ - public boolean isInfinite() { - return Double.isInfinite(value); - } - - //----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since Commons Lang 2.2 - */ - public void increment() { - value++; - } - - /** - * Decrements the value. - * - * @since Commons Lang 2.2 - */ - public void decrement() { - value--; - } - - //----------------------------------------------------------------------- - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add - * @since Commons Lang 2.2 - */ - public void add(double operand) { - this.value += operand; - } - - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void add(Number operand) { - this.value += operand.doubleValue(); - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since Commons Lang 2.2 - */ - public void subtract(double operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void subtract(Number operand) { - this.value -= operand.doubleValue(); - } - - //----------------------------------------------------------------------- - // shortValue and byteValue rely on Number implementation - /** - * Returns the value of this MutableDouble as an int. - * - * @return the numeric value represented by this object after conversion to type int. - */ - @Override - public int intValue() { - return (int) value; - } - - /** - * Returns the value of this MutableDouble as a long. - * - * @return the numeric value represented by this object after conversion to type long. - */ - @Override - public long longValue() { - return (long) value; - } - - /** - * Returns the value of this MutableDouble as a float. - * - * @return the numeric value represented by this object after conversion to type float. - */ - @Override - public float floatValue() { - return (float) value; - } - - /** - * Returns the value of this MutableDouble as a double. - * - * @return the numeric value represented by this object after conversion to type double. - */ - @Override - public double doubleValue() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Double. - * - * @return a Double instance containing the value from this mutable, never null - */ - public Double toDouble() { - return Double.valueOf(doubleValue()); - } - - //----------------------------------------------------------------------- - /** - * Compares this object against the specified object. The result is true if and only if the argument - * is not null and is a Double object that represents a double that has the identical - * bit pattern to the bit pattern of the double represented by this object. For this purpose, two - * double values are considered to be the same if and only if the method - * {@link Double#doubleToLongBits(double)}returns the same long value when applied to each. - *

- * Note that in most cases, for two instances of class Double,d1 and d2, - * the value of d1.equals(d2) is true if and only if

- * - *
-     *   d1.doubleValue() == d2.doubleValue()
-     * 
- * - *
- *

- * also has the value true. However, there are two exceptions: - *

    - *
  • If d1 and d2 both represent Double.NaN, then the - * equals method returns true, even though Double.NaN==Double.NaN has - * the value false. - *
  • If d1 represents +0.0 while d2 represents -0.0, - * or vice versa, the equal test has the value false, even though - * +0.0==-0.0 has the value true. This allows hashtables to operate properly. - *
- * - * @param obj the object to compare with, null returns false - * @return true if the objects are the same; false otherwise. - */ - @Override - public boolean equals(Object obj) { - return obj instanceof MutableDouble - && Double.doubleToLongBits(((MutableDouble) obj).value) == Double.doubleToLongBits(value); - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - long bits = Double.doubleToLongBits(value); - return (int) (bits ^ bits >>> 32); - } - - //----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - public int compareTo(MutableDouble other) { - double anotherVal = other.value; - return Double.compare(value, anotherVal); - } - - //----------------------------------------------------------------------- - /** - * Returns the String value of this mutable. - * - * @return the mutable value as a string - */ - @Override - public String toString() { - return String.valueOf(value); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableFloat.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableFloat.java deleted file mode 100644 index 4e932cb1..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableFloat.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.mutable; - -/** - * A mutable float wrapper. - *

- * Note that as MutableFloat does not extend Float, it is not treated by String.format as a Float parameter. - * - * @see Float - * @since 2.1 - * @version $Id: MutableFloat.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class MutableFloat extends Number implements Comparable, Mutable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 5787169186L; - - /** The mutable value. */ - private float value; - - /** - * Constructs a new MutableFloat with the default value of zero. - */ - public MutableFloat() { - super(); - } - - /** - * Constructs a new MutableFloat with the specified value. - * - * @param value the initial value to store - */ - public MutableFloat(float value) { - super(); - this.value = value; - } - - /** - * Constructs a new MutableFloat with the specified value. - * - * @param value the initial value to store, not null - * @throws NullPointerException if the object is null - */ - public MutableFloat(Number value) { - super(); - this.value = value.floatValue(); - } - - /** - * Constructs a new MutableFloat parsing the given string. - * - * @param value the string to parse, not null - * @throws NumberFormatException if the string cannot be parsed into a float - * @since 2.5 - */ - public MutableFloat(String value) throws NumberFormatException { - super(); - this.value = Float.parseFloat(value); - } - - //----------------------------------------------------------------------- - /** - * Gets the value as a Float instance. - * - * @return the value as a Float, never null - */ - public Float getValue() { - return Float.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(float value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - public void setValue(Number value) { - this.value = value.floatValue(); - } - - //----------------------------------------------------------------------- - /** - * Checks whether the float value is the special NaN value. - * - * @return true if NaN - */ - public boolean isNaN() { - return Float.isNaN(value); - } - - /** - * Checks whether the float value is infinite. - * - * @return true if infinite - */ - public boolean isInfinite() { - return Float.isInfinite(value); - } - - //----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since Commons Lang 2.2 - */ - public void increment() { - value++; - } - - /** - * Decrements the value. - * - * @since Commons Lang 2.2 - */ - public void decrement() { - value--; - } - - //----------------------------------------------------------------------- - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @since Commons Lang 2.2 - */ - public void add(float operand) { - this.value += operand; - } - - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void add(Number operand) { - this.value += operand.floatValue(); - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract - * @since Commons Lang 2.2 - */ - public void subtract(float operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void subtract(Number operand) { - this.value -= operand.floatValue(); - } - - //----------------------------------------------------------------------- - // shortValue and byteValue rely on Number implementation - /** - * Returns the value of this MutableFloat as an int. - * - * @return the numeric value represented by this object after conversion to type int. - */ - @Override - public int intValue() { - return (int) value; - } - - /** - * Returns the value of this MutableFloat as a long. - * - * @return the numeric value represented by this object after conversion to type long. - */ - @Override - public long longValue() { - return (long) value; - } - - /** - * Returns the value of this MutableFloat as a float. - * - * @return the numeric value represented by this object after conversion to type float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value of this MutableFloat as a double. - * - * @return the numeric value represented by this object after conversion to type double. - */ - @Override - public double doubleValue() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Float. - * - * @return a Float instance containing the value from this mutable, never null - */ - public Float toFloat() { - return Float.valueOf(floatValue()); - } - - //----------------------------------------------------------------------- - /** - * Compares this object against some other object. The result is true if and only if the argument is - * not null and is a Float object that represents a float that has the - * identical bit pattern to the bit pattern of the float represented by this object. For this - * purpose, two float values are considered to be the same if and only if the method - * {@link Float#floatToIntBits(float)}returns the same int value when applied to each. - *

- * Note that in most cases, for two instances of class Float,f1 and f2, - * the value of f1.equals(f2) is true if and only if

- * - *
-     *   f1.floatValue() == f2.floatValue()
-     * 
- * - *
- *

- * also has the value true. However, there are two exceptions: - *

    - *
  • If f1 and f2 both represent Float.NaN, then the - * equals method returns true, even though Float.NaN==Float.NaN has - * the value false. - *
  • If f1 represents +0.0f while f2 represents -0.0f, - * or vice versa, the equal test has the value false, even though - * 0.0f==-0.0f has the value true. - *
- * This definition allows hashtables to operate properly. - * - * @param obj the object to compare with, null returns false - * @return true if the objects are the same; false otherwise. - * @see java.lang.Float#floatToIntBits(float) - */ - @Override - public boolean equals(Object obj) { - return obj instanceof MutableFloat - && Float.floatToIntBits(((MutableFloat) obj).value) == Float.floatToIntBits(value); - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return Float.floatToIntBits(value); - } - - //----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - public int compareTo(MutableFloat other) { - float anotherVal = other.value; - return Float.compare(value, anotherVal); - } - - //----------------------------------------------------------------------- - /** - * Returns the String value of this mutable. - * - * @return the mutable value as a string - */ - @Override - public String toString() { - return String.valueOf(value); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableLong.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableLong.java deleted file mode 100644 index 5365c3e4..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableLong.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.mutable; - -/** - * A mutable long wrapper. - *

- * Note that as MutableLong does not extend Long, it is not treated by String.format as a Long parameter. - * - * @see Long - * @since 2.1 - * @version $Id: MutableLong.java 1160571 2011-08-23 07:36:08Z bayard $ - */ -public class MutableLong extends Number implements Comparable, Mutable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 62986528375L; - - /** The mutable value. */ - private long value; - - /** - * Constructs a new MutableLong with the default value of zero. - */ - public MutableLong() { - super(); - } - - /** - * Constructs a new MutableLong with the specified value. - * - * @param value the initial value to store - */ - public MutableLong(long value) { - super(); - this.value = value; - } - - /** - * Constructs a new MutableLong with the specified value. - * - * @param value the initial value to store, not null - * @throws NullPointerException if the object is null - */ - public MutableLong(Number value) { - super(); - this.value = value.longValue(); - } - - /** - * Constructs a new MutableLong parsing the given string. - * - * @param value the string to parse, not null - * @throws NumberFormatException if the string cannot be parsed into a long - * @since 2.5 - */ - public MutableLong(String value) throws NumberFormatException { - super(); - this.value = Long.parseLong(value); - } - - //----------------------------------------------------------------------- - /** - * Gets the value as a Long instance. - * - * @return the value as a Long, never null - */ - public Long getValue() { - return Long.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(long value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - public void setValue(Number value) { - this.value = value.longValue(); - } - - //----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since Commons Lang 2.2 - */ - public void increment() { - value++; - } - - /** - * Decrements the value. - * - * @since Commons Lang 2.2 - */ - public void decrement() { - value--; - } - - //----------------------------------------------------------------------- - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @since Commons Lang 2.2 - */ - public void add(long operand) { - this.value += operand; - } - - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void add(Number operand) { - this.value += operand.longValue(); - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since Commons Lang 2.2 - */ - public void subtract(long operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void subtract(Number operand) { - this.value -= operand.longValue(); - } - - //----------------------------------------------------------------------- - // shortValue and byteValue rely on Number implementation - /** - * Returns the value of this MutableLong as an int. - * - * @return the numeric value represented by this object after conversion to type int. - */ - @Override - public int intValue() { - return (int) value; - } - - /** - * Returns the value of this MutableLong as a long. - * - * @return the numeric value represented by this object after conversion to type long. - */ - @Override - public long longValue() { - return value; - } - - /** - * Returns the value of this MutableLong as a float. - * - * @return the numeric value represented by this object after conversion to type float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value of this MutableLong as a double. - * - * @return the numeric value represented by this object after conversion to type double. - */ - @Override - public double doubleValue() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Long. - * - * @return a Long instance containing the value from this mutable, never null - */ - public Long toLong() { - return Long.valueOf(longValue()); - } - - //----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is true if and only if the argument - * is not null and is a MutableLong object that contains the same long - * value as this object. - * - * @param obj the object to compare with, null returns false - * @return true if the objects are the same; false otherwise. - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof MutableLong) { - return value == ((MutableLong) obj).longValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return (int) (value ^ (value >>> 32)); - } - - //----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - public int compareTo(MutableLong other) { - long anotherVal = other.value; - return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1); - } - - //----------------------------------------------------------------------- - /** - * Returns the String value of this mutable. - * - * @return the mutable value as a string - */ - @Override - public String toString() { - return String.valueOf(value); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableObject.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableObject.java deleted file mode 100644 index 4f903592..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableObject.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package external.org.apache.commons.lang3.mutable; - -import java.io.Serializable; - -/** - * A mutable Object wrapper. - * - * @since 2.1 - * @version $Id: MutableObject.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class MutableObject implements Mutable, Serializable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 86241875189L; - - /** The mutable value. */ - private T value; - - /** - * Constructs a new MutableObject with the default value of null. - */ - public MutableObject() { - super(); - } - - /** - * Constructs a new MutableObject with the specified value. - * - * @param value the initial value to store - */ - public MutableObject(T value) { - super(); - this.value = value; - } - - //----------------------------------------------------------------------- - /** - * Gets the value. - * - * @return the value, may be null - */ - public T getValue() { - return this.value; - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(T value) { - this.value = value; - } - - //----------------------------------------------------------------------- - /** - *

- * Compares this object against the specified object. The result is true if and only if the argument - * is not null and is a MutableObject object that contains the same T - * value as this object. - *

- * - * @param obj the object to compare with, null returns false - * @return true if the objects are the same; - * true if the objects have equivalent value fields; - * false otherwise. - */ - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (this.getClass() == obj.getClass()) { - MutableObject that = (MutableObject) obj; - return this.value.equals(that.value); - } else { - return false; - } - } - - /** - * Returns the value's hash code or 0 if the value is null. - * - * @return the value's hash code or 0 if the value is null. - */ - @Override - public int hashCode() { - return value == null ? 0 : value.hashCode(); - } - - //----------------------------------------------------------------------- - /** - * Returns the String value of this mutable. - * - * @return the mutable value as a string - */ - @Override - public String toString() { - return value == null ? "null" : value.toString(); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableShort.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableShort.java deleted file mode 100644 index b737b96e..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/mutable/MutableShort.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.mutable; - -/** - * A mutable short wrapper. - *

- * Note that as MutableShort does not extend Short, it is not treated by String.format as a Short parameter. - * - * @see Short - * @since 2.1 - * @version $Id: MutableShort.java 1160571 2011-08-23 07:36:08Z bayard $ - */ -public class MutableShort extends Number implements Comparable, Mutable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = -2135791679L; - - /** The mutable value. */ - private short value; - - /** - * Constructs a new MutableShort with the default value of zero. - */ - public MutableShort() { - super(); - } - - /** - * Constructs a new MutableShort with the specified value. - * - * @param value the initial value to store - */ - public MutableShort(short value) { - super(); - this.value = value; - } - - /** - * Constructs a new MutableShort with the specified value. - * - * @param value the initial value to store, not null - * @throws NullPointerException if the object is null - */ - public MutableShort(Number value) { - super(); - this.value = value.shortValue(); - } - - /** - * Constructs a new MutableShort parsing the given string. - * - * @param value the string to parse, not null - * @throws NumberFormatException if the string cannot be parsed into a short - * @since 2.5 - */ - public MutableShort(String value) throws NumberFormatException { - super(); - this.value = Short.parseShort(value); - } - - //----------------------------------------------------------------------- - /** - * Gets the value as a Short instance. - * - * @return the value as a Short, never null - */ - public Short getValue() { - return Short.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(short value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - public void setValue(Number value) { - this.value = value.shortValue(); - } - - //----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since Commons Lang 2.2 - */ - public void increment() { - value++; - } - - /** - * Decrements the value. - * - * @since Commons Lang 2.2 - */ - public void decrement() { - value--; - } - - //----------------------------------------------------------------------- - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @since Commons Lang 2.2 - */ - public void add(short operand) { - this.value += operand; - } - - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void add(Number operand) { - this.value += operand.shortValue(); - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since Commons Lang 2.2 - */ - public void subtract(short operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since Commons Lang 2.2 - */ - public void subtract(Number operand) { - this.value -= operand.shortValue(); - } - - //----------------------------------------------------------------------- - // byteValue relies on Number implementation - /** - * Returns the value of this MutableShort as a short. - * - * @return the numeric value represented by this object after conversion to type short. - */ - @Override - public short shortValue() { - return value; - } - - /** - * Returns the value of this MutableShort as an int. - * - * @return the numeric value represented by this object after conversion to type int. - */ - @Override - public int intValue() { - return value; - } - - /** - * Returns the value of this MutableShort as a long. - * - * @return the numeric value represented by this object after conversion to type long. - */ - @Override - public long longValue() { - return value; - } - - /** - * Returns the value of this MutableShort as a float. - * - * @return the numeric value represented by this object after conversion to type float. - */ - @Override - public float floatValue() { - return value; - } - - /** - * Returns the value of this MutableShort as a double. - * - * @return the numeric value represented by this object after conversion to type double. - */ - @Override - public double doubleValue() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Short. - * - * @return a Short instance containing the value from this mutable, never null - */ - public Short toShort() { - return Short.valueOf(shortValue()); - } - - //----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is true if and only if the argument - * is not null and is a MutableShort object that contains the same short - * value as this object. - * - * @param obj the object to compare with, null returns false - * @return true if the objects are the same; false otherwise. - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof MutableShort) { - return value == ((MutableShort) obj).shortValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return value; - } - - //----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - public int compareTo(MutableShort other) { - short anotherVal = other.value; - return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1); - } - - //----------------------------------------------------------------------- - /** - * Returns the String value of this mutable. - * - * @return the mutable value as a string - */ - @Override - public String toString() { - return String.valueOf(value); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/ConstructorUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/ConstructorUtils.java deleted file mode 100644 index 539156e4..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/ConstructorUtils.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.reflect; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; - -import external.org.apache.commons.lang3.ArrayUtils; -import external.org.apache.commons.lang3.ClassUtils; - -/** - *

Utility reflection methods focused on constructors, modeled after - * {@link MethodUtils}.

- * - *

Known Limitations

Accessing Public Constructors In A Default - * Access Superclass

There is an issue when invoking public constructors - * contained in a default access superclass. Reflection locates these - * constructors fine and correctly assigns them as public. However, an - * IllegalAccessException is thrown if the constructors is - * invoked.

- * - *

ConstructorUtils contains a workaround for this situation. It - * will attempt to call setAccessible on this constructor. If this - * call succeeds, then the method can be invoked as normal. This call will only - * succeed when the application has sufficient security privileges. If this call - * fails then a warning will be logged and the method may fail.

- * - * @since 2.5 - * @version $Id: ConstructorUtils.java 1144010 2011-07-07 20:02:10Z joehni $ - */ -public class ConstructorUtils { - - /** - *

ConstructorUtils instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * ConstructorUtils.invokeConstructor(cls, args).

- * - *

This constructor is public to permit tools that require a JavaBean - * instance to operate.

- */ - public ConstructorUtils() { - super(); - } - - /** - *

Returns a new instance of the specified class inferring the right constructor - * from the types of the arguments.

- * - *

This locates and calls a constructor. - * The constructor signature must match the argument types by assignment compatibility.

- * - * @param the type to be constructed - * @param cls the class to be constructed, not null - * @param args the array of arguments, null treated as empty - * @return new instance of cls, not null - * - * @throws NoSuchMethodException if a matching constructor cannot be found - * @throws IllegalAccessException if invocation is not permitted by security - * @throws InvocationTargetException if an error occurs on invocation - * @throws InstantiationException if an error occurs on instantiation - * @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) - */ - public static T invokeConstructor(Class cls, Object... args) - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, - InstantiationException { - if (args == null) { - args = ArrayUtils.EMPTY_OBJECT_ARRAY; - } - Class parameterTypes[] = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - parameterTypes[i] = args[i].getClass(); - } - return invokeConstructor(cls, args, parameterTypes); - } - - /** - *

Returns a new instance of the specified class choosing the right constructor - * from the list of parameter types.

- * - *

This locates and calls a constructor. - * The constructor signature must match the parameter types by assignment compatibility.

- * - * @param the type to be constructed - * @param cls the class to be constructed, not null - * @param args the array of arguments, null treated as empty - * @param parameterTypes the array of parameter types, null treated as empty - * @return new instance of cls, not null - * - * @throws NoSuchMethodException if a matching constructor cannot be found - * @throws IllegalAccessException if invocation is not permitted by security - * @throws InvocationTargetException if an error occurs on invocation - * @throws InstantiationException if an error occurs on instantiation - * @see Constructor#newInstance - */ - public static T invokeConstructor(Class cls, Object[] args, Class[] parameterTypes) - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, - InstantiationException { - if (parameterTypes == null) { - parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; - } - if (args == null) { - args = ArrayUtils.EMPTY_OBJECT_ARRAY; - } - Constructor ctor = getMatchingAccessibleConstructor(cls, parameterTypes); - if (ctor == null) { - throw new NoSuchMethodException( - "No such accessible constructor on object: " + cls.getName()); - } - return ctor.newInstance(args); - } - - /** - *

Returns a new instance of the specified class inferring the right constructor - * from the types of the arguments.

- * - *

This locates and calls a constructor. - * The constructor signature must match the argument types exactly.

- * - * @param the type to be constructed - * @param cls the class to be constructed, not null - * @param args the array of arguments, null treated as empty - * @return new instance of cls, not null - * - * @throws NoSuchMethodException if a matching constructor cannot be found - * @throws IllegalAccessException if invocation is not permitted by security - * @throws InvocationTargetException if an error occurs on invocation - * @throws InstantiationException if an error occurs on instantiation - * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) - */ - public static T invokeExactConstructor(Class cls, Object... args) - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, - InstantiationException { - if (args == null) { - args = ArrayUtils.EMPTY_OBJECT_ARRAY; - } - int arguments = args.length; - Class parameterTypes[] = new Class[arguments]; - for (int i = 0; i < arguments; i++) { - parameterTypes[i] = args[i].getClass(); - } - return invokeExactConstructor(cls, args, parameterTypes); - } - - /** - *

Returns a new instance of the specified class choosing the right constructor - * from the list of parameter types.

- * - *

This locates and calls a constructor. - * The constructor signature must match the parameter types exactly.

- * - * @param the type to be constructed - * @param cls the class to be constructed, not null - * @param args the array of arguments, null treated as empty - * @param parameterTypes the array of parameter types, null treated as empty - * @return new instance of cls, not null - * - * @throws NoSuchMethodException if a matching constructor cannot be found - * @throws IllegalAccessException if invocation is not permitted by security - * @throws InvocationTargetException if an error occurs on invocation - * @throws InstantiationException if an error occurs on instantiation - * @see Constructor#newInstance - */ - public static T invokeExactConstructor(Class cls, Object[] args, - Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { - if (args == null) { - args = ArrayUtils.EMPTY_OBJECT_ARRAY; - } - if (parameterTypes == null) { - parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; - } - Constructor ctor = getAccessibleConstructor(cls, parameterTypes); - if (ctor == null) { - throw new NoSuchMethodException( - "No such accessible constructor on object: "+ cls.getName()); - } - return ctor.newInstance(args); - } - - //----------------------------------------------------------------------- - /** - *

Finds a constructor given a class and signature, checking accessibility.

- * - *

This finds the constructor and ensures that it is accessible. - * The constructor signature must match the parameter types exactly.

- * - * @param the constructor type - * @param cls the class to find a constructor for, not null - * @param parameterTypes the array of parameter types, null treated as empty - * @return the constructor, null if no matching accessible constructor found - * @see Class#getConstructor - * @see #getAccessibleConstructor(java.lang.reflect.Constructor) - */ - public static Constructor getAccessibleConstructor(Class cls, - Class... parameterTypes) { - try { - return getAccessibleConstructor(cls.getConstructor(parameterTypes)); - } catch (NoSuchMethodException e) { - return null; - } - } - - /** - *

Checks if the specified constructor is accessible.

- * - *

This simply ensures that the constructor is accessible.

- * - * @param the constructor type - * @param ctor the prototype constructor object, not null - * @return the constructor, null if no matching accessible constructor found - * @see java.lang.SecurityManager - */ - public static Constructor getAccessibleConstructor(Constructor ctor) { - return MemberUtils.isAccessible(ctor) - && Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) ? ctor : null; - } - - /** - *

Finds an accessible constructor with compatible parameters.

- * - *

This checks all the constructor and finds one with compatible parameters - * This requires that every parameter is assignable from the given parameter types. - * This is a more flexible search than the normal exact matching algorithm.

- * - *

First it checks if there is a constructor matching the exact signature. - * If not then all the constructors of the class are checked to see if their - * signatures are assignment compatible with the parameter types. - * The first assignment compatible matching constructor is returned.

- * - * @param the constructor type - * @param cls the class to find a constructor for, not null - * @param parameterTypes find method with compatible parameters - * @return the constructor, null if no matching accessible constructor found - */ - public static Constructor getMatchingAccessibleConstructor(Class cls, - Class... parameterTypes) { - // see if we can find the constructor directly - // most of the time this works and it's much faster - try { - Constructor ctor = cls.getConstructor(parameterTypes); - MemberUtils.setAccessibleWorkaround(ctor); - return ctor; - } catch (NoSuchMethodException e) { // NOPMD - Swallow - } - Constructor result = null; - /* - * (1) Class.getConstructors() is documented to return Constructor so as - * long as the array is not subsequently modified, everything's fine. - */ - Constructor[] ctors = cls.getConstructors(); - - // return best match: - for (Constructor ctor : ctors) { - // compare parameters - if (ClassUtils.isAssignable(parameterTypes, ctor.getParameterTypes(), true)) { - // get accessible version of constructor - ctor = getAccessibleConstructor(ctor); - if (ctor != null) { - MemberUtils.setAccessibleWorkaround(ctor); - if (result == null - || MemberUtils.compareParameterTypes(ctor.getParameterTypes(), result - .getParameterTypes(), parameterTypes) < 0) { - // temporary variable for annotation, see comment above (1) - @SuppressWarnings("unchecked") - Constructor constructor = (Constructor)ctor; - result = constructor; - } - } - } - } - return result; - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/FieldUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/FieldUtils.java deleted file mode 100644 index 49141afe..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/FieldUtils.java +++ /dev/null @@ -1,595 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.reflect; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; - -import external.org.apache.commons.lang3.ClassUtils; - -/** - * Utilities for working with fields by reflection. Adapted and refactored - * from the dormant [reflect] Commons sandbox component. - *

- * The ability is provided to break the scoping restrictions coded by the - * programmer. This can allow fields to be changed that shouldn't be. This - * facility should be used with care. - * - * @since 2.5 - * @version $Id: FieldUtils.java 1144929 2011-07-10 18:26:16Z ggregory $ - */ -public class FieldUtils { - - /** - * FieldUtils instances should NOT be constructed in standard programming. - *

- * This constructor is public to permit tools that require a JavaBean instance - * to operate. - */ - public FieldUtils() { - super(); - } - - /** - * Gets an accessible Field by name respecting scope. - * Superclasses/interfaces will be considered. - * - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @return the Field object - * @throws IllegalArgumentException if the class or field name is null - */ - public static Field getField(Class cls, String fieldName) { - Field field = getField(cls, fieldName, false); - MemberUtils.setAccessibleWorkaround(field); - return field; - } - - /** - * Gets an accessible Field by name breaking scope - * if requested. Superclasses/interfaces will be considered. - * - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @return the Field object - * @throws IllegalArgumentException if the class or field name is null - */ - public static Field getField(final Class cls, String fieldName, boolean forceAccess) { - if (cls == null) { - throw new IllegalArgumentException("The class must not be null"); - } - if (fieldName == null) { - throw new IllegalArgumentException("The field name must not be null"); - } - // Sun Java 1.3 has a bugged implementation of getField hence we write the - // code ourselves - - // getField() will return the Field object with the declaring class - // set correctly to the class that declares the field. Thus requesting the - // field on a subclass will return the field from the superclass. - // - // priority order for lookup: - // searchclass private/protected/package/public - // superclass protected/package/public - // private/different package blocks access to further superclasses - // implementedinterface public - - // check up the superclass hierarchy - for (Class acls = cls; acls != null; acls = acls.getSuperclass()) { - try { - Field field = acls.getDeclaredField(fieldName); - // getDeclaredField checks for non-public scopes as well - // and it returns accurate results - if (!Modifier.isPublic(field.getModifiers())) { - if (forceAccess) { - field.setAccessible(true); - } else { - continue; - } - } - return field; - } catch (NoSuchFieldException ex) { // NOPMD - // ignore - } - } - // check the public interface case. This must be manually searched for - // incase there is a public supersuperclass field hidden by a private/package - // superclass field. - Field match = null; - for (Class class1 : ClassUtils.getAllInterfaces(cls)) { - try { - Field test = ((Class) class1).getField(fieldName); - if (match != null) { - throw new IllegalArgumentException("Reference to field " + fieldName + " is ambiguous relative to " + cls - + "; a matching field exists on two or more implemented interfaces."); - } - match = test; - } catch (NoSuchFieldException ex) { // NOPMD - // ignore - } - } - return match; - } - - /** - * Gets an accessible Field by name respecting scope. - * Only the specified class will be considered. - * - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @return the Field object - * @throws IllegalArgumentException if the class or field name is null - */ - public static Field getDeclaredField(Class cls, String fieldName) { - return getDeclaredField(cls, fieldName, false); - } - - /** - * Gets an accessible Field by name breaking scope - * if requested. Only the specified class will be considered. - * - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only match public fields. - * @return the Field object - * @throws IllegalArgumentException if the class or field name is null - */ - public static Field getDeclaredField(Class cls, String fieldName, boolean forceAccess) { - if (cls == null) { - throw new IllegalArgumentException("The class must not be null"); - } - if (fieldName == null) { - throw new IllegalArgumentException("The field name must not be null"); - } - try { - // only consider the specified class by using getDeclaredField() - Field field = cls.getDeclaredField(fieldName); - if (!MemberUtils.isAccessible(field)) { - if (forceAccess) { - field.setAccessible(true); - } else { - return null; - } - } - return field; - } catch (NoSuchFieldException e) { // NOPMD - // ignore - } - return null; - } - - /** - * Reads an accessible static Field. - * @param field to read - * @return the field value - * @throws IllegalArgumentException if the field is null or not static - * @throws IllegalAccessException if the field is not accessible - */ - public static Object readStaticField(Field field) throws IllegalAccessException { - return readStaticField(field, false); - } - - /** - * Reads a static Field. - * @param field to read - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. - * @return the field value - * @throws IllegalArgumentException if the field is null or not static - * @throws IllegalAccessException if the field is not made accessible - */ - public static Object readStaticField(Field field, boolean forceAccess) throws IllegalAccessException { - if (field == null) { - throw new IllegalArgumentException("The field must not be null"); - } - if (!Modifier.isStatic(field.getModifiers())) { - throw new IllegalArgumentException("The field '" + field.getName() + "' is not static"); - } - return readField(field, (Object) null, forceAccess); - } - - /** - * Reads the named public static field. Superclasses will be considered. - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @return the value of the field - * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found - * @throws IllegalAccessException if the field is not accessible - */ - public static Object readStaticField(Class cls, String fieldName) throws IllegalAccessException { - return readStaticField(cls, fieldName, false); - } - - /** - * Reads the named static field. Superclasses will be considered. - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @return the Field object - * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found - * @throws IllegalAccessException if the field is not made accessible - */ - public static Object readStaticField(Class cls, String fieldName, boolean forceAccess) - throws IllegalAccessException { - Field field = getField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls); - } - //already forced access above, don't repeat it here: - return readStaticField(field, false); - } - - /** - * Gets a static Field value by name. The field must be public. - * Only the specified class will be considered. - * - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @return the value of the field - * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found - * @throws IllegalAccessException if the field is not accessible - */ - public static Object readDeclaredStaticField(Class cls, String fieldName) throws IllegalAccessException { - return readDeclaredStaticField(cls, fieldName, false); - } - - /** - * Gets a static Field value by name. Only the specified class will - * be considered. - * - * @param cls the class to reflect, must not be null - * @param fieldName the field name to obtain - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @return the Field object - * @throws IllegalArgumentException if the class is null, the field name is null or if the field could not be found - * @throws IllegalAccessException if the field is not made accessible - */ - public static Object readDeclaredStaticField(Class cls, String fieldName, boolean forceAccess) - throws IllegalAccessException { - Field field = getDeclaredField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); - } - //already forced access above, don't repeat it here: - return readStaticField(field, false); - } - - /** - * Reads an accessible Field. - * @param field the field to use - * @param target the object to call on, may be null for static fields - * @return the field value - * @throws IllegalArgumentException if the field is null - * @throws IllegalAccessException if the field is not accessible - */ - public static Object readField(Field field, Object target) throws IllegalAccessException { - return readField(field, target, false); - } - - /** - * Reads a Field. - * @param field the field to use - * @param target the object to call on, may be null for static fields - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. - * @return the field value - * @throws IllegalArgumentException if the field is null - * @throws IllegalAccessException if the field is not made accessible - */ - public static Object readField(Field field, Object target, boolean forceAccess) throws IllegalAccessException { - if (field == null) { - throw new IllegalArgumentException("The field must not be null"); - } - if (forceAccess && !field.isAccessible()) { - field.setAccessible(true); - } else { - MemberUtils.setAccessibleWorkaround(field); - } - return field.get(target); - } - - /** - * Reads the named public field. Superclasses will be considered. - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @return the value of the field - * @throws IllegalArgumentException if the class or field name is null - * @throws IllegalAccessException if the named field is not public - */ - public static Object readField(Object target, String fieldName) throws IllegalAccessException { - return readField(target, fieldName, false); - } - - /** - * Reads the named field. Superclasses will be considered. - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @return the field value - * @throws IllegalArgumentException if the class or field name is null - * @throws IllegalAccessException if the named field is not made accessible - */ - public static Object readField(Object target, String fieldName, boolean forceAccess) throws IllegalAccessException { - if (target == null) { - throw new IllegalArgumentException("target object must not be null"); - } - Class cls = target.getClass(); - Field field = getField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls); - } - //already forced access above, don't repeat it here: - return readField(field, target); - } - - /** - * Reads the named public field. Only the class of the specified object will be considered. - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @return the value of the field - * @throws IllegalArgumentException if the class or field name is null - * @throws IllegalAccessException if the named field is not public - */ - public static Object readDeclaredField(Object target, String fieldName) throws IllegalAccessException { - return readDeclaredField(target, fieldName, false); - } - - /** - * Gets a Field value by name. Only the class of the specified - * object will be considered. - * - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @return the Field object - * @throws IllegalArgumentException if target or fieldName is null - * @throws IllegalAccessException if the field is not made accessible - */ - public static Object readDeclaredField(Object target, String fieldName, boolean forceAccess) - throws IllegalAccessException { - if (target == null) { - throw new IllegalArgumentException("target object must not be null"); - } - Class cls = target.getClass(); - Field field = getDeclaredField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); - } - //already forced access above, don't repeat it here: - return readField(field, target); - } - - /** - * Writes a public static Field. - * @param field to write - * @param value to set - * @throws IllegalArgumentException if the field is null or not static - * @throws IllegalAccessException if the field is not public or is final - */ - public static void writeStaticField(Field field, Object value) throws IllegalAccessException { - writeStaticField(field, value, false); - } - - /** - * Writes a static Field. - * @param field to write - * @param value to set - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @throws IllegalArgumentException if the field is null or not static - * @throws IllegalAccessException if the field is not made accessible or is final - */ - public static void writeStaticField(Field field, Object value, boolean forceAccess) throws IllegalAccessException { - if (field == null) { - throw new IllegalArgumentException("The field must not be null"); - } - if (!Modifier.isStatic(field.getModifiers())) { - throw new IllegalArgumentException("The field '" + field.getName() + "' is not static"); - } - writeField(field, (Object) null, value, forceAccess); - } - - /** - * Writes a named public static Field. Superclasses will be considered. - * @param cls Class on which the Field is to be found - * @param fieldName to write - * @param value to set - * @throws IllegalArgumentException if the field cannot be located or is not static - * @throws IllegalAccessException if the field is not public or is final - */ - public static void writeStaticField(Class cls, String fieldName, Object value) throws IllegalAccessException { - writeStaticField(cls, fieldName, value, false); - } - - /** - * Writes a named static Field. Superclasses will be considered. - * @param cls Class on which the Field is to be found - * @param fieldName to write - * @param value to set - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @throws IllegalArgumentException if the field cannot be located or is not static - * @throws IllegalAccessException if the field is not made accessible or is final - */ - public static void writeStaticField(Class cls, String fieldName, Object value, boolean forceAccess) - throws IllegalAccessException { - Field field = getField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls); - } - //already forced access above, don't repeat it here: - writeStaticField(field, value); - } - - /** - * Writes a named public static Field. Only the specified class will be considered. - * @param cls Class on which the Field is to be found - * @param fieldName to write - * @param value to set - * @throws IllegalArgumentException if the field cannot be located or is not static - * @throws IllegalAccessException if the field is not public or is final - */ - public static void writeDeclaredStaticField(Class cls, String fieldName, Object value) - throws IllegalAccessException { - writeDeclaredStaticField(cls, fieldName, value, false); - } - - /** - * Writes a named static Field. Only the specified class will be considered. - * @param cls Class on which the Field is to be found - * @param fieldName to write - * @param value to set - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @throws IllegalArgumentException if the field cannot be located or is not static - * @throws IllegalAccessException if the field is not made accessible or is final - */ - public static void writeDeclaredStaticField(Class cls, String fieldName, Object value, boolean forceAccess) - throws IllegalAccessException { - Field field = getDeclaredField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); - } - //already forced access above, don't repeat it here: - writeField(field, (Object) null, value); - } - - /** - * Writes an accessible field. - * @param field to write - * @param target the object to call on, may be null for static fields - * @param value to set - * @throws IllegalArgumentException if the field is null - * @throws IllegalAccessException if the field is not accessible or is final - */ - public static void writeField(Field field, Object target, Object value) throws IllegalAccessException { - writeField(field, target, value, false); - } - - /** - * Writes a field. - * @param field to write - * @param target the object to call on, may be null for static fields - * @param value to set - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @throws IllegalArgumentException if the field is null - * @throws IllegalAccessException if the field is not made accessible or is final - */ - public static void writeField(Field field, Object target, Object value, boolean forceAccess) - throws IllegalAccessException { - if (field == null) { - throw new IllegalArgumentException("The field must not be null"); - } - if (forceAccess && !field.isAccessible()) { - field.setAccessible(true); - } else { - MemberUtils.setAccessibleWorkaround(field); - } - field.set(target, value); - } - - /** - * Writes a public field. Superclasses will be considered. - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @param value to set - * @throws IllegalArgumentException if target or fieldName is null - * @throws IllegalAccessException if the field is not accessible - */ - public static void writeField(Object target, String fieldName, Object value) throws IllegalAccessException { - writeField(target, fieldName, value, false); - } - - /** - * Writes a field. Superclasses will be considered. - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @param value to set - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @throws IllegalArgumentException if target or fieldName is null - * @throws IllegalAccessException if the field is not made accessible - */ - public static void writeField(Object target, String fieldName, Object value, boolean forceAccess) - throws IllegalAccessException { - if (target == null) { - throw new IllegalArgumentException("target object must not be null"); - } - Class cls = target.getClass(); - Field field = getField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); - } - //already forced access above, don't repeat it here: - writeField(field, target, value); - } - - /** - * Writes a public field. Only the specified class will be considered. - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @param value to set - * @throws IllegalArgumentException if target or fieldName is null - * @throws IllegalAccessException if the field is not made accessible - */ - public static void writeDeclaredField(Object target, String fieldName, Object value) throws IllegalAccessException { - writeDeclaredField(target, fieldName, value, false); - } - - /** - * Writes a public field. Only the specified class will be considered. - * @param target the object to reflect, must not be null - * @param fieldName the field name to obtain - * @param value to set - * @param forceAccess whether to break scope restrictions using the - * setAccessible method. False will only - * match public fields. - * @throws IllegalArgumentException if target or fieldName is null - * @throws IllegalAccessException if the field is not made accessible - */ - public static void writeDeclaredField(Object target, String fieldName, Object value, boolean forceAccess) - throws IllegalAccessException { - if (target == null) { - throw new IllegalArgumentException("target object must not be null"); - } - Class cls = target.getClass(); - Field field = getDeclaredField(cls, fieldName, forceAccess); - if (field == null) { - throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); - } - //already forced access above, don't repeat it here: - writeField(field, target, value); - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/TypeUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/TypeUtils.java deleted file mode 100644 index a96a7d22..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/reflect/TypeUtils.java +++ /dev/null @@ -1,1088 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.reflect; - -import java.lang.reflect.Array; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import external.org.apache.commons.lang3.ClassUtils; - -/** - *

Utility methods focusing on type inspection, particularly with regard to - * generics.

- * - * @since 3.0 - * @version $Id: TypeUtils.java 1144929 2011-07-10 18:26:16Z ggregory $ - */ -public class TypeUtils { - - /** - *

TypeUtils instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * TypeUtils.isAssignable(cls, toClass).

This - * constructor is public to permit tools that require a JavaBean instance to - * operate.

- */ - public TypeUtils() { - super(); - } - - /** - *

Checks if the subject type may be implicitly cast to the target type - * following the Java generics rules. If both types are {@link Class} - * objects, the method returns the result of - * {@link ClassUtils#isAssignable(Class, Class)}.

- * - * @param type the subject type to be assigned to the target type - * @param toType the target type - * @return true if type is assignable to toType. - */ - public static boolean isAssignable(Type type, Type toType) { - return isAssignable(type, toType, null); - } - - /** - *

Checks if the subject type may be implicitly cast to the target type - * following the Java generics rules.

- * - * @param type the subject type to be assigned to the target type - * @param toType the target type - * @param typeVarAssigns optional map of type variable assignments - * @return true if type is assignable to toType. - */ - private static boolean isAssignable(Type type, Type toType, - Map, Type> typeVarAssigns) { - if (toType == null || toType instanceof Class) { - return isAssignable(type, (Class) toType); - } - - if (toType instanceof ParameterizedType) { - return isAssignable(type, (ParameterizedType) toType, typeVarAssigns); - } - - if (toType instanceof GenericArrayType) { - return isAssignable(type, (GenericArrayType) toType, typeVarAssigns); - } - - if (toType instanceof WildcardType) { - return isAssignable(type, (WildcardType) toType, typeVarAssigns); - } - - // * - if (toType instanceof TypeVariable) { - return isAssignable(type, (TypeVariable) toType, typeVarAssigns); - } - // */ - - throw new IllegalStateException("found an unhandled type: " + toType); - } - - /** - *

Checks if the subject type may be implicitly cast to the target class - * following the Java generics rules.

- * - * @param type the subject type to be assigned to the target type - * @param toClass the target class - * @return true if type is assignable to toClass. - */ - private static boolean isAssignable(Type type, Class toClass) { - if (type == null) { - // consistency with ClassUtils.isAssignable() behavior - return toClass == null || !toClass.isPrimitive(); - } - - // only a null type can be assigned to null type which - // would have cause the previous to return true - if (toClass == null) { - return false; - } - - // all types are assignable to themselves - if (toClass.equals(type)) { - return true; - } - - if (type instanceof Class) { - // just comparing two classes - return ClassUtils.isAssignable((Class) type, toClass); - } - - if (type instanceof ParameterizedType) { - // only have to compare the raw type to the class - return isAssignable(getRawType((ParameterizedType) type), toClass); - } - - // * - if (type instanceof TypeVariable) { - // if any of the bounds are assignable to the class, then the - // type is assignable to the class. - for (Type bound : ((TypeVariable) type).getBounds()) { - if (isAssignable(bound, toClass)) { - return true; - } - } - - return false; - } - - // the only classes to which a generic array type can be assigned - // are class Object and array classes - if (type instanceof GenericArrayType) { - return toClass.equals(Object.class) - || toClass.isArray() - && isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass - .getComponentType()); - } - - // wildcard types are not assignable to a class (though one would think - // "? super Object" would be assignable to Object) - if (type instanceof WildcardType) { - return false; - } - - throw new IllegalStateException("found an unhandled type: " + type); - } - - /** - *

Checks if the subject type may be implicitly cast to the target - * parameterized type following the Java generics rules.

- * - * @param type the subject type to be assigned to the target type - * @param toParameterizedType the target parameterized type - * @param typeVarAssigns a map with type variables - * @return true if type is assignable to toType. - */ - private static boolean isAssignable(Type type, ParameterizedType toParameterizedType, - Map, Type> typeVarAssigns) { - if (type == null) { - return true; - } - - // only a null type can be assigned to null type which - // would have cause the previous to return true - if (toParameterizedType == null) { - return false; - } - - // all types are assignable to themselves - if (toParameterizedType.equals(type)) { - return true; - } - - // get the target type's raw type - Class toClass = getRawType(toParameterizedType); - // get the subject type's type arguments including owner type arguments - // and supertype arguments up to and including the target class. - Map, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null); - - // null means the two types are not compatible - if (fromTypeVarAssigns == null) { - return false; - } - - // compatible types, but there's no type arguments. this is equivalent - // to comparing Map< ?, ? > to Map, and raw types are always assignable - // to parameterized types. - if (fromTypeVarAssigns.isEmpty()) { - return true; - } - - // get the target type's type arguments including owner type arguments - Map, Type> toTypeVarAssigns = getTypeArguments(toParameterizedType, - toClass, typeVarAssigns); - - // now to check each type argument - for (Map.Entry, Type> entry : toTypeVarAssigns.entrySet()) { - Type toTypeArg = entry.getValue(); - Type fromTypeArg = fromTypeVarAssigns.get(entry.getKey()); - - // parameters must either be absent from the subject type, within - // the bounds of the wildcard type, or be an exact match to the - // parameters of the target type. - if (fromTypeArg != null - && !toTypeArg.equals(fromTypeArg) - && !(toTypeArg instanceof WildcardType && isAssignable(fromTypeArg, toTypeArg, - typeVarAssigns))) { - return false; - } - } - - return true; - } - - /** - *

Checks if the subject type may be implicitly cast to the target - * generic array type following the Java generics rules.

- * - * @param type the subject type to be assigned to the target type - * @param toGenericArrayType the target generic array type - * @param typeVarAssigns a map with type variables - * @return true if type is assignable to - * toGenericArrayType. - */ - private static boolean isAssignable(Type type, GenericArrayType toGenericArrayType, - Map, Type> typeVarAssigns) { - if (type == null) { - return true; - } - - // only a null type can be assigned to null type which - // would have cause the previous to return true - if (toGenericArrayType == null) { - return false; - } - - // all types are assignable to themselves - if (toGenericArrayType.equals(type)) { - return true; - } - - Type toComponentType = toGenericArrayType.getGenericComponentType(); - - if (type instanceof Class) { - Class cls = (Class) type; - - // compare the component types - return cls.isArray() - && isAssignable(cls.getComponentType(), toComponentType, typeVarAssigns); - } - - if (type instanceof GenericArrayType) { - // compare the component types - return isAssignable(((GenericArrayType) type).getGenericComponentType(), - toComponentType, typeVarAssigns); - } - - if (type instanceof WildcardType) { - // so long as one of the upper bounds is assignable, it's good - for (Type bound : getImplicitUpperBounds((WildcardType) type)) { - if (isAssignable(bound, toGenericArrayType)) { - return true; - } - } - - return false; - } - - if (type instanceof TypeVariable) { - // probably should remove the following logic and just return false. - // type variables cannot specify arrays as bounds. - for (Type bound : getImplicitBounds((TypeVariable) type)) { - if (isAssignable(bound, toGenericArrayType)) { - return true; - } - } - - return false; - } - - if (type instanceof ParameterizedType) { - // the raw type of a parameterized type is never an array or - // generic array, otherwise the declaration would look like this: - // Collection[]< ? extends String > collection; - return false; - } - - throw new IllegalStateException("found an unhandled type: " + type); - } - - /** - *

Checks if the subject type may be implicitly cast to the target - * wildcard type following the Java generics rules.

- * - * @param type the subject type to be assigned to the target type - * @param toWildcardType the target wildcard type - * @param typeVarAssigns a map with type variables - * @return true if type is assignable to - * toWildcardType. - */ - private static boolean isAssignable(Type type, WildcardType toWildcardType, - Map, Type> typeVarAssigns) { - if (type == null) { - return true; - } - - // only a null type can be assigned to null type which - // would have cause the previous to return true - if (toWildcardType == null) { - return false; - } - - // all types are assignable to themselves - if (toWildcardType.equals(type)) { - return true; - } - - Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType); - Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType); - - if (type instanceof WildcardType) { - WildcardType wildcardType = (WildcardType) type; - Type[] upperBounds = getImplicitUpperBounds(wildcardType); - Type[] lowerBounds = getImplicitLowerBounds(wildcardType); - - for (Type toBound : toUpperBounds) { - // if there are assignments for unresolved type variables, - // now's the time to substitute them. - toBound = substituteTypeVariables(toBound, typeVarAssigns); - - // each upper bound of the subject type has to be assignable to - // each - // upper bound of the target type - for (Type bound : upperBounds) { - if (!isAssignable(bound, toBound, typeVarAssigns)) { - return false; - } - } - } - - for (Type toBound : toLowerBounds) { - // if there are assignments for unresolved type variables, - // now's the time to substitute them. - toBound = substituteTypeVariables(toBound, typeVarAssigns); - - // each lower bound of the target type has to be assignable to - // each - // lower bound of the subject type - for (Type bound : lowerBounds) { - if (!isAssignable(toBound, bound, typeVarAssigns)) { - return false; - } - } - } - - return true; - } - - for (Type toBound : toUpperBounds) { - // if there are assignments for unresolved type variables, - // now's the time to substitute them. - if (!isAssignable(type, substituteTypeVariables(toBound, typeVarAssigns), - typeVarAssigns)) { - return false; - } - } - - for (Type toBound : toLowerBounds) { - // if there are assignments for unresolved type variables, - // now's the time to substitute them. - if (!isAssignable(substituteTypeVariables(toBound, typeVarAssigns), type, - typeVarAssigns)) { - return false; - } - } - - return true; - } - - /** - *

Checks if the subject type may be implicitly cast to the target type - * variable following the Java generics rules.

- * - * @param type the subject type to be assigned to the target type - * @param toTypeVariable the target type variable - * @param typeVarAssigns a map with type variables - * @return true if type is assignable to - * toTypeVariable. - */ - private static boolean isAssignable(Type type, TypeVariable toTypeVariable, - Map, Type> typeVarAssigns) { - if (type == null) { - return true; - } - - // only a null type can be assigned to null type which - // would have cause the previous to return true - if (toTypeVariable == null) { - return false; - } - - // all types are assignable to themselves - if (toTypeVariable.equals(type)) { - return true; - } - - if (type instanceof TypeVariable) { - // a type variable is assignable to another type variable, if - // and only if the former is the latter, extends the latter, or - // is otherwise a descendant of the latter. - Type[] bounds = getImplicitBounds((TypeVariable) type); - - for (Type bound : bounds) { - if (isAssignable(bound, toTypeVariable, typeVarAssigns)) { - return true; - } - } - } - - if (type instanceof Class || type instanceof ParameterizedType - || type instanceof GenericArrayType || type instanceof WildcardType) { - return false; - } - - throw new IllegalStateException("found an unhandled type: " + type); - } - - /** - *

- * - * @param type the type to be replaced - * @param typeVarAssigns the map with type variables - * @return the replaced type - * @throws IllegalArgumentException if the type cannot be substituted - */ - private static Type substituteTypeVariables(Type type, Map, Type> typeVarAssigns) { - if (type instanceof TypeVariable && typeVarAssigns != null) { - Type replacementType = typeVarAssigns.get(type); - - if (replacementType == null) { - throw new IllegalArgumentException("missing assignment type for type variable " - + type); - } - - return replacementType; - } - - return type; - } - - /** - *

Retrieves all the type arguments for this parameterized type - * including owner hierarchy arguments such as - * Outer.Inner.DeepInner . The arguments are returned in a - * {@link Map} specifying the argument type for each {@link TypeVariable}. - *

- * - * @param type specifies the subject parameterized type from which to - * harvest the parameters. - * @return a map of the type arguments to their respective type variables. - */ - public static Map, Type> getTypeArguments(ParameterizedType type) { - return getTypeArguments(type, getRawType(type), null); - } - - /** - *

Gets the type arguments of a class/interface based on a subtype. For - * instance, this method will determine that both of the parameters for the - * interface {@link Map} are {@link Object} for the subtype - * {@link java.util.Properties Properties} even though the subtype does not - * directly implement the Map interface.

This method - * returns null if type is not assignable to - * toClass. It returns an empty map if none of the classes or - * interfaces in its inheritance hierarchy specify any type arguments.

- *

A side-effect of this method is that it also retrieves the type - * arguments for the classes and interfaces that are part of the hierarchy - * between type and toClass. So with the above - * example, this method will also determine that the type arguments for - * {@link java.util.Hashtable Hashtable} are also both Object. - * In cases where the interface specified by toClass is - * (indirectly) implemented more than once (e.g. where toClass - * specifies the interface {@link java.lang.Iterable Iterable} and - * type specifies a parameterized type that implements both - * {@link java.util.Set Set} and {@link java.util.Collection Collection}), - * this method will look at the inheritance hierarchy of only one of the - * implementations/subclasses; the first interface encountered that isn't a - * subinterface to one of the others in the type to - * toClass hierarchy.

- * - * @param type the type from which to determine the type parameters of - * toClass - * @param toClass the class whose type parameters are to be determined based - * on the subtype type - * @return a map of the type assignments for the type variables in each type - * in the inheritance hierarchy from type to - * toClass inclusive. - */ - public static Map, Type> getTypeArguments(Type type, Class toClass) { - return getTypeArguments(type, toClass, null); - } - - /** - *

Return a map of the type arguments of type in the context of toClass.

- * - * @param type the type in question - * @param toClass the class - * @param subtypeVarAssigns a map with type variables - * @return the map with type arguments - */ - private static Map, Type> getTypeArguments(Type type, Class toClass, - Map, Type> subtypeVarAssigns) { - if (type instanceof Class) { - return getTypeArguments((Class) type, toClass, subtypeVarAssigns); - } - - if (type instanceof ParameterizedType) { - return getTypeArguments((ParameterizedType) type, toClass, subtypeVarAssigns); - } - - if (type instanceof GenericArrayType) { - return getTypeArguments(((GenericArrayType) type).getGenericComponentType(), toClass - .isArray() ? toClass.getComponentType() : toClass, subtypeVarAssigns); - } - - // since wildcard types are not assignable to classes, should this just - // return null? - if (type instanceof WildcardType) { - for (Type bound : getImplicitUpperBounds((WildcardType) type)) { - // find the first bound that is assignable to the target class - if (isAssignable(bound, toClass)) { - return getTypeArguments(bound, toClass, subtypeVarAssigns); - } - } - - return null; - } - - // * - if (type instanceof TypeVariable) { - for (Type bound : getImplicitBounds((TypeVariable) type)) { - // find the first bound that is assignable to the target class - if (isAssignable(bound, toClass)) { - return getTypeArguments(bound, toClass, subtypeVarAssigns); - } - } - - return null; - } - // */ - - throw new IllegalStateException("found an unhandled type: " + type); - } - - /** - *

Return a map of the type arguments of a parameterized type in the context of toClass.

- * - * @param parameterizedType the parameterized type - * @param toClass the class - * @param subtypeVarAssigns a map with type variables - * @return the map with type arguments - */ - private static Map, Type> getTypeArguments( - ParameterizedType parameterizedType, Class toClass, - Map, Type> subtypeVarAssigns) { - Class cls = getRawType(parameterizedType); - - // make sure they're assignable - if (!isAssignable(cls, toClass)) { - return null; - } - - Type ownerType = parameterizedType.getOwnerType(); - Map, Type> typeVarAssigns; - - if (ownerType instanceof ParameterizedType) { - // get the owner type arguments first - ParameterizedType parameterizedOwnerType = (ParameterizedType) ownerType; - typeVarAssigns = getTypeArguments(parameterizedOwnerType, - getRawType(parameterizedOwnerType), subtypeVarAssigns); - } else { - // no owner, prep the type variable assignments map - typeVarAssigns = subtypeVarAssigns == null ? new HashMap, Type>() - : new HashMap, Type>(subtypeVarAssigns); - } - - // get the subject parameterized type's arguments - Type[] typeArgs = parameterizedType.getActualTypeArguments(); - // and get the corresponding type variables from the raw class - TypeVariable[] typeParams = cls.getTypeParameters(); - - // map the arguments to their respective type variables - for (int i = 0; i < typeParams.length; i++) { - Type typeArg = typeArgs[i]; - typeVarAssigns.put(typeParams[i], typeVarAssigns.containsKey(typeArg) ? typeVarAssigns - .get(typeArg) : typeArg); - } - - if (toClass.equals(cls)) { - // target class has been reached. Done. - return typeVarAssigns; - } - - // walk the inheritance hierarchy until the target class is reached - return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns); - } - - /** - *

Return a map of the type arguments of a class in the context of toClass.

- * - * @param cls the class in question - * @param toClass the context class - * @param subtypeVarAssigns a map with type variables - * @return the map with type arguments - */ - private static Map, Type> getTypeArguments(Class cls, Class toClass, - Map, Type> subtypeVarAssigns) { - // make sure they're assignable - if (!isAssignable(cls, toClass)) { - return null; - } - - // can't work with primitives - if (cls.isPrimitive()) { - // both classes are primitives? - if (toClass.isPrimitive()) { - // dealing with widening here. No type arguments to be - // harvested with these two types. - return new HashMap, Type>(); - } - - // work with wrapper the wrapper class instead of the primitive - cls = ClassUtils.primitiveToWrapper(cls); - } - - // create a copy of the incoming map, or an empty one if it's null - HashMap, Type> typeVarAssigns = subtypeVarAssigns == null ? new HashMap, Type>() - : new HashMap, Type>(subtypeVarAssigns); - - // no arguments for the parameters, or target class has been reached - if (cls.getTypeParameters().length > 0 || toClass.equals(cls)) { - return typeVarAssigns; - } - - // walk the inheritance hierarchy until the target class is reached - return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns); - } - - /** - *

Tries to determine the type arguments of a class/interface based on a - * super parameterized type's type arguments. This method is the inverse of - * {@link #getTypeArguments(Type, Class)} which gets a class/interface's - * type arguments based on a subtype. It is far more limited in determining - * the type arguments for the subject class's type variables in that it can - * only determine those parameters that map from the subject {@link Class} - * object to the supertype.

Example: {@link java.util.TreeSet - * TreeSet} sets its parameter as the parameter for - * {@link java.util.NavigableSet NavigableSet}, which in turn sets the - * parameter of {@link java.util.SortedSet}, which in turn sets the - * parameter of {@link Set}, which in turn sets the parameter of - * {@link java.util.Collection}, which in turn sets the parameter of - * {@link java.lang.Iterable}. Since TreeSet's parameter maps - * (indirectly) to Iterable's parameter, it will be able to - * determine that based on the super type Iterable>>, the parameter of - * TreeSet is ? extends Map>.

- * - * @param cls the class whose type parameters are to be determined - * @param superType the super type from which cls's type - * arguments are to be determined - * @return a map of the type assignments that could be determined for the - * type variables in each type in the inheritance hierarchy from - * type to toClass inclusive. - */ - public static Map, Type> determineTypeArguments(Class cls, - ParameterizedType superType) { - Class superClass = getRawType(superType); - - // compatibility check - if (!isAssignable(cls, superClass)) { - return null; - } - - if (cls.equals(superClass)) { - return getTypeArguments(superType, superClass, null); - } - - // get the next class in the inheritance hierarchy - Type midType = getClosestParentType(cls, superClass); - - // can only be a class or a parameterized type - if (midType instanceof Class) { - return determineTypeArguments((Class) midType, superType); - } - - ParameterizedType midParameterizedType = (ParameterizedType) midType; - Class midClass = getRawType(midParameterizedType); - // get the type variables of the mid class that map to the type - // arguments of the super class - Map, Type> typeVarAssigns = determineTypeArguments(midClass, superType); - // map the arguments of the mid type to the class type variables - mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns); - - return typeVarAssigns; - } - - /** - *

Performs a mapping of type variables.

- * - * @param the generic type of the class in question - * @param cls the class in question - * @param parameterizedType the parameterized type - * @param typeVarAssigns the map to be filled - */ - private static void mapTypeVariablesToArguments(Class cls, - ParameterizedType parameterizedType, Map, Type> typeVarAssigns) { - // capture the type variables from the owner type that have assignments - Type ownerType = parameterizedType.getOwnerType(); - - if (ownerType instanceof ParameterizedType) { - // recursion to make sure the owner's owner type gets processed - mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType, typeVarAssigns); - } - - // parameterizedType is a generic interface/class (or it's in the owner - // hierarchy of said interface/class) implemented/extended by the class - // cls. Find out which type variables of cls are type arguments of - // parameterizedType: - Type[] typeArgs = parameterizedType.getActualTypeArguments(); - - // of the cls's type variables that are arguments of parameterizedType, - // find out which ones can be determined from the super type's arguments - TypeVariable[] typeVars = getRawType(parameterizedType).getTypeParameters(); - - // use List view of type parameters of cls so the contains() method can be used: - List>> typeVarList = Arrays.asList(cls - .getTypeParameters()); - - for (int i = 0; i < typeArgs.length; i++) { - TypeVariable typeVar = typeVars[i]; - Type typeArg = typeArgs[i]; - - // argument of parameterizedType is a type variable of cls - if (typeVarList.contains(typeArg) - // type variable of parameterizedType has an assignment in - // the super type. - && typeVarAssigns.containsKey(typeVar)) { - // map the assignment to the cls's type variable - typeVarAssigns.put((TypeVariable) typeArg, typeVarAssigns.get(typeVar)); - } - } - } - - /** - *

Closest parent type? Closest to what? The closest parent type to the - * super class specified by superClass.

- * - * @param cls the class in question - * @param superClass the super class - * @return the closes parent type - */ - private static Type getClosestParentType(Class cls, Class superClass) { - // only look at the interfaces if the super class is also an interface - if (superClass.isInterface()) { - // get the generic interfaces of the subject class - Type[] interfaceTypes = cls.getGenericInterfaces(); - // will hold the best generic interface match found - Type genericInterface = null; - - // find the interface closest to the super class - for (Type midType : interfaceTypes) { - Class midClass = null; - - if (midType instanceof ParameterizedType) { - midClass = getRawType((ParameterizedType) midType); - } else if (midType instanceof Class) { - midClass = (Class) midType; - } else { - throw new IllegalStateException("Unexpected generic" - + " interface type found: " + midType); - } - - // check if this interface is further up the inheritance chain - // than the previously found match - if (isAssignable(midClass, superClass) - && isAssignable(genericInterface, (Type) midClass)) { - genericInterface = midType; - } - } - - // found a match? - if (genericInterface != null) { - return genericInterface; - } - } - - // none of the interfaces were descendants of the target class, so the - // super class has to be one, instead - return cls.getGenericSuperclass(); - } - - /** - *

Checks if the given value can be assigned to the target type - * following the Java generics rules.

- * - * @param value the value to be checked - * @param type the target type - * @return true of value is an instance of type. - */ - public static boolean isInstance(Object value, Type type) { - if (type == null) { - return false; - } - - return value == null ? !(type instanceof Class) || !((Class) type).isPrimitive() - : isAssignable(value.getClass(), type, null); - } - - /** - *

This method strips out the redundant upper bound types in type - * variable types and wildcard types (or it would with wildcard types if - * multiple upper bounds were allowed).

Example: with the variable - * type declaration: - * - *

 <K extends java.util.Collection<String> &
-     * java.util.List<String>> 
- * - * since List is a subinterface of Collection, - * this method will return the bounds as if the declaration had been: - * - *
 <K extends java.util.List<String>> 
- * - *

- * - * @param bounds an array of types representing the upper bounds of either - * WildcardType or TypeVariable. - * @return an array containing the values from bounds minus the - * redundant types. - */ - public static Type[] normalizeUpperBounds(Type[] bounds) { - // don't bother if there's only one (or none) type - if (bounds.length < 2) { - return bounds; - } - - Set types = new HashSet(bounds.length); - - for (Type type1 : bounds) { - boolean subtypeFound = false; - - for (Type type2 : bounds) { - if (type1 != type2 && isAssignable(type2, type1, null)) { - subtypeFound = true; - break; - } - } - - if (!subtypeFound) { - types.add(type1); - } - } - - return types.toArray(new Type[types.size()]); - } - - /** - *

Returns an array containing the sole type of {@link Object} if - * {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it - * returns the result of TypeVariable.getBounds() passed into - * {@link #normalizeUpperBounds}.

- * - * @param typeVariable the subject type variable - * @return a non-empty array containing the bounds of the type variable. - */ - public static Type[] getImplicitBounds(TypeVariable typeVariable) { - Type[] bounds = typeVariable.getBounds(); - - return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds); - } - - /** - *

Returns an array containing the sole value of {@link Object} if - * {@link WildcardType#getUpperBounds()} returns an empty array. Otherwise, - * it returns the result of WildcardType.getUpperBounds() - * passed into {@link #normalizeUpperBounds}.

- * - * @param wildcardType the subject wildcard type - * @return a non-empty array containing the upper bounds of the wildcard - * type. - */ - public static Type[] getImplicitUpperBounds(WildcardType wildcardType) { - Type[] bounds = wildcardType.getUpperBounds(); - - return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds); - } - - /** - *

Returns an array containing a single value of null if - * {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise, - * it returns the result of WildcardType.getLowerBounds().

- * - * @param wildcardType the subject wildcard type - * @return a non-empty array containing the lower bounds of the wildcard - * type. - */ - public static Type[] getImplicitLowerBounds(WildcardType wildcardType) { - Type[] bounds = wildcardType.getLowerBounds(); - - return bounds.length == 0 ? new Type[] { null } : bounds; - } - - /** - *

Determines whether or not specified types satisfy the bounds of their - * mapped type variables. When a type parameter extends another (such as - * ), uses another as a type parameter (such as - * ), or otherwise depends on - * another type variable to be specified, the dependencies must be included - * in typeVarAssigns.

- * - * @param typeVarAssigns specifies the potential types to be assigned to the - * type variables. - * @return whether or not the types can be assigned to their respective type - * variables. - */ - public static boolean typesSatisfyVariables(Map, Type> typeVarAssigns) { - // all types must be assignable to all the bounds of the their mapped - // type variable. - for (Map.Entry, Type> entry : typeVarAssigns.entrySet()) { - TypeVariable typeVar = entry.getKey(); - Type type = entry.getValue(); - - for (Type bound : getImplicitBounds(typeVar)) { - if (!isAssignable(type, substituteTypeVariables(bound, typeVarAssigns), - typeVarAssigns)) { - return false; - } - } - } - - return true; - } - - /** - *

Transforms the passed in type to a {@code Class} object. Type-checking method of convenience.

- * - * @param parameterizedType the type to be converted - * @return the corresponding {@code Class} object - * @throws IllegalStateException if the conversion fails - */ - private static Class getRawType(ParameterizedType parameterizedType) { - Type rawType = parameterizedType.getRawType(); - - // check if raw type is a Class object - // not currently necessary, but since the return type is Type instead of - // Class, there's enough reason to believe that future versions of Java - // may return other Type implementations. And type-safety checking is - // rarely a bad idea. - if (!(rawType instanceof Class)) { - throw new IllegalStateException("Wait... What!? Type of rawType: " + rawType); - } - - return (Class) rawType; - } - - /** - *

Get the raw type of a Java type, given its context. Primarily for use - * with {@link TypeVariable}s and {@link GenericArrayType}s, or when you do - * not know the runtime type of type: if you know you have a - * {@link Class} instance, it is already raw; if you know you have a - * {@link ParameterizedType}, its raw type is only a method call away.

- * - * @param type to resolve - * @param assigningType type to be resolved against - * @return the resolved Class object or null if - * the type could not be resolved - */ - public static Class getRawType(Type type, Type assigningType) { - if (type instanceof Class) { - // it is raw, no problem - return (Class) type; - } - - if (type instanceof ParameterizedType) { - // simple enough to get the raw type of a ParameterizedType - return getRawType((ParameterizedType) type); - } - - if (type instanceof TypeVariable) { - if (assigningType == null) { - return null; - } - - // get the entity declaring this type variable - Object genericDeclaration = ((TypeVariable) type).getGenericDeclaration(); - - // can't get the raw type of a method- or constructor-declared type - // variable - if (!(genericDeclaration instanceof Class)) { - return null; - } - - // get the type arguments for the declaring class/interface based - // on the enclosing type - Map, Type> typeVarAssigns = getTypeArguments(assigningType, - (Class) genericDeclaration); - - // enclosingType has to be a subclass (or subinterface) of the - // declaring type - if (typeVarAssigns == null) { - return null; - } - - // get the argument assigned to this type variable - Type typeArgument = typeVarAssigns.get(type); - - if (typeArgument == null) { - return null; - } - - // get the argument for this type variable - return getRawType(typeArgument, assigningType); - } - - if (type instanceof GenericArrayType) { - // get raw component type - Class rawComponentType = getRawType(((GenericArrayType) type) - .getGenericComponentType(), assigningType); - - // create array type from raw component type and return its class - return Array.newInstance(rawComponentType, 0).getClass(); - } - - // (hand-waving) this is not the method you're looking for - if (type instanceof WildcardType) { - return null; - } - - throw new IllegalArgumentException("unknown type: " + type); - } - - /** - * Learn whether the specified type denotes an array type. - * @param type the type to be checked - * @return true if type is an array class or a {@link GenericArrayType}. - */ - public static boolean isArrayType(Type type) { - return type instanceof GenericArrayType || type instanceof Class && ((Class) type).isArray(); - } - - /** - * Get the array component type of type. - * @param type the type to be checked - * @return component type or null if type is not an array type - */ - public static Type getArrayComponentType(Type type) { - if (type instanceof Class) { - Class clazz = (Class) type; - return clazz.isArray() ? clazz.getComponentType() : null; - } - if (type instanceof GenericArrayType) { - return ((GenericArrayType) type).getGenericComponentType(); - } - return null; - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/CompositeFormat.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/CompositeFormat.java deleted file mode 100644 index 5c59afdf..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/CompositeFormat.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.text.FieldPosition; -import java.text.Format; -import java.text.ParseException; -import java.text.ParsePosition; - -/** - * Formats using one formatter and parses using a different formatter. An - * example of use for this would be a webapp where data is taken in one way and - * stored in a database another way. - * - * @version $Id: CompositeFormat.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class CompositeFormat extends Format { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = -4329119827877627683L; - - /** The parser to use. */ - private final Format parser; - /** The formatter to use. */ - private final Format formatter; - - /** - * Create a format that points its parseObject method to one implementation - * and its format method to another. - * - * @param parser implementation - * @param formatter implementation - */ - public CompositeFormat(Format parser, Format formatter) { - this.parser = parser; - this.formatter = formatter; - } - - /** - * Uses the formatter Format instance. - * - * @param obj the object to format - * @param toAppendTo the {@link StringBuffer} to append to - * @param pos the FieldPosition to use (or ignore). - * @return toAppendTo - * @see Format#format(Object, StringBuffer, FieldPosition) - */ - @Override - public StringBuffer format(Object obj, StringBuffer toAppendTo, - FieldPosition pos) { - return formatter.format(obj, toAppendTo, pos); - } - - /** - * Uses the parser Format instance. - * - * @param source the String source - * @param pos the ParsePosition containing the position to parse from, will - * be updated according to parsing success (index) or failure - * (error index) - * @return the parsed Object - * @see Format#parseObject(String, ParsePosition) - */ - @Override - public Object parseObject(String source, ParsePosition pos) { - return parser.parseObject(source, pos); - } - - /** - * Provides access to the parser Format implementation. - * - * @return parser Format implementation - */ - public Format getParser() { - return this.parser; - } - - /** - * Provides access to the parser Format implementation. - * - * @return formatter Format implementation - */ - public Format getFormatter() { - return this.formatter; - } - - /** - * Utility method to parse and then reformat a String. - * - * @param input String to reformat - * @return A reformatted String - * @throws ParseException thrown by parseObject(String) call - */ - public String reformat(String input) throws ParseException { - return format(parseObject(input)); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/ExtendedMessageFormat.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/ExtendedMessageFormat.java deleted file mode 100644 index 264b817a..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/ExtendedMessageFormat.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.text.Format; -import java.text.MessageFormat; -import java.text.ParsePosition; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; - -import external.org.apache.commons.lang3.ObjectUtils; -import external.org.apache.commons.lang3.Validate; - -/** - * Extends java.text.MessageFormat to allow pluggable/additional formatting - * options for embedded format elements. Client code should specify a registry - * of FormatFactory instances associated with String - * format names. This registry will be consulted when the format elements are - * parsed from the message pattern. In this way custom patterns can be specified, - * and the formats supported by java.text.MessageFormat can be overridden - * at the format and/or format style level (see MessageFormat). A "format element" - * embedded in the message pattern is specified (()? signifies optionality):
- * {argument-number(,format-name - * (,format-style)?)?} - * - *

- * format-name and format-style values are trimmed of surrounding whitespace - * in the manner of java.text.MessageFormat. If format-name denotes - * FormatFactory formatFactoryInstance in registry, a Format - * matching format-name and format-style is requested from - * formatFactoryInstance. If this is successful, the Format - * found is used for this format element. - *

- * - *

NOTICE: The various subformat mutator methods are considered unnecessary; they exist on the parent - * class to allow the type of customization which it is the job of this class to provide in - * a configurable fashion. These methods have thus been disabled and will throw - * UnsupportedOperationException if called. - *

- * - *

Limitations inherited from java.text.MessageFormat: - *

    - *
  • When using "choice" subformats, support for nested formatting instructions is limited - * to that provided by the base class.
  • - *
  • Thread-safety of Formats, including MessageFormat and thus - * ExtendedMessageFormat, is not guaranteed.
  • - *
- *

- * - * @since 2.4 - * @version $Id: ExtendedMessageFormat.java 1199983 2011-11-09 21:41:24Z ggregory $ - */ -public class ExtendedMessageFormat extends MessageFormat { - private static final long serialVersionUID = -2362048321261811743L; - private static final int HASH_SEED = 31; - - private static final String DUMMY_PATTERN = ""; - private static final String ESCAPED_QUOTE = "''"; - private static final char START_FMT = ','; - private static final char END_FE = '}'; - private static final char START_FE = '{'; - private static final char QUOTE = '\''; - - private String toPattern; - private final Map registry; - - /** - * Create a new ExtendedMessageFormat for the default locale. - * - * @param pattern the pattern to use, not null - * @throws IllegalArgumentException in case of a bad pattern. - */ - public ExtendedMessageFormat(String pattern) { - this(pattern, Locale.getDefault()); - } - - /** - * Create a new ExtendedMessageFormat. - * - * @param pattern the pattern to use, not null - * @param locale the locale to use, not null - * @throws IllegalArgumentException in case of a bad pattern. - */ - public ExtendedMessageFormat(String pattern, Locale locale) { - this(pattern, locale, null); - } - - /** - * Create a new ExtendedMessageFormat for the default locale. - * - * @param pattern the pattern to use, not null - * @param registry the registry of format factories, may be null - * @throws IllegalArgumentException in case of a bad pattern. - */ - public ExtendedMessageFormat(String pattern, Map registry) { - this(pattern, Locale.getDefault(), registry); - } - - /** - * Create a new ExtendedMessageFormat. - * - * @param pattern the pattern to use, not null - * @param locale the locale to use, not null - * @param registry the registry of format factories, may be null - * @throws IllegalArgumentException in case of a bad pattern. - */ - public ExtendedMessageFormat(String pattern, Locale locale, Map registry) { - super(DUMMY_PATTERN); - setLocale(locale); - this.registry = registry; - applyPattern(pattern); - } - - /** - * {@inheritDoc} - */ - @Override - public String toPattern() { - return toPattern; - } - - /** - * Apply the specified pattern. - * - * @param pattern String - */ - @Override - public final void applyPattern(String pattern) { - if (registry == null) { - super.applyPattern(pattern); - toPattern = super.toPattern(); - return; - } - ArrayList foundFormats = new ArrayList(); - ArrayList foundDescriptions = new ArrayList(); - StringBuilder stripCustom = new StringBuilder(pattern.length()); - - ParsePosition pos = new ParsePosition(0); - char[] c = pattern.toCharArray(); - int fmtCount = 0; - while (pos.getIndex() < pattern.length()) { - switch (c[pos.getIndex()]) { - case QUOTE: - appendQuotedString(pattern, pos, stripCustom, true); - break; - case START_FE: - fmtCount++; - seekNonWs(pattern, pos); - int start = pos.getIndex(); - int index = readArgumentIndex(pattern, next(pos)); - stripCustom.append(START_FE).append(index); - seekNonWs(pattern, pos); - Format format = null; - String formatDescription = null; - if (c[pos.getIndex()] == START_FMT) { - formatDescription = parseFormatDescription(pattern, - next(pos)); - format = getFormat(formatDescription); - if (format == null) { - stripCustom.append(START_FMT).append(formatDescription); - } - } - foundFormats.add(format); - foundDescriptions.add(format == null ? null : formatDescription); - Validate.isTrue(foundFormats.size() == fmtCount); - Validate.isTrue(foundDescriptions.size() == fmtCount); - if (c[pos.getIndex()] != END_FE) { - throw new IllegalArgumentException( - "Unreadable format element at position " + start); - } - //$FALL-THROUGH$ - default: - stripCustom.append(c[pos.getIndex()]); - next(pos); - } - } - super.applyPattern(stripCustom.toString()); - toPattern = insertFormats(super.toPattern(), foundDescriptions); - if (containsElements(foundFormats)) { - Format[] origFormats = getFormats(); - // only loop over what we know we have, as MessageFormat on Java 1.3 - // seems to provide an extra format element: - int i = 0; - for (Iterator it = foundFormats.iterator(); it.hasNext(); i++) { - Format f = it.next(); - if (f != null) { - origFormats[i] = f; - } - } - super.setFormats(origFormats); - } - } - - /** - * Throws UnsupportedOperationException - see class Javadoc for details. - * - * @param formatElementIndex format element index - * @param newFormat the new format - * @throws UnsupportedOperationException - */ - @Override - public void setFormat(int formatElementIndex, Format newFormat) { - throw new UnsupportedOperationException(); - } - - /** - * Throws UnsupportedOperationException - see class Javadoc for details. - * - * @param argumentIndex argument index - * @param newFormat the new format - * @throws UnsupportedOperationException - */ - @Override - public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) { - throw new UnsupportedOperationException(); - } - - /** - * Throws UnsupportedOperationException - see class Javadoc for details. - * - * @param newFormats new formats - * @throws UnsupportedOperationException - */ - @Override - public void setFormats(Format[] newFormats) { - throw new UnsupportedOperationException(); - } - - /** - * Throws UnsupportedOperationException - see class Javadoc for details. - * - * @param newFormats new formats - * @throws UnsupportedOperationException - */ - @Override - public void setFormatsByArgumentIndex(Format[] newFormats) { - throw new UnsupportedOperationException(); - } - - /** - * Check if this extended message format is equal to another object. - * - * @param obj the object to compare to - * @return true if this object equals the other, otherwise false - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null) { - return false; - } - if (!super.equals(obj)) { - return false; - } - if (ObjectUtils.notEqual(getClass(), obj.getClass())) { - return false; - } - ExtendedMessageFormat rhs = (ExtendedMessageFormat)obj; - if (ObjectUtils.notEqual(toPattern, rhs.toPattern)) { - return false; - } - if (ObjectUtils.notEqual(registry, rhs.registry)) { - return false; - } - return true; - } - - /** - * Return the hashcode. - * - * @return the hashcode - */ - @Override - public int hashCode() { - int result = super.hashCode(); - result = HASH_SEED * result + ObjectUtils.hashCode(registry); - result = HASH_SEED * result + ObjectUtils.hashCode(toPattern); - return result; - } - - /** - * Get a custom format from a format description. - * - * @param desc String - * @return Format - */ - private Format getFormat(String desc) { - if (registry != null) { - String name = desc; - String args = null; - int i = desc.indexOf(START_FMT); - if (i > 0) { - name = desc.substring(0, i).trim(); - args = desc.substring(i + 1).trim(); - } - FormatFactory factory = registry.get(name); - if (factory != null) { - return factory.getFormat(name, args, getLocale()); - } - } - return null; - } - - /** - * Read the argument index from the current format element - * - * @param pattern pattern to parse - * @param pos current parse position - * @return argument index - */ - private int readArgumentIndex(String pattern, ParsePosition pos) { - int start = pos.getIndex(); - seekNonWs(pattern, pos); - StringBuffer result = new StringBuffer(); - boolean error = false; - for (; !error && pos.getIndex() < pattern.length(); next(pos)) { - char c = pattern.charAt(pos.getIndex()); - if (Character.isWhitespace(c)) { - seekNonWs(pattern, pos); - c = pattern.charAt(pos.getIndex()); - if (c != START_FMT && c != END_FE) { - error = true; - continue; - } - } - if ((c == START_FMT || c == END_FE) && result.length() > 0) { - try { - return Integer.parseInt(result.toString()); - } catch (NumberFormatException e) { // NOPMD - // we've already ensured only digits, so unless something - // outlandishly large was specified we should be okay. - } - } - error = !Character.isDigit(c); - result.append(c); - } - if (error) { - throw new IllegalArgumentException( - "Invalid format argument index at position " + start + ": " - + pattern.substring(start, pos.getIndex())); - } - throw new IllegalArgumentException( - "Unterminated format element at position " + start); - } - - /** - * Parse the format component of a format element. - * - * @param pattern string to parse - * @param pos current parse position - * @return Format description String - */ - private String parseFormatDescription(String pattern, ParsePosition pos) { - int start = pos.getIndex(); - seekNonWs(pattern, pos); - int text = pos.getIndex(); - int depth = 1; - for (; pos.getIndex() < pattern.length(); next(pos)) { - switch (pattern.charAt(pos.getIndex())) { - case START_FE: - depth++; - break; - case END_FE: - depth--; - if (depth == 0) { - return pattern.substring(text, pos.getIndex()); - } - break; - case QUOTE: - getQuotedString(pattern, pos, false); - break; - } - } - throw new IllegalArgumentException( - "Unterminated format element at position " + start); - } - - /** - * Insert formats back into the pattern for toPattern() support. - * - * @param pattern source - * @param customPatterns The custom patterns to re-insert, if any - * @return full pattern - */ - private String insertFormats(String pattern, ArrayList customPatterns) { - if (!containsElements(customPatterns)) { - return pattern; - } - StringBuilder sb = new StringBuilder(pattern.length() * 2); - ParsePosition pos = new ParsePosition(0); - int fe = -1; - int depth = 0; - while (pos.getIndex() < pattern.length()) { - char c = pattern.charAt(pos.getIndex()); - switch (c) { - case QUOTE: - appendQuotedString(pattern, pos, sb, false); - break; - case START_FE: - depth++; - if (depth == 1) { - fe++; - sb.append(START_FE).append( - readArgumentIndex(pattern, next(pos))); - String customPattern = customPatterns.get(fe); - if (customPattern != null) { - sb.append(START_FMT).append(customPattern); - } - } - break; - case END_FE: - depth--; - //$FALL-THROUGH$ - default: - sb.append(c); - next(pos); - } - } - return sb.toString(); - } - - /** - * Consume whitespace from the current parse position. - * - * @param pattern String to read - * @param pos current position - */ - private void seekNonWs(String pattern, ParsePosition pos) { - int len = 0; - char[] buffer = pattern.toCharArray(); - do { - len = StrMatcher.splitMatcher().isMatch(buffer, pos.getIndex()); - pos.setIndex(pos.getIndex() + len); - } while (len > 0 && pos.getIndex() < pattern.length()); - } - - /** - * Convenience method to advance parse position by 1 - * - * @param pos ParsePosition - * @return pos - */ - private ParsePosition next(ParsePosition pos) { - pos.setIndex(pos.getIndex() + 1); - return pos; - } - - /** - * Consume a quoted string, adding it to appendTo if - * specified. - * - * @param pattern pattern to parse - * @param pos current parse position - * @param appendTo optional StringBuffer to append - * @param escapingOn whether to process escaped quotes - * @return appendTo - */ - private StringBuilder appendQuotedString(String pattern, ParsePosition pos, - StringBuilder appendTo, boolean escapingOn) { - int start = pos.getIndex(); - char[] c = pattern.toCharArray(); - if (escapingOn && c[start] == QUOTE) { - next(pos); - return appendTo == null ? null : appendTo.append(QUOTE); - } - int lastHold = start; - for (int i = pos.getIndex(); i < pattern.length(); i++) { - if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) { - appendTo.append(c, lastHold, pos.getIndex() - lastHold).append( - QUOTE); - pos.setIndex(i + ESCAPED_QUOTE.length()); - lastHold = pos.getIndex(); - continue; - } - switch (c[pos.getIndex()]) { - case QUOTE: - next(pos); - return appendTo == null ? null : appendTo.append(c, lastHold, - pos.getIndex() - lastHold); - default: - next(pos); - } - } - throw new IllegalArgumentException( - "Unterminated quoted string at position " + start); - } - - /** - * Consume quoted string only - * - * @param pattern pattern to parse - * @param pos current parse position - * @param escapingOn whether to process escaped quotes - */ - private void getQuotedString(String pattern, ParsePosition pos, - boolean escapingOn) { - appendQuotedString(pattern, pos, null, escapingOn); - } - - /** - * Learn whether the specified Collection contains non-null elements. - * @param coll to check - * @return true if some Object was found, false otherwise. - */ - private boolean containsElements(Collection coll) { - if (coll == null || coll.isEmpty()) { - return false; - } - for (Object name : coll) { - if (name != null) { - return true; - } - } - return false; - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormatFactory.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormatFactory.java deleted file mode 100644 index 359df9e0..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormatFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.text.Format; -import java.util.Locale; - -/** - * Format factory. - * - * @since 2.4 - * @version $Id: FormatFactory.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public interface FormatFactory { - - /** - * Create or retrieve a format instance. - * - * @param name The format type name - * @param arguments Arguments used to create the format instance. This allows the - * FormatFactory to implement the "format style" - * concept from java.text.MessageFormat. - * @param locale The locale, may be null - * @return The format instance - */ - Format getFormat(String name, String arguments, Locale locale); - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormattableUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormattableUtils.java deleted file mode 100644 index 2fc80cd2..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/FormattableUtils.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import static java.util.FormattableFlags.LEFT_JUSTIFY; - -import java.util.Formattable; -import java.util.Formatter; - -import external.org.apache.commons.lang3.ObjectUtils; -import external.org.apache.commons.lang3.StringUtils; -import external.org.apache.commons.lang3.Validate; - -/** - *

Provides utilities for working with the {@code Formattable} interface.

- * - *

The {@link Formattable} interface provides basic control over formatting - * when using a {@code Formatter}. It is primarily concerned with numeric precision - * and padding, and is not designed to allow generalised alternate formats.

- * - * @since Lang 3.0 - * @version $Id: FormattableUtils.java 1132390 2011-06-05 12:45:10Z sebb $ - */ -public class FormattableUtils { - - /** - * A format that simply outputs the value as a string. - */ - private static final String SIMPLEST_FORMAT = "%s"; - - /** - *

{@code FormattableUtils} instances should NOT be constructed in - * standard programming. Instead, the methods of the class should be invoked - * statically.

- * - *

This constructor is public to permit tools that require a JavaBean - * instance to operate.

- */ - public FormattableUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - * Get the default formatted representation of the specified - * {@code Formattable}. - * - * @param formattable the instance to convert to a string, not null - * @return the resulting string, not null - */ - public static String toString(Formattable formattable) { - return String.format(SIMPLEST_FORMAT, formattable); - } - - /** - * Handles the common {@code Formattable} operations of truncate-pad-append, - * with no ellipsis on precision overflow, and padding width underflow with - * spaces. - * - * @param seq the string to handle, not null - * @param formatter the destination formatter, not null - * @param flags the flags for formatting, see {@code Formattable} - * @param width the width of the output, see {@code Formattable} - * @param precision the precision of the output, see {@code Formattable} - * @return the {@code formatter} instance, not null - */ - public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width, - int precision) { - return append(seq, formatter, flags, width, precision, ' ', null); - } - - /** - * Handles the common {@link Formattable} operations of truncate-pad-append, - * with no ellipsis on precision overflow. - * - * @param seq the string to handle, not null - * @param formatter the destination formatter, not null - * @param flags the flags for formatting, see {@code Formattable} - * @param width the width of the output, see {@code Formattable} - * @param precision the precision of the output, see {@code Formattable} - * @param padChar the pad character to use - * @return the {@code formatter} instance, not null - */ - public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width, - int precision, char padChar) { - return append(seq, formatter, flags, width, precision, padChar, null); - } - - /** - * Handles the common {@link Formattable} operations of truncate-pad-append, - * padding width underflow with spaces. - * - * @param seq the string to handle, not null - * @param formatter the destination formatter, not null - * @param flags the flags for formatting, see {@code Formattable} - * @param width the width of the output, see {@code Formattable} - * @param precision the precision of the output, see {@code Formattable} - * @param ellipsis the ellipsis to use when precision dictates truncation, null or - * empty causes a hard truncation - * @return the {@code formatter} instance, not null - */ - public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width, - int precision, CharSequence ellipsis) { - return append(seq, formatter, flags, width, precision, ' ', ellipsis); - } - - /** - * Handles the common {@link Formattable} operations of truncate-pad-append. - * - * @param seq the string to handle, not null - * @param formatter the destination formatter, not null - * @param flags the flags for formatting, see {@code Formattable} - * @param width the width of the output, see {@code Formattable} - * @param precision the precision of the output, see {@code Formattable} - * @param padChar the pad character to use - * @param ellipsis the ellipsis to use when precision dictates truncation, null or - * empty causes a hard truncation - * @return the {@code formatter} instance, not null - */ - public static Formatter append(CharSequence seq, Formatter formatter, int flags, int width, - int precision, char padChar, CharSequence ellipsis) { - Validate.isTrue(ellipsis == null || precision < 0 || ellipsis.length() <= precision, - "Specified ellipsis '%1$s' exceeds precision of %2$s", ellipsis, Integer.valueOf(precision)); - StringBuilder buf = new StringBuilder(seq); - if (precision >= 0 && precision < seq.length()) { - CharSequence _ellipsis = ObjectUtils.defaultIfNull(ellipsis, StringUtils.EMPTY); - buf.replace(precision - _ellipsis.length(), seq.length(), _ellipsis.toString()); - } - boolean leftJustify = (flags & LEFT_JUSTIFY) == LEFT_JUSTIFY; - for (int i = buf.length(); i < width; i++) { - buf.insert(leftJustify ? i : 0, padChar); - } - formatter.format(buf.toString()); - return formatter; - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrBuilder.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrBuilder.java deleted file mode 100644 index 1d803a2d..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrBuilder.java +++ /dev/null @@ -1,2849 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.io.Reader; -import java.io.Writer; -import java.util.Iterator; -import java.util.List; - -import external.org.apache.commons.lang3.ArrayUtils; -import external.org.apache.commons.lang3.ObjectUtils; -import external.org.apache.commons.lang3.SystemUtils; - -/** - * Builds a string from constituent parts providing a more flexible and powerful API - * than StringBuffer. - *

- * The main differences from StringBuffer/StringBuilder are: - *

    - *
  • Not synchronized
  • - *
  • Not final
  • - *
  • Subclasses have direct access to character array
  • - *
  • Additional methods - *
      - *
    • appendWithSeparators - adds an array of values, with a separator
    • - *
    • appendPadding - adds a length padding characters
    • - *
    • appendFixedLength - adds a fixed width field to the builder
    • - *
    • toCharArray/getChars - simpler ways to get a range of the character array
    • - *
    • delete - delete char or string
    • - *
    • replace - search and replace for a char or string
    • - *
    • leftString/rightString/midString - substring without exceptions
    • - *
    • contains - whether the builder contains a char or string
    • - *
    • size/clear/isEmpty - collections style API methods
    • - *
    - *
  • - *
- *
  • Views - *
      - *
    • asTokenizer - uses the internal buffer as the source of a StrTokenizer
    • - *
    • asReader - uses the internal buffer as the source of a Reader
    • - *
    • asWriter - allows a Writer to write directly to the internal buffer
    • - *
    - *
  • - * - *

    - * The aim has been to provide an API that mimics very closely what StringBuffer - * provides, but with additional methods. It should be noted that some edge cases, - * with invalid indices or null input, have been altered - see individual methods. - * The biggest of these changes is that by default, null will not output the text - * 'null'. This can be controlled by a property, {@link #setNullText(String)}. - *

    - * Prior to 3.0, this class implemented Cloneable but did not implement the - * clone method so could not be used. From 3.0 onwards it no longer implements - * the interface. - * - * @since 2.2 - * @version $Id: StrBuilder.java 1199888 2011-11-09 17:35:01Z ggregory $ - */ -public class StrBuilder implements CharSequence, Appendable { - - /** - * The extra capacity for new builders. - */ - static final int CAPACITY = 32; - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 7628716375283629643L; - - /** Internal data storage. */ - protected char[] buffer; // TODO make private? - /** Current size of the buffer. */ - protected int size; // TODO make private? - /** The new line. */ - private String newLine; - /** The null text. */ - private String nullText; - - //----------------------------------------------------------------------- - /** - * Constructor that creates an empty builder initial capacity 32 characters. - */ - public StrBuilder() { - this(CAPACITY); - } - - /** - * Constructor that creates an empty builder the specified initial capacity. - * - * @param initialCapacity the initial capacity, zero or less will be converted to 32 - */ - public StrBuilder(int initialCapacity) { - super(); - if (initialCapacity <= 0) { - initialCapacity = CAPACITY; - } - buffer = new char[initialCapacity]; - } - - /** - * Constructor that creates a builder from the string, allocating - * 32 extra characters for growth. - * - * @param str the string to copy, null treated as blank string - */ - public StrBuilder(String str) { - super(); - if (str == null) { - buffer = new char[CAPACITY]; - } else { - buffer = new char[str.length() + CAPACITY]; - append(str); - } - } - - //----------------------------------------------------------------------- - /** - * Gets the text to be appended when a new line is added. - * - * @return the new line text, null means use system default - */ - public String getNewLineText() { - return newLine; - } - - /** - * Sets the text to be appended when a new line is added. - * - * @param newLine the new line text, null means use system default - * @return this, to enable chaining - */ - public StrBuilder setNewLineText(String newLine) { - this.newLine = newLine; - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets the text to be appended when null is added. - * - * @return the null text, null means no append - */ - public String getNullText() { - return nullText; - } - - /** - * Sets the text to be appended when null is added. - * - * @param nullText the null text, null means no append - * @return this, to enable chaining - */ - public StrBuilder setNullText(String nullText) { - if (nullText != null && nullText.length() == 0) { - nullText = null; - } - this.nullText = nullText; - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets the length of the string builder. - * - * @return the length - */ - public int length() { - return size; - } - - /** - * Updates the length of the builder by either dropping the last characters - * or adding filler of Unicode zero. - * - * @param length the length to set to, must be zero or positive - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the length is negative - */ - public StrBuilder setLength(int length) { - if (length < 0) { - throw new StringIndexOutOfBoundsException(length); - } - if (length < size) { - size = length; - } else if (length > size) { - ensureCapacity(length); - int oldEnd = size; - int newEnd = length; - size = length; - for (int i = oldEnd; i < newEnd; i++) { - buffer[i] = '\0'; - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets the current size of the internal character array buffer. - * - * @return the capacity - */ - public int capacity() { - return buffer.length; - } - - /** - * Checks the capacity and ensures that it is at least the size specified. - * - * @param capacity the capacity to ensure - * @return this, to enable chaining - */ - public StrBuilder ensureCapacity(int capacity) { - if (capacity > buffer.length) { - char[] old = buffer; - buffer = new char[capacity * 2]; - System.arraycopy(old, 0, buffer, 0, size); - } - return this; - } - - /** - * Minimizes the capacity to the actual length of the string. - * - * @return this, to enable chaining - */ - public StrBuilder minimizeCapacity() { - if (buffer.length > length()) { - char[] old = buffer; - buffer = new char[length()]; - System.arraycopy(old, 0, buffer, 0, size); - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets the length of the string builder. - *

    - * This method is the same as {@link #length()} and is provided to match the - * API of Collections. - * - * @return the length - */ - public int size() { - return size; - } - - /** - * Checks is the string builder is empty (convenience Collections API style method). - *

    - * This method is the same as checking {@link #length()} and is provided to match the - * API of Collections. - * - * @return true if the size is 0. - */ - public boolean isEmpty() { - return size == 0; - } - - /** - * Clears the string builder (convenience Collections API style method). - *

    - * This method does not reduce the size of the internal character buffer. - * To do that, call clear() followed by {@link #minimizeCapacity()}. - *

    - * This method is the same as {@link #setLength(int)} called with zero - * and is provided to match the API of Collections. - * - * @return this, to enable chaining - */ - public StrBuilder clear() { - size = 0; - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets the character at the specified index. - * - * @see #setCharAt(int, char) - * @see #deleteCharAt(int) - * @param index the index to retrieve, must be valid - * @return the character at the index - * @throws IndexOutOfBoundsException if the index is invalid - */ - public char charAt(int index) { - if (index < 0 || index >= length()) { - throw new StringIndexOutOfBoundsException(index); - } - return buffer[index]; - } - - /** - * Sets the character at the specified index. - * - * @see #charAt(int) - * @see #deleteCharAt(int) - * @param index the index to set - * @param ch the new character - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder setCharAt(int index, char ch) { - if (index < 0 || index >= length()) { - throw new StringIndexOutOfBoundsException(index); - } - buffer[index] = ch; - return this; - } - - /** - * Deletes the character at the specified index. - * - * @see #charAt(int) - * @see #setCharAt(int, char) - * @param index the index to delete - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder deleteCharAt(int index) { - if (index < 0 || index >= size) { - throw new StringIndexOutOfBoundsException(index); - } - deleteImpl(index, index + 1, 1); - return this; - } - - //----------------------------------------------------------------------- - /** - * Copies the builder's character array into a new character array. - * - * @return a new array that represents the contents of the builder - */ - public char[] toCharArray() { - if (size == 0) { - return ArrayUtils.EMPTY_CHAR_ARRAY; - } - char chars[] = new char[size]; - System.arraycopy(buffer, 0, chars, 0, size); - return chars; - } - - /** - * Copies part of the builder's character array into a new character array. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except that - * if too large it is treated as end of string - * @return a new array that holds part of the contents of the builder - * @throws IndexOutOfBoundsException if startIndex is invalid, - * or if endIndex is invalid (but endIndex greater than size is valid) - */ - public char[] toCharArray(int startIndex, int endIndex) { - endIndex = validateRange(startIndex, endIndex); - int len = endIndex - startIndex; - if (len == 0) { - return ArrayUtils.EMPTY_CHAR_ARRAY; - } - char chars[] = new char[len]; - System.arraycopy(buffer, startIndex, chars, 0, len); - return chars; - } - - /** - * Copies the character array into the specified array. - * - * @param destination the destination array, null will cause an array to be created - * @return the input array, unless that was null or too small - */ - public char[] getChars(char[] destination) { - int len = length(); - if (destination == null || destination.length < len) { - destination = new char[len]; - } - System.arraycopy(buffer, 0, destination, 0, len); - return destination; - } - - /** - * Copies the character array into the specified array. - * - * @param startIndex first index to copy, inclusive, must be valid - * @param endIndex last index, exclusive, must be valid - * @param destination the destination array, must not be null or too small - * @param destinationIndex the index to start copying in destination - * @throws NullPointerException if the array is null - * @throws IndexOutOfBoundsException if any index is invalid - */ - public void getChars(int startIndex, int endIndex, char destination[], int destinationIndex) { - if (startIndex < 0) { - throw new StringIndexOutOfBoundsException(startIndex); - } - if (endIndex < 0 || endIndex > length()) { - throw new StringIndexOutOfBoundsException(endIndex); - } - if (startIndex > endIndex) { - throw new StringIndexOutOfBoundsException("end < start"); - } - System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex); - } - - //----------------------------------------------------------------------- - /** - * Appends the new line string to this string builder. - *

    - * The new line string can be altered using {@link #setNewLineText(String)}. - * This might be used to force the output to always use Unix line endings - * even when on Windows. - * - * @return this, to enable chaining - */ - public StrBuilder appendNewLine() { - if (newLine == null) { - append(SystemUtils.LINE_SEPARATOR); - return this; - } - return append(newLine); - } - - /** - * Appends the text representing null to this string builder. - * - * @return this, to enable chaining - */ - public StrBuilder appendNull() { - if (nullText == null) { - return this; - } - return append(nullText); - } - - /** - * Appends an object to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param obj the object to append - * @return this, to enable chaining - */ - public StrBuilder append(Object obj) { - if (obj == null) { - return appendNull(); - } - return append(obj.toString()); - } - - /** - * Appends a CharSequence to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param seq the CharSequence to append - * @return this, to enable chaining - * @since 3.0 - */ - public StrBuilder append(CharSequence seq) { - if (seq == null) { - return appendNull(); - } - return append(seq.toString()); - } - - /** - * Appends part of a CharSequence to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param seq the CharSequence to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 3.0 - */ - public StrBuilder append(CharSequence seq, int startIndex, int length) { - if (seq == null) { - return appendNull(); - } - return append(seq.toString(), startIndex, length); - } - - /** - * Appends a string to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @return this, to enable chaining - */ - public StrBuilder append(String str) { - if (str == null) { - return appendNull(); - } - int strLen = str.length(); - if (strLen > 0) { - int len = length(); - ensureCapacity(len + strLen); - str.getChars(0, strLen, buffer, len); - size += strLen; - } - return this; - } - - /** - * Appends part of a string to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - */ - public StrBuilder append(String str, int startIndex, int length) { - if (str == null) { - return appendNull(); - } - if (startIndex < 0 || startIndex > str.length()) { - throw new StringIndexOutOfBoundsException("startIndex must be valid"); - } - if (length < 0 || (startIndex + length) > str.length()) { - throw new StringIndexOutOfBoundsException("length must be valid"); - } - if (length > 0) { - int len = length(); - ensureCapacity(len + length); - str.getChars(startIndex, startIndex + length, buffer, len); - size += length; - } - return this; - } - - /** - * Appends a string buffer to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string buffer to append - * @return this, to enable chaining - */ - public StrBuilder append(StringBuffer str) { - if (str == null) { - return appendNull(); - } - int strLen = str.length(); - if (strLen > 0) { - int len = length(); - ensureCapacity(len + strLen); - str.getChars(0, strLen, buffer, len); - size += strLen; - } - return this; - } - - /** - * Appends part of a string buffer to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - */ - public StrBuilder append(StringBuffer str, int startIndex, int length) { - if (str == null) { - return appendNull(); - } - if (startIndex < 0 || startIndex > str.length()) { - throw new StringIndexOutOfBoundsException("startIndex must be valid"); - } - if (length < 0 || (startIndex + length) > str.length()) { - throw new StringIndexOutOfBoundsException("length must be valid"); - } - if (length > 0) { - int len = length(); - ensureCapacity(len + length); - str.getChars(startIndex, startIndex + length, buffer, len); - size += length; - } - return this; - } - - /** - * Appends another string builder to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string builder to append - * @return this, to enable chaining - */ - public StrBuilder append(StrBuilder str) { - if (str == null) { - return appendNull(); - } - int strLen = str.length(); - if (strLen > 0) { - int len = length(); - ensureCapacity(len + strLen); - System.arraycopy(str.buffer, 0, buffer, len, strLen); - size += strLen; - } - return this; - } - - /** - * Appends part of a string builder to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - */ - public StrBuilder append(StrBuilder str, int startIndex, int length) { - if (str == null) { - return appendNull(); - } - if (startIndex < 0 || startIndex > str.length()) { - throw new StringIndexOutOfBoundsException("startIndex must be valid"); - } - if (length < 0 || (startIndex + length) > str.length()) { - throw new StringIndexOutOfBoundsException("length must be valid"); - } - if (length > 0) { - int len = length(); - ensureCapacity(len + length); - str.getChars(startIndex, startIndex + length, buffer, len); - size += length; - } - return this; - } - - /** - * Appends a char array to the string builder. - * Appending null will call {@link #appendNull()}. - * - * @param chars the char array to append - * @return this, to enable chaining - */ - public StrBuilder append(char[] chars) { - if (chars == null) { - return appendNull(); - } - int strLen = chars.length; - if (strLen > 0) { - int len = length(); - ensureCapacity(len + strLen); - System.arraycopy(chars, 0, buffer, len, strLen); - size += strLen; - } - return this; - } - - /** - * Appends a char array to the string builder. - * Appending null will call {@link #appendNull()}. - * - * @param chars the char array to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - */ - public StrBuilder append(char[] chars, int startIndex, int length) { - if (chars == null) { - return appendNull(); - } - if (startIndex < 0 || startIndex > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length); - } - if (length < 0 || (startIndex + length) > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid length: " + length); - } - if (length > 0) { - int len = length(); - ensureCapacity(len + length); - System.arraycopy(chars, startIndex, buffer, len, length); - size += length; - } - return this; - } - - /** - * Appends a boolean value to the string builder. - * - * @param value the value to append - * @return this, to enable chaining - */ - public StrBuilder append(boolean value) { - if (value) { - ensureCapacity(size + 4); - buffer[size++] = 't'; - buffer[size++] = 'r'; - buffer[size++] = 'u'; - buffer[size++] = 'e'; - } else { - ensureCapacity(size + 5); - buffer[size++] = 'f'; - buffer[size++] = 'a'; - buffer[size++] = 'l'; - buffer[size++] = 's'; - buffer[size++] = 'e'; - } - return this; - } - - /** - * Appends a char value to the string builder. - * - * @param ch the value to append - * @return this, to enable chaining - * @since 3.0 - */ - public StrBuilder append(char ch) { - int len = length(); - ensureCapacity(len + 1); - buffer[size++] = ch; - return this; - } - - /** - * Appends an int value to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - */ - public StrBuilder append(int value) { - return append(String.valueOf(value)); - } - - /** - * Appends a long value to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - */ - public StrBuilder append(long value) { - return append(String.valueOf(value)); - } - - /** - * Appends a float value to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - */ - public StrBuilder append(float value) { - return append(String.valueOf(value)); - } - - /** - * Appends a double value to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - */ - public StrBuilder append(double value) { - return append(String.valueOf(value)); - } - - //----------------------------------------------------------------------- - /** - * Appends an object followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param obj the object to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(Object obj) { - return append(obj).appendNewLine(); - } - - /** - * Appends a string followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(String str) { - return append(str).appendNewLine(); - } - - /** - * Appends part of a string followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(String str, int startIndex, int length) { - return append(str, startIndex, length).appendNewLine(); - } - - /** - * Appends a string buffer followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string buffer to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(StringBuffer str) { - return append(str).appendNewLine(); - } - - /** - * Appends part of a string buffer followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(StringBuffer str, int startIndex, int length) { - return append(str, startIndex, length).appendNewLine(); - } - - /** - * Appends another string builder followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string builder to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(StrBuilder str) { - return append(str).appendNewLine(); - } - - /** - * Appends part of a string builder followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(StrBuilder str, int startIndex, int length) { - return append(str, startIndex, length).appendNewLine(); - } - - /** - * Appends a char array followed by a new line to the string builder. - * Appending null will call {@link #appendNull()}. - * - * @param chars the char array to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(char[] chars) { - return append(chars).appendNewLine(); - } - - /** - * Appends a char array followed by a new line to the string builder. - * Appending null will call {@link #appendNull()}. - * - * @param chars the char array to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(char[] chars, int startIndex, int length) { - return append(chars, startIndex, length).appendNewLine(); - } - - /** - * Appends a boolean value followed by a new line to the string builder. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(boolean value) { - return append(value).appendNewLine(); - } - - /** - * Appends a char value followed by a new line to the string builder. - * - * @param ch the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(char ch) { - return append(ch).appendNewLine(); - } - - /** - * Appends an int value followed by a new line to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(int value) { - return append(value).appendNewLine(); - } - - /** - * Appends a long value followed by a new line to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(long value) { - return append(value).appendNewLine(); - } - - /** - * Appends a float value followed by a new line to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(float value) { - return append(value).appendNewLine(); - } - - /** - * Appends a double value followed by a new line to the string builder using String.valueOf. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(double value) { - return append(value).appendNewLine(); - } - - //----------------------------------------------------------------------- - /** - * Appends each item in an array to the builder without any separators. - * Appending a null array will have no effect. - * Each object is appended using {@link #append(Object)}. - * - * @param array the array to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendAll(Object[] array) { - if (array != null && array.length > 0) { - for (Object element : array) { - append(element); - } - } - return this; - } - - /** - * Appends each item in a iterable to the builder without any separators. - * Appending a null iterable will have no effect. - * Each object is appended using {@link #append(Object)}. - * - * @param iterable the iterable to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendAll(Iterable iterable) { - if (iterable != null) { - Iterator it = iterable.iterator(); - while (it.hasNext()) { - append(it.next()); - } - } - return this; - } - - /** - * Appends each item in an iterator to the builder without any separators. - * Appending a null iterator will have no effect. - * Each object is appended using {@link #append(Object)}. - * - * @param it the iterator to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendAll(Iterator it) { - if (it != null) { - while (it.hasNext()) { - append(it.next()); - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Appends an array placing separators between each value, but - * not before the first or after the last. - * Appending a null array will have no effect. - * Each object is appended using {@link #append(Object)}. - * - * @param array the array to append - * @param separator the separator to use, null means no separator - * @return this, to enable chaining - */ - public StrBuilder appendWithSeparators(Object[] array, String separator) { - if (array != null && array.length > 0) { - separator = ObjectUtils.toString(separator); - append(array[0]); - for (int i = 1; i < array.length; i++) { - append(separator); - append(array[i]); - } - } - return this; - } - - /** - * Appends a iterable placing separators between each value, but - * not before the first or after the last. - * Appending a null iterable will have no effect. - * Each object is appended using {@link #append(Object)}. - * - * @param iterable the iterable to append - * @param separator the separator to use, null means no separator - * @return this, to enable chaining - */ - public StrBuilder appendWithSeparators(Iterable iterable, String separator) { - if (iterable != null) { - separator = ObjectUtils.toString(separator); - Iterator it = iterable.iterator(); - while (it.hasNext()) { - append(it.next()); - if (it.hasNext()) { - append(separator); - } - } - } - return this; - } - - /** - * Appends an iterator placing separators between each value, but - * not before the first or after the last. - * Appending a null iterator will have no effect. - * Each object is appended using {@link #append(Object)}. - * - * @param it the iterator to append - * @param separator the separator to use, null means no separator - * @return this, to enable chaining - */ - public StrBuilder appendWithSeparators(Iterator it, String separator) { - if (it != null) { - separator = ObjectUtils.toString(separator); - while (it.hasNext()) { - append(it.next()); - if (it.hasNext()) { - append(separator); - } - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Appends a separator if the builder is currently non-empty. - * Appending a null separator will have no effect. - * The separator is appended using {@link #append(String)}. - *

    - * This method is useful for adding a separator each time around the - * loop except the first. - *

    -     * for (Iterator it = list.iterator(); it.hasNext(); ) {
    -     *   appendSeparator(",");
    -     *   append(it.next());
    -     * }
    -     * 
    - * Note that for this simple example, you should use - * {@link #appendWithSeparators(Iterable, String)}. - * - * @param separator the separator to use, null means no separator - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendSeparator(String separator) { - return appendSeparator(separator, null); - } - - /** - * Appends one of both separators to the StrBuilder. - * If the builder is currently empty it will append the defaultIfEmpty-separator - * Otherwise it will append the standard-separator - * - * Appending a null separator will have no effect. - * The separator is appended using {@link #append(String)}. - *

    - * This method is for example useful for constructing queries - *

    -     * StrBuilder whereClause = new StrBuilder();
    -     * if(searchCommand.getPriority() != null) {
    -     *  whereClause.appendSeparator(" and", " where");
    -     *  whereClause.append(" priority = ?")
    -     * }
    -     * if(searchCommand.getComponent() != null) {
    -     *  whereClause.appendSeparator(" and", " where");
    -     *  whereClause.append(" component = ?")
    -     * }
    -     * selectClause.append(whereClause)
    -     * 
    - * - * @param standard the separator if builder is not empty, null means no separator - * @param defaultIfEmpty the separator if builder is empty, null means no separator - * @return this, to enable chaining - * @since 2.5 - */ - public StrBuilder appendSeparator(String standard, String defaultIfEmpty) { - String str = isEmpty() ? defaultIfEmpty : standard; - if (str != null) { - append(str); - } - return this; - } - - /** - * Appends a separator if the builder is currently non-empty. - * The separator is appended using {@link #append(char)}. - *

    - * This method is useful for adding a separator each time around the - * loop except the first. - *

    -     * for (Iterator it = list.iterator(); it.hasNext(); ) {
    -     *   appendSeparator(',');
    -     *   append(it.next());
    -     * }
    -     * 
    - * Note that for this simple example, you should use - * {@link #appendWithSeparators(Iterable, String)}. - * - * @param separator the separator to use - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendSeparator(char separator) { - if (size() > 0) { - append(separator); - } - return this; - } - - /** - * Append one of both separators to the builder - * If the builder is currently empty it will append the defaultIfEmpty-separator - * Otherwise it will append the standard-separator - * - * The separator is appended using {@link #append(char)}. - * @param standard the separator if builder is not empty - * @param defaultIfEmpty the separator if builder is empty - * @return this, to enable chaining - * @since 2.5 - */ - public StrBuilder appendSeparator(char standard, char defaultIfEmpty) { - if (size() > 0) { - append(standard); - } else { - append(defaultIfEmpty); - } - return this; - } - /** - * Appends a separator to the builder if the loop index is greater than zero. - * Appending a null separator will have no effect. - * The separator is appended using {@link #append(String)}. - *

    - * This method is useful for adding a separator each time around the - * loop except the first. - *

    -     * for (int i = 0; i < list.size(); i++) {
    -     *   appendSeparator(",", i);
    -     *   append(list.get(i));
    -     * }
    -     * 
    - * Note that for this simple example, you should use - * {@link #appendWithSeparators(Iterable, String)}. - * - * @param separator the separator to use, null means no separator - * @param loopIndex the loop index - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendSeparator(String separator, int loopIndex) { - if (separator != null && loopIndex > 0) { - append(separator); - } - return this; - } - - /** - * Appends a separator to the builder if the loop index is greater than zero. - * The separator is appended using {@link #append(char)}. - *

    - * This method is useful for adding a separator each time around the - * loop except the first. - *

    -     * for (int i = 0; i < list.size(); i++) {
    -     *   appendSeparator(",", i);
    -     *   append(list.get(i));
    -     * }
    -     * 
    - * Note that for this simple example, you should use - * {@link #appendWithSeparators(Iterable, String)}. - * - * @param separator the separator to use - * @param loopIndex the loop index - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendSeparator(char separator, int loopIndex) { - if (loopIndex > 0) { - append(separator); - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Appends the pad character to the builder the specified number of times. - * - * @param length the length to append, negative means no append - * @param padChar the character to append - * @return this, to enable chaining - */ - public StrBuilder appendPadding(int length, char padChar) { - if (length >= 0) { - ensureCapacity(size + length); - for (int i = 0; i < length; i++) { - buffer[size++] = padChar; - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Appends an object to the builder padding on the left to a fixed width. - * The toString of the object is used. - * If the object is larger than the length, the left hand side is lost. - * If the object is null, the null text value is used. - * - * @param obj the object to append, null uses null text - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use - * @return this, to enable chaining - */ - public StrBuilder appendFixedWidthPadLeft(Object obj, int width, char padChar) { - if (width > 0) { - ensureCapacity(size + width); - String str = (obj == null ? getNullText() : obj.toString()); - if (str == null) { - str = ""; - } - int strLen = str.length(); - if (strLen >= width) { - str.getChars(strLen - width, strLen, buffer, size); - } else { - int padLen = width - strLen; - for (int i = 0; i < padLen; i++) { - buffer[size + i] = padChar; - } - str.getChars(0, strLen, buffer, size + padLen); - } - size += width; - } - return this; - } - - /** - * Appends an object to the builder padding on the left to a fixed width. - * The String.valueOf of the int value is used. - * If the formatted value is larger than the length, the left hand side is lost. - * - * @param value the value to append - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use - * @return this, to enable chaining - */ - public StrBuilder appendFixedWidthPadLeft(int value, int width, char padChar) { - return appendFixedWidthPadLeft(String.valueOf(value), width, padChar); - } - - /** - * Appends an object to the builder padding on the right to a fixed length. - * The toString of the object is used. - * If the object is larger than the length, the right hand side is lost. - * If the object is null, null text value is used. - * - * @param obj the object to append, null uses null text - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use - * @return this, to enable chaining - */ - public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) { - if (width > 0) { - ensureCapacity(size + width); - String str = (obj == null ? getNullText() : obj.toString()); - if (str == null) { - str = ""; - } - int strLen = str.length(); - if (strLen >= width) { - str.getChars(0, width, buffer, size); - } else { - int padLen = width - strLen; - str.getChars(0, strLen, buffer, size); - for (int i = 0; i < padLen; i++) { - buffer[size + strLen + i] = padChar; - } - } - size += width; - } - return this; - } - - /** - * Appends an object to the builder padding on the right to a fixed length. - * The String.valueOf of the int value is used. - * If the object is larger than the length, the right hand side is lost. - * - * @param value the value to append - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use - * @return this, to enable chaining - */ - public StrBuilder appendFixedWidthPadRight(int value, int width, char padChar) { - return appendFixedWidthPadRight(String.valueOf(value), width, padChar); - } - - //----------------------------------------------------------------------- - /** - * Inserts the string representation of an object into this builder. - * Inserting null will use the stored null text value. - * - * @param index the index to add at, must be valid - * @param obj the object to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, Object obj) { - if (obj == null) { - return insert(index, nullText); - } - return insert(index, obj.toString()); - } - - /** - * Inserts the string into this builder. - * Inserting null will use the stored null text value. - * - * @param index the index to add at, must be valid - * @param str the string to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - @SuppressWarnings("null") // str cannot be null - public StrBuilder insert(int index, String str) { - validateIndex(index); - if (str == null) { - str = nullText; - } - int strLen = (str == null ? 0 : str.length()); - if (strLen > 0) { - int newSize = size + strLen; - ensureCapacity(newSize); - System.arraycopy(buffer, index, buffer, index + strLen, size - index); - size = newSize; - str.getChars(0, strLen, buffer, index); // str cannot be null here - } - return this; - } - - /** - * Inserts the character array into this builder. - * Inserting null will use the stored null text value. - * - * @param index the index to add at, must be valid - * @param chars the char array to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, char chars[]) { - validateIndex(index); - if (chars == null) { - return insert(index, nullText); - } - int len = chars.length; - if (len > 0) { - ensureCapacity(size + len); - System.arraycopy(buffer, index, buffer, index + len, size - index); - System.arraycopy(chars, 0, buffer, index, len); - size += len; - } - return this; - } - - /** - * Inserts part of the character array into this builder. - * Inserting null will use the stored null text value. - * - * @param index the index to add at, must be valid - * @param chars the char array to insert - * @param offset the offset into the character array to start at, must be valid - * @param length the length of the character array part to copy, must be positive - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if any index is invalid - */ - public StrBuilder insert(int index, char chars[], int offset, int length) { - validateIndex(index); - if (chars == null) { - return insert(index, nullText); - } - if (offset < 0 || offset > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid offset: " + offset); - } - if (length < 0 || offset + length > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid length: " + length); - } - if (length > 0) { - ensureCapacity(size + length); - System.arraycopy(buffer, index, buffer, index + length, size - index); - System.arraycopy(chars, offset, buffer, index, length); - size += length; - } - return this; - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, boolean value) { - validateIndex(index); - if (value) { - ensureCapacity(size + 4); - System.arraycopy(buffer, index, buffer, index + 4, size - index); - buffer[index++] = 't'; - buffer[index++] = 'r'; - buffer[index++] = 'u'; - buffer[index] = 'e'; - size += 4; - } else { - ensureCapacity(size + 5); - System.arraycopy(buffer, index, buffer, index + 5, size - index); - buffer[index++] = 'f'; - buffer[index++] = 'a'; - buffer[index++] = 'l'; - buffer[index++] = 's'; - buffer[index] = 'e'; - size += 5; - } - return this; - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, char value) { - validateIndex(index); - ensureCapacity(size + 1); - System.arraycopy(buffer, index, buffer, index + 1, size - index); - buffer[index] = value; - size++; - return this; - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, int value) { - return insert(index, String.valueOf(value)); - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, long value) { - return insert(index, String.valueOf(value)); - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, float value) { - return insert(index, String.valueOf(value)); - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, double value) { - return insert(index, String.valueOf(value)); - } - - //----------------------------------------------------------------------- - /** - * Internal method to delete a range without validation. - * - * @param startIndex the start index, must be valid - * @param endIndex the end index (exclusive), must be valid - * @param len the length, must be valid - * @throws IndexOutOfBoundsException if any index is invalid - */ - private void deleteImpl(int startIndex, int endIndex, int len) { - System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex); - size -= len; - } - - /** - * Deletes the characters between the two specified indices. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except - * that if too large it is treated as end of string - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder delete(int startIndex, int endIndex) { - endIndex = validateRange(startIndex, endIndex); - int len = endIndex - startIndex; - if (len > 0) { - deleteImpl(startIndex, endIndex, len); - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Deletes the character wherever it occurs in the builder. - * - * @param ch the character to delete - * @return this, to enable chaining - */ - public StrBuilder deleteAll(char ch) { - for (int i = 0; i < size; i++) { - if (buffer[i] == ch) { - int start = i; - while (++i < size) { - if (buffer[i] != ch) { - break; - } - } - int len = i - start; - deleteImpl(start, i, len); - i -= len; - } - } - return this; - } - - /** - * Deletes the character wherever it occurs in the builder. - * - * @param ch the character to delete - * @return this, to enable chaining - */ - public StrBuilder deleteFirst(char ch) { - for (int i = 0; i < size; i++) { - if (buffer[i] == ch) { - deleteImpl(i, i + 1, 1); - break; - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Deletes the string wherever it occurs in the builder. - * - * @param str the string to delete, null causes no action - * @return this, to enable chaining - */ - public StrBuilder deleteAll(String str) { - int len = (str == null ? 0 : str.length()); - if (len > 0) { - int index = indexOf(str, 0); - while (index >= 0) { - deleteImpl(index, index + len, len); - index = indexOf(str, index); - } - } - return this; - } - - /** - * Deletes the string wherever it occurs in the builder. - * - * @param str the string to delete, null causes no action - * @return this, to enable chaining - */ - public StrBuilder deleteFirst(String str) { - int len = (str == null ? 0 : str.length()); - if (len > 0) { - int index = indexOf(str, 0); - if (index >= 0) { - deleteImpl(index, index + len, len); - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Deletes all parts of the builder that the matcher matches. - *

    - * Matchers can be used to perform advanced deletion behaviour. - * For example you could write a matcher to delete all occurances - * where the character 'a' is followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no action - * @return this, to enable chaining - */ - public StrBuilder deleteAll(StrMatcher matcher) { - return replace(matcher, null, 0, size, -1); - } - - /** - * Deletes the first match within the builder using the specified matcher. - *

    - * Matchers can be used to perform advanced deletion behaviour. - * For example you could write a matcher to delete - * where the character 'a' is followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no action - * @return this, to enable chaining - */ - public StrBuilder deleteFirst(StrMatcher matcher) { - return replace(matcher, null, 0, size, 1); - } - - //----------------------------------------------------------------------- - /** - * Internal method to delete a range without validation. - * - * @param startIndex the start index, must be valid - * @param endIndex the end index (exclusive), must be valid - * @param removeLen the length to remove (endIndex - startIndex), must be valid - * @param insertStr the string to replace with, null means delete range - * @param insertLen the length of the insert string, must be valid - * @throws IndexOutOfBoundsException if any index is invalid - */ - private void replaceImpl(int startIndex, int endIndex, int removeLen, String insertStr, int insertLen) { - int newSize = size - removeLen + insertLen; - if (insertLen != removeLen) { - ensureCapacity(newSize); - System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex); - size = newSize; - } - if (insertLen > 0) { - insertStr.getChars(0, insertLen, buffer, startIndex); - } - } - - /** - * Replaces a portion of the string builder with another string. - * The length of the inserted string does not have to match the removed length. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except - * that if too large it is treated as end of string - * @param replaceStr the string to replace with, null means delete range - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder replace(int startIndex, int endIndex, String replaceStr) { - endIndex = validateRange(startIndex, endIndex); - int insertLen = (replaceStr == null ? 0 : replaceStr.length()); - replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen); - return this; - } - - //----------------------------------------------------------------------- - /** - * Replaces the search character with the replace character - * throughout the builder. - * - * @param search the search character - * @param replace the replace character - * @return this, to enable chaining - */ - public StrBuilder replaceAll(char search, char replace) { - if (search != replace) { - for (int i = 0; i < size; i++) { - if (buffer[i] == search) { - buffer[i] = replace; - } - } - } - return this; - } - - /** - * Replaces the first instance of the search character with the - * replace character in the builder. - * - * @param search the search character - * @param replace the replace character - * @return this, to enable chaining - */ - public StrBuilder replaceFirst(char search, char replace) { - if (search != replace) { - for (int i = 0; i < size; i++) { - if (buffer[i] == search) { - buffer[i] = replace; - break; - } - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Replaces the search string with the replace string throughout the builder. - * - * @param searchStr the search string, null causes no action to occur - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceAll(String searchStr, String replaceStr) { - int searchLen = (searchStr == null ? 0 : searchStr.length()); - if (searchLen > 0) { - int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); - int index = indexOf(searchStr, 0); - while (index >= 0) { - replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); - index = indexOf(searchStr, index + replaceLen); - } - } - return this; - } - - /** - * Replaces the first instance of the search string with the replace string. - * - * @param searchStr the search string, null causes no action to occur - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceFirst(String searchStr, String replaceStr) { - int searchLen = (searchStr == null ? 0 : searchStr.length()); - if (searchLen > 0) { - int index = indexOf(searchStr, 0); - if (index >= 0) { - int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); - replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Replaces all matches within the builder with the replace string. - *

    - * Matchers can be used to perform advanced replace behaviour. - * For example you could write a matcher to replace all occurances - * where the character 'a' is followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no action - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceAll(StrMatcher matcher, String replaceStr) { - return replace(matcher, replaceStr, 0, size, -1); - } - - /** - * Replaces the first match within the builder with the replace string. - *

    - * Matchers can be used to perform advanced replace behaviour. - * For example you could write a matcher to replace - * where the character 'a' is followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no action - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceFirst(StrMatcher matcher, String replaceStr) { - return replace(matcher, replaceStr, 0, size, 1); - } - - // ----------------------------------------------------------------------- - /** - * Advanced search and replaces within the builder using a matcher. - *

    - * Matchers can be used to perform advanced behaviour. - * For example you could write a matcher to delete all occurances - * where the character 'a' is followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no action - * @param replaceStr the string to replace the match with, null is a delete - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except - * that if too large it is treated as end of string - * @param replaceCount the number of times to replace, -1 for replace all - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if start index is invalid - */ - public StrBuilder replace( - StrMatcher matcher, String replaceStr, - int startIndex, int endIndex, int replaceCount) { - endIndex = validateRange(startIndex, endIndex); - return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount); - } - - /** - * Replaces within the builder using a matcher. - *

    - * Matchers can be used to perform advanced behaviour. - * For example you could write a matcher to delete all occurances - * where the character 'a' is followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no action - * @param replaceStr the string to replace the match with, null is a delete - * @param from the start index, must be valid - * @param to the end index (exclusive), must be valid - * @param replaceCount the number of times to replace, -1 for replace all - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if any index is invalid - */ - private StrBuilder replaceImpl( - StrMatcher matcher, String replaceStr, - int from, int to, int replaceCount) { - if (matcher == null || size == 0) { - return this; - } - int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); - char[] buf = buffer; - for (int i = from; i < to && replaceCount != 0; i++) { - int removeLen = matcher.isMatch(buf, i, from, to); - if (removeLen > 0) { - replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen); - to = to - removeLen + replaceLen; - i = i + replaceLen - 1; - if (replaceCount > 0) { - replaceCount--; - } - } - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Reverses the string builder placing each character in the opposite index. - * - * @return this, to enable chaining - */ - public StrBuilder reverse() { - if (size == 0) { - return this; - } - - int half = size / 2; - char[] buf = buffer; - for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++,rightIdx--) { - char swap = buf[leftIdx]; - buf[leftIdx] = buf[rightIdx]; - buf[rightIdx] = swap; - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Trims the builder by removing characters less than or equal to a space - * from the beginning and end. - * - * @return this, to enable chaining - */ - public StrBuilder trim() { - if (size == 0) { - return this; - } - int len = size; - char[] buf = buffer; - int pos = 0; - while (pos < len && buf[pos] <= ' ') { - pos++; - } - while (pos < len && buf[len - 1] <= ' ') { - len--; - } - if (len < size) { - delete(len, size); - } - if (pos > 0) { - delete(0, pos); - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Checks whether this builder starts with the specified string. - *

    - * Note that this method handles null input quietly, unlike String. - * - * @param str the string to search for, null returns false - * @return true if the builder starts with the string - */ - public boolean startsWith(String str) { - if (str == null) { - return false; - } - int len = str.length(); - if (len == 0) { - return true; - } - if (len > size) { - return false; - } - for (int i = 0; i < len; i++) { - if (buffer[i] != str.charAt(i)) { - return false; - } - } - return true; - } - - /** - * Checks whether this builder ends with the specified string. - *

    - * Note that this method handles null input quietly, unlike String. - * - * @param str the string to search for, null returns false - * @return true if the builder ends with the string - */ - public boolean endsWith(String str) { - if (str == null) { - return false; - } - int len = str.length(); - if (len == 0) { - return true; - } - if (len > size) { - return false; - } - int pos = size - len; - for (int i = 0; i < len; i++,pos++) { - if (buffer[pos] != str.charAt(i)) { - return false; - } - } - return true; - } - - //----------------------------------------------------------------------- - /** - * {@inheritDoc} - * @since 3.0 - */ - public CharSequence subSequence(int startIndex, int endIndex) { - if (startIndex < 0) { - throw new StringIndexOutOfBoundsException(startIndex); - } - if (endIndex > size) { - throw new StringIndexOutOfBoundsException(endIndex); - } - if (startIndex > endIndex) { - throw new StringIndexOutOfBoundsException(endIndex - startIndex); - } - return substring(startIndex, endIndex); - } - - /** - * Extracts a portion of this string builder as a string. - * - * @param start the start index, inclusive, must be valid - * @return the new string - * @throws IndexOutOfBoundsException if the index is invalid - */ - public String substring(int start) { - return substring(start, size); - } - - /** - * Extracts a portion of this string builder as a string. - *

    - * Note: This method treats an endIndex greater than the length of the - * builder as equal to the length of the builder, and continues - * without error, unlike StringBuffer or String. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except - * that if too large it is treated as end of string - * @return the new string - * @throws IndexOutOfBoundsException if the index is invalid - */ - public String substring(int startIndex, int endIndex) { - endIndex = validateRange(startIndex, endIndex); - return new String(buffer, startIndex, endIndex - startIndex); - } - - /** - * Extracts the leftmost characters from the string builder without - * throwing an exception. - *

    - * This method extracts the left length characters from - * the builder. If this many characters are not available, the whole - * builder is returned. Thus the returned string may be shorter than the - * length requested. - * - * @param length the number of characters to extract, negative returns empty string - * @return the new string - */ - public String leftString(int length) { - if (length <= 0) { - return ""; - } else if (length >= size) { - return new String(buffer, 0, size); - } else { - return new String(buffer, 0, length); - } - } - - /** - * Extracts the rightmost characters from the string builder without - * throwing an exception. - *

    - * This method extracts the right length characters from - * the builder. If this many characters are not available, the whole - * builder is returned. Thus the returned string may be shorter than the - * length requested. - * - * @param length the number of characters to extract, negative returns empty string - * @return the new string - */ - public String rightString(int length) { - if (length <= 0) { - return ""; - } else if (length >= size) { - return new String(buffer, 0, size); - } else { - return new String(buffer, size - length, length); - } - } - - /** - * Extracts some characters from the middle of the string builder without - * throwing an exception. - *

    - * This method extracts length characters from the builder - * at the specified index. - * If the index is negative it is treated as zero. - * If the index is greater than the builder size, it is treated as the builder size. - * If the length is negative, the empty string is returned. - * If insufficient characters are available in the builder, as much as possible is returned. - * Thus the returned string may be shorter than the length requested. - * - * @param index the index to start at, negative means zero - * @param length the number of characters to extract, negative returns empty string - * @return the new string - */ - public String midString(int index, int length) { - if (index < 0) { - index = 0; - } - if (length <= 0 || index >= size) { - return ""; - } - if (size <= index + length) { - return new String(buffer, index, size - index); - } else { - return new String(buffer, index, length); - } - } - - //----------------------------------------------------------------------- - /** - * Checks if the string builder contains the specified char. - * - * @param ch the character to find - * @return true if the builder contains the character - */ - public boolean contains(char ch) { - char[] thisBuf = buffer; - for (int i = 0; i < this.size; i++) { - if (thisBuf[i] == ch) { - return true; - } - } - return false; - } - - /** - * Checks if the string builder contains the specified string. - * - * @param str the string to find - * @return true if the builder contains the string - */ - public boolean contains(String str) { - return indexOf(str, 0) >= 0; - } - - /** - * Checks if the string builder contains a string matched using the - * specified matcher. - *

    - * Matchers can be used to perform advanced searching behaviour. - * For example you could write a matcher to search for the character - * 'a' followed by a number. - * - * @param matcher the matcher to use, null returns -1 - * @return true if the matcher finds a match in the builder - */ - public boolean contains(StrMatcher matcher) { - return indexOf(matcher, 0) >= 0; - } - - //----------------------------------------------------------------------- - /** - * Searches the string builder to find the first reference to the specified char. - * - * @param ch the character to find - * @return the first index of the character, or -1 if not found - */ - public int indexOf(char ch) { - return indexOf(ch, 0); - } - - /** - * Searches the string builder to find the first reference to the specified char. - * - * @param ch the character to find - * @param startIndex the index to start at, invalid index rounded to edge - * @return the first index of the character, or -1 if not found - */ - public int indexOf(char ch, int startIndex) { - startIndex = (startIndex < 0 ? 0 : startIndex); - if (startIndex >= size) { - return -1; - } - char[] thisBuf = buffer; - for (int i = startIndex; i < size; i++) { - if (thisBuf[i] == ch) { - return i; - } - } - return -1; - } - - /** - * Searches the string builder to find the first reference to the specified string. - *

    - * Note that a null input string will return -1, whereas the JDK throws an exception. - * - * @param str the string to find, null returns -1 - * @return the first index of the string, or -1 if not found - */ - public int indexOf(String str) { - return indexOf(str, 0); - } - - /** - * Searches the string builder to find the first reference to the specified - * string starting searching from the given index. - *

    - * Note that a null input string will return -1, whereas the JDK throws an exception. - * - * @param str the string to find, null returns -1 - * @param startIndex the index to start at, invalid index rounded to edge - * @return the first index of the string, or -1 if not found - */ - public int indexOf(String str, int startIndex) { - startIndex = (startIndex < 0 ? 0 : startIndex); - if (str == null || startIndex >= size) { - return -1; - } - int strLen = str.length(); - if (strLen == 1) { - return indexOf(str.charAt(0), startIndex); - } - if (strLen == 0) { - return startIndex; - } - if (strLen > size) { - return -1; - } - char[] thisBuf = buffer; - int len = size - strLen + 1; - outer: - for (int i = startIndex; i < len; i++) { - for (int j = 0; j < strLen; j++) { - if (str.charAt(j) != thisBuf[i + j]) { - continue outer; - } - } - return i; - } - return -1; - } - - /** - * Searches the string builder using the matcher to find the first match. - *

    - * Matchers can be used to perform advanced searching behaviour. - * For example you could write a matcher to find the character 'a' - * followed by a number. - * - * @param matcher the matcher to use, null returns -1 - * @return the first index matched, or -1 if not found - */ - public int indexOf(StrMatcher matcher) { - return indexOf(matcher, 0); - } - - /** - * Searches the string builder using the matcher to find the first - * match searching from the given index. - *

    - * Matchers can be used to perform advanced searching behaviour. - * For example you could write a matcher to find the character 'a' - * followed by a number. - * - * @param matcher the matcher to use, null returns -1 - * @param startIndex the index to start at, invalid index rounded to edge - * @return the first index matched, or -1 if not found - */ - public int indexOf(StrMatcher matcher, int startIndex) { - startIndex = (startIndex < 0 ? 0 : startIndex); - if (matcher == null || startIndex >= size) { - return -1; - } - int len = size; - char[] buf = buffer; - for (int i = startIndex; i < len; i++) { - if (matcher.isMatch(buf, i, startIndex, len) > 0) { - return i; - } - } - return -1; - } - - //----------------------------------------------------------------------- - /** - * Searches the string builder to find the last reference to the specified char. - * - * @param ch the character to find - * @return the last index of the character, or -1 if not found - */ - public int lastIndexOf(char ch) { - return lastIndexOf(ch, size - 1); - } - - /** - * Searches the string builder to find the last reference to the specified char. - * - * @param ch the character to find - * @param startIndex the index to start at, invalid index rounded to edge - * @return the last index of the character, or -1 if not found - */ - public int lastIndexOf(char ch, int startIndex) { - startIndex = (startIndex >= size ? size - 1 : startIndex); - if (startIndex < 0) { - return -1; - } - for (int i = startIndex; i >= 0; i--) { - if (buffer[i] == ch) { - return i; - } - } - return -1; - } - - /** - * Searches the string builder to find the last reference to the specified string. - *

    - * Note that a null input string will return -1, whereas the JDK throws an exception. - * - * @param str the string to find, null returns -1 - * @return the last index of the string, or -1 if not found - */ - public int lastIndexOf(String str) { - return lastIndexOf(str, size - 1); - } - - /** - * Searches the string builder to find the last reference to the specified - * string starting searching from the given index. - *

    - * Note that a null input string will return -1, whereas the JDK throws an exception. - * - * @param str the string to find, null returns -1 - * @param startIndex the index to start at, invalid index rounded to edge - * @return the last index of the string, or -1 if not found - */ - public int lastIndexOf(String str, int startIndex) { - startIndex = (startIndex >= size ? size - 1 : startIndex); - if (str == null || startIndex < 0) { - return -1; - } - int strLen = str.length(); - if (strLen > 0 && strLen <= size) { - if (strLen == 1) { - return lastIndexOf(str.charAt(0), startIndex); - } - - outer: - for (int i = startIndex - strLen + 1; i >= 0; i--) { - for (int j = 0; j < strLen; j++) { - if (str.charAt(j) != buffer[i + j]) { - continue outer; - } - } - return i; - } - - } else if (strLen == 0) { - return startIndex; - } - return -1; - } - - /** - * Searches the string builder using the matcher to find the last match. - *

    - * Matchers can be used to perform advanced searching behaviour. - * For example you could write a matcher to find the character 'a' - * followed by a number. - * - * @param matcher the matcher to use, null returns -1 - * @return the last index matched, or -1 if not found - */ - public int lastIndexOf(StrMatcher matcher) { - return lastIndexOf(matcher, size); - } - - /** - * Searches the string builder using the matcher to find the last - * match searching from the given index. - *

    - * Matchers can be used to perform advanced searching behaviour. - * For example you could write a matcher to find the character 'a' - * followed by a number. - * - * @param matcher the matcher to use, null returns -1 - * @param startIndex the index to start at, invalid index rounded to edge - * @return the last index matched, or -1 if not found - */ - public int lastIndexOf(StrMatcher matcher, int startIndex) { - startIndex = (startIndex >= size ? size - 1 : startIndex); - if (matcher == null || startIndex < 0) { - return -1; - } - char[] buf = buffer; - int endIndex = startIndex + 1; - for (int i = startIndex; i >= 0; i--) { - if (matcher.isMatch(buf, i, 0, endIndex) > 0) { - return i; - } - } - return -1; - } - - //----------------------------------------------------------------------- - /** - * Creates a tokenizer that can tokenize the contents of this builder. - *

    - * This method allows the contents of this builder to be tokenized. - * The tokenizer will be setup by default to tokenize on space, tab, - * newline and formfeed (as per StringTokenizer). These values can be - * changed on the tokenizer class, before retrieving the tokens. - *

    - * The returned tokenizer is linked to this builder. You may intermix - * calls to the buider and tokenizer within certain limits, however - * there is no synchronization. Once the tokenizer has been used once, - * it must be {@link StrTokenizer#reset() reset} to pickup the latest - * changes in the builder. For example: - *

    -     * StrBuilder b = new StrBuilder();
    -     * b.append("a b ");
    -     * StrTokenizer t = b.asTokenizer();
    -     * String[] tokens1 = t.getTokenArray();  // returns a,b
    -     * b.append("c d ");
    -     * String[] tokens2 = t.getTokenArray();  // returns a,b (c and d ignored)
    -     * t.reset();              // reset causes builder changes to be picked up
    -     * String[] tokens3 = t.getTokenArray();  // returns a,b,c,d
    -     * 
    - * In addition to simply intermixing appends and tokenization, you can also - * call the set methods on the tokenizer to alter how it tokenizes. Just - * remember to call reset when you want to pickup builder changes. - *

    - * Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])} - * with a non-null value will break the link with the builder. - * - * @return a tokenizer that is linked to this builder - */ - public StrTokenizer asTokenizer() { - return new StrBuilderTokenizer(); - } - - //----------------------------------------------------------------------- - /** - * Gets the contents of this builder as a Reader. - *

    - * This method allows the contents of the builder to be read - * using any standard method that expects a Reader. - *

    - * To use, simply create a StrBuilder, populate it with - * data, call asReader, and then read away. - *

    - * The internal character array is shared between the builder and the reader. - * This allows you to append to the builder after creating the reader, - * and the changes will be picked up. - * Note however, that no synchronization occurs, so you must perform - * all operations with the builder and the reader in one thread. - *

    - * The returned reader supports marking, and ignores the flush method. - * - * @return a reader that reads from this builder - */ - public Reader asReader() { - return new StrBuilderReader(); - } - - //----------------------------------------------------------------------- - /** - * Gets this builder as a Writer that can be written to. - *

    - * This method allows you to populate the contents of the builder - * using any standard method that takes a Writer. - *

    - * To use, simply create a StrBuilder, - * call asWriter, and populate away. The data is available - * at any time using the methods of the StrBuilder. - *

    - * The internal character array is shared between the builder and the writer. - * This allows you to intermix calls that append to the builder and - * write using the writer and the changes will be occur correctly. - * Note however, that no synchronization occurs, so you must perform - * all operations with the builder and the writer in one thread. - *

    - * The returned writer ignores the close and flush methods. - * - * @return a writer that populates this builder - */ - public Writer asWriter() { - return new StrBuilderWriter(); - } - - //----------------------------------------------------------------------- -// /** -// * Gets a String version of the string builder by calling the internal -// * constructor of String by reflection. -// *

    -// * WARNING: You must not use the StrBuilder after calling this method -// * as the buffer is now shared with the String object. To ensure this, -// * the internal character array is set to null, so you will get -// * NullPointerExceptions on all method calls. -// * -// * @return the builder as a String -// */ -// public String toSharedString() { -// try { -// Constructor con = String.class.getDeclaredConstructor( -// new Class[] {int.class, int.class, char[].class}); -// con.setAccessible(true); -// char[] buffer = buf; -// buf = null; -// size = -1; -// nullText = null; -// return (String) con.newInstance( -// new Object[] {Integer.valueOf(0), Integer.valueOf(size), buffer}); -// -// } catch (Exception ex) { -// ex.printStackTrace(); -// throw new UnsupportedOperationException("StrBuilder.toSharedString is unsupported: " + ex.getMessage()); -// } -// } - - //----------------------------------------------------------------------- - /** - * Checks the contents of this builder against another to see if they - * contain the same character content ignoring case. - * - * @param other the object to check, null returns false - * @return true if the builders contain the same characters in the same order - */ - public boolean equalsIgnoreCase(StrBuilder other) { - if (this == other) { - return true; - } - if (this.size != other.size) { - return false; - } - char thisBuf[] = this.buffer; - char otherBuf[] = other.buffer; - for (int i = size - 1; i >= 0; i--) { - char c1 = thisBuf[i]; - char c2 = otherBuf[i]; - if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) { - return false; - } - } - return true; - } - - /** - * Checks the contents of this builder against another to see if they - * contain the same character content. - * - * @param other the object to check, null returns false - * @return true if the builders contain the same characters in the same order - */ - public boolean equals(StrBuilder other) { - if (this == other) { - return true; - } - if (this.size != other.size) { - return false; - } - char thisBuf[] = this.buffer; - char otherBuf[] = other.buffer; - for (int i = size - 1; i >= 0; i--) { - if (thisBuf[i] != otherBuf[i]) { - return false; - } - } - return true; - } - - /** - * Checks the contents of this builder against another to see if they - * contain the same character content. - * - * @param obj the object to check, null returns false - * @return true if the builders contain the same characters in the same order - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof StrBuilder) { - return equals((StrBuilder) obj); - } - return false; - } - - /** - * Gets a suitable hash code for this builder. - * - * @return a hash code - */ - @Override - public int hashCode() { - char buf[] = buffer; - int hash = 0; - for (int i = size - 1; i >= 0; i--) { - hash = 31 * hash + buf[i]; - } - return hash; - } - - //----------------------------------------------------------------------- - /** - * Gets a String version of the string builder, creating a new instance - * each time the method is called. - *

    - * Note that unlike StringBuffer, the string version returned is - * independent of the string builder. - * - * @return the builder as a String - */ - @Override - public String toString() { - return new String(buffer, 0, size); - } - - /** - * Gets a StringBuffer version of the string builder, creating a - * new instance each time the method is called. - * - * @return the builder as a StringBuffer - */ - public StringBuffer toStringBuffer() { - return new StringBuffer(size).append(buffer, 0, size); - } - - //----------------------------------------------------------------------- - /** - * Validates parameters defining a range of the builder. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except - * that if too large it is treated as end of string - * @return the new string - * @throws IndexOutOfBoundsException if the index is invalid - */ - protected int validateRange(int startIndex, int endIndex) { - if (startIndex < 0) { - throw new StringIndexOutOfBoundsException(startIndex); - } - if (endIndex > size) { - endIndex = size; - } - if (startIndex > endIndex) { - throw new StringIndexOutOfBoundsException("end < start"); - } - return endIndex; - } - - /** - * Validates parameters defining a single index in the builder. - * - * @param index the index, must be valid - * @throws IndexOutOfBoundsException if the index is invalid - */ - protected void validateIndex(int index) { - if (index < 0 || index > size) { - throw new StringIndexOutOfBoundsException(index); - } - } - - //----------------------------------------------------------------------- - /** - * Inner class to allow StrBuilder to operate as a tokenizer. - */ - class StrBuilderTokenizer extends StrTokenizer { - - /** - * Default constructor. - */ - StrBuilderTokenizer() { - super(); - } - - /** {@inheritDoc} */ - @Override - protected List tokenize(char[] chars, int offset, int count) { - if (chars == null) { - return super.tokenize(StrBuilder.this.buffer, 0, StrBuilder.this.size()); - } else { - return super.tokenize(chars, offset, count); - } - } - - /** {@inheritDoc} */ - @Override - public String getContent() { - String str = super.getContent(); - if (str == null) { - return StrBuilder.this.toString(); - } else { - return str; - } - } - } - - //----------------------------------------------------------------------- - /** - * Inner class to allow StrBuilder to operate as a writer. - */ - class StrBuilderReader extends Reader { - /** The current stream position. */ - private int pos; - /** The last mark position. */ - private int mark; - - /** - * Default constructor. - */ - StrBuilderReader() { - super(); - } - - /** {@inheritDoc} */ - @Override - public void close() { - // do nothing - } - - /** {@inheritDoc} */ - @Override - public int read() { - if (ready() == false) { - return -1; - } - return StrBuilder.this.charAt(pos++); - } - - /** {@inheritDoc} */ - @Override - public int read(char b[], int off, int len) { - if (off < 0 || len < 0 || off > b.length || - (off + len) > b.length || (off + len) < 0) { - throw new IndexOutOfBoundsException(); - } - if (len == 0) { - return 0; - } - if (pos >= StrBuilder.this.size()) { - return -1; - } - if (pos + len > size()) { - len = StrBuilder.this.size() - pos; - } - StrBuilder.this.getChars(pos, pos + len, b, off); - pos += len; - return len; - } - - /** {@inheritDoc} */ - @Override - public long skip(long n) { - if (pos + n > StrBuilder.this.size()) { - n = StrBuilder.this.size() - pos; - } - if (n < 0) { - return 0; - } - pos += n; - return n; - } - - /** {@inheritDoc} */ - @Override - public boolean ready() { - return pos < StrBuilder.this.size(); - } - - /** {@inheritDoc} */ - @Override - public boolean markSupported() { - return true; - } - - /** {@inheritDoc} */ - @Override - public void mark(int readAheadLimit) { - mark = pos; - } - - /** {@inheritDoc} */ - @Override - public void reset() { - pos = mark; - } - } - - //----------------------------------------------------------------------- - /** - * Inner class to allow StrBuilder to operate as a writer. - */ - class StrBuilderWriter extends Writer { - - /** - * Default constructor. - */ - StrBuilderWriter() { - super(); - } - - /** {@inheritDoc} */ - @Override - public void close() { - // do nothing - } - - /** {@inheritDoc} */ - @Override - public void flush() { - // do nothing - } - - /** {@inheritDoc} */ - @Override - public void write(int c) { - StrBuilder.this.append((char) c); - } - - /** {@inheritDoc} */ - @Override - public void write(char[] cbuf) { - StrBuilder.this.append(cbuf); - } - - /** {@inheritDoc} */ - @Override - public void write(char[] cbuf, int off, int len) { - StrBuilder.this.append(cbuf, off, len); - } - - /** {@inheritDoc} */ - @Override - public void write(String str) { - StrBuilder.this.append(str); - } - - /** {@inheritDoc} */ - @Override - public void write(String str, int off, int len) { - StrBuilder.this.append(str, off, len); - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrLookup.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrLookup.java deleted file mode 100644 index 1dd437b1..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrLookup.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.util.Map; - -/** - * Lookup a String key to a String value. - *

    - * This class represents the simplest form of a string to string map. - * It has a benefit over a map in that it can create the result on - * demand based on the key. - *

    - * This class comes complete with various factory methods. - * If these do not suffice, you can subclass and implement your own matcher. - *

    - * For example, it would be possible to implement a lookup that used the - * key as a primary key, and looked up the value on demand from the database - * - * @since 2.2 - * @version $Id: StrLookup.java 1153484 2011-08-03 13:39:42Z ggregory $ - */ -public abstract class StrLookup { - - /** - * Lookup that always returns null. - */ - private static final StrLookup NONE_LOOKUP; - /** - * Lookup that uses System properties. - */ - private static final StrLookup SYSTEM_PROPERTIES_LOOKUP; - static { - NONE_LOOKUP = new MapStrLookup(null); - StrLookup lookup = null; - try { - final Map propMap = System.getProperties(); - @SuppressWarnings("unchecked") // System property keys and values are always Strings - final Map properties = (Map) propMap; - lookup = new MapStrLookup(properties); - } catch (SecurityException ex) { - lookup = NONE_LOOKUP; - } - SYSTEM_PROPERTIES_LOOKUP = lookup; - } - - //----------------------------------------------------------------------- - /** - * Returns a lookup which always returns null. - * - * @return a lookup that always returns null, not null - */ - public static StrLookup noneLookup() { - return NONE_LOOKUP; - } - - /** - * Returns a lookup which uses {@link System#getProperties() System properties} - * to lookup the key to value. - *

    - * If a security manager blocked access to system properties, then null will - * be returned from every lookup. - *

    - * If a null key is used, this lookup will throw a NullPointerException. - * - * @return a lookup using system properties, not null - */ - public static StrLookup systemPropertiesLookup() { - return SYSTEM_PROPERTIES_LOOKUP; - } - - /** - * Returns a lookup which looks up values using a map. - *

    - * If the map is null, then null will be returned from every lookup. - * The map result object is converted to a string using toString(). - * - * @param the type of the values supported by the lookup - * @param map the map of keys to values, may be null - * @return a lookup using the map, not null - */ - public static StrLookup mapLookup(Map map) { - return new MapStrLookup(map); - } - - //----------------------------------------------------------------------- - /** - * Constructor. - */ - protected StrLookup() { - super(); - } - - /** - * Looks up a String key to a String value. - *

    - * The internal implementation may use any mechanism to return the value. - * The simplest implementation is to use a Map. However, virtually any - * implementation is possible. - *

    - * For example, it would be possible to implement a lookup that used the - * key as a primary key, and looked up the value on demand from the database - * Or, a numeric based implementation could be created that treats the key - * as an integer, increments the value and return the result as a string - - * converting 1 to 2, 15 to 16 etc. - *

    - * The {@link #lookup(String)} method always returns a String, regardless of - * the underlying data, by converting it as necessary. For example: - *

    -     * Map map = new HashMap();
    -     * map.put("number", Integer.valueOf(2));
    -     * assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
    -     * 
    - * @param key the key to be looked up, may be null - * @return the matching value, null if no match - */ - public abstract String lookup(String key); - - //----------------------------------------------------------------------- - /** - * Lookup implementation that uses a Map. - */ - static class MapStrLookup extends StrLookup { - - /** Map keys are variable names and value. */ - private final Map map; - - /** - * Creates a new instance backed by a Map. - * - * @param map the map of keys to values, may be null - */ - MapStrLookup(Map map) { - this.map = map; - } - - /** - * Looks up a String key to a String value using the map. - *

    - * If the map is null, then null is returned. - * The map result object is converted to a string using toString(). - * - * @param key the key to be looked up, may be null - * @return the matching value, null if no match - */ - @Override - public String lookup(String key) { - if (map == null) { - return null; - } - Object obj = map.get(key); - if (obj == null) { - return null; - } - return obj.toString(); - } - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrMatcher.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrMatcher.java deleted file mode 100644 index a6b1d0e5..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrMatcher.java +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.util.Arrays; - -import external.org.apache.commons.lang3.StringUtils; - -/** - * A matcher class that can be queried to determine if a character array - * portion matches. - *

    - * This class comes complete with various factory methods. - * If these do not suffice, you can subclass and implement your own matcher. - * - * @since 2.2 - * @version $Id: StrMatcher.java 1144925 2011-07-10 18:07:05Z ggregory $ - */ -public abstract class StrMatcher { - - /** - * Matches the comma character. - */ - private static final StrMatcher COMMA_MATCHER = new CharMatcher(','); - /** - * Matches the tab character. - */ - private static final StrMatcher TAB_MATCHER = new CharMatcher('\t'); - /** - * Matches the space character. - */ - private static final StrMatcher SPACE_MATCHER = new CharMatcher(' '); - /** - * Matches the same characters as StringTokenizer, - * namely space, tab, newline, formfeed. - */ - private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray()); - /** - * Matches the String trim() whitespace characters. - */ - private static final StrMatcher TRIM_MATCHER = new TrimMatcher(); - /** - * Matches the double quote character. - */ - private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\''); - /** - * Matches the double quote character. - */ - private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"'); - /** - * Matches the single or double quote character. - */ - private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray()); - /** - * Matches no characters. - */ - private static final StrMatcher NONE_MATCHER = new NoMatcher(); - - // ----------------------------------------------------------------------- - - /** - * Returns a matcher which matches the comma character. - * - * @return a matcher for a comma - */ - public static StrMatcher commaMatcher() { - return COMMA_MATCHER; - } - - /** - * Returns a matcher which matches the tab character. - * - * @return a matcher for a tab - */ - public static StrMatcher tabMatcher() { - return TAB_MATCHER; - } - - /** - * Returns a matcher which matches the space character. - * - * @return a matcher for a space - */ - public static StrMatcher spaceMatcher() { - return SPACE_MATCHER; - } - - /** - * Matches the same characters as StringTokenizer, - * namely space, tab, newline and formfeed. - * - * @return the split matcher - */ - public static StrMatcher splitMatcher() { - return SPLIT_MATCHER; - } - - /** - * Matches the String trim() whitespace characters. - * - * @return the trim matcher - */ - public static StrMatcher trimMatcher() { - return TRIM_MATCHER; - } - - /** - * Returns a matcher which matches the single quote character. - * - * @return a matcher for a single quote - */ - public static StrMatcher singleQuoteMatcher() { - return SINGLE_QUOTE_MATCHER; - } - - /** - * Returns a matcher which matches the double quote character. - * - * @return a matcher for a double quote - */ - public static StrMatcher doubleQuoteMatcher() { - return DOUBLE_QUOTE_MATCHER; - } - - /** - * Returns a matcher which matches the single or double quote character. - * - * @return a matcher for a single or double quote - */ - public static StrMatcher quoteMatcher() { - return QUOTE_MATCHER; - } - - /** - * Matches no characters. - * - * @return a matcher that matches nothing - */ - public static StrMatcher noneMatcher() { - return NONE_MATCHER; - } - - /** - * Constructor that creates a matcher from a character. - * - * @param ch the character to match, must not be null - * @return a new Matcher for the given char - */ - public static StrMatcher charMatcher(char ch) { - return new CharMatcher(ch); - } - - /** - * Constructor that creates a matcher from a set of characters. - * - * @param chars the characters to match, null or empty matches nothing - * @return a new matcher for the given char[] - */ - public static StrMatcher charSetMatcher(char... chars) { - if (chars == null || chars.length == 0) { - return NONE_MATCHER; - } - if (chars.length == 1) { - return new CharMatcher(chars[0]); - } - return new CharSetMatcher(chars); - } - - /** - * Constructor that creates a matcher from a string representing a set of characters. - * - * @param chars the characters to match, null or empty matches nothing - * @return a new Matcher for the given characters - */ - public static StrMatcher charSetMatcher(String chars) { - if (chars == null || chars.length() == 0) { - return NONE_MATCHER; - } - if (chars.length() == 1) { - return new CharMatcher(chars.charAt(0)); - } - return new CharSetMatcher(chars.toCharArray()); - } - - /** - * Constructor that creates a matcher from a string. - * - * @param str the string to match, null or empty matches nothing - * @return a new Matcher for the given String - */ - public static StrMatcher stringMatcher(String str) { - if (StringUtils.isEmpty(str)) { - return NONE_MATCHER; - } - return new StringMatcher(str); - } - - //----------------------------------------------------------------------- - /** - * Constructor. - */ - protected StrMatcher() { - super(); - } - - /** - * Returns the number of matching characters, zero for no match. - *

    - * This method is called to check for a match. - * The parameter pos represents the current position to be - * checked in the string buffer (a character array which must - * not be changed). - * The API guarantees that pos is a valid index for buffer. - *

    - * The character array may be larger than the active area to be matched. - * Only values in the buffer between the specifed indices may be accessed. - *

    - * The matching code may check one character or many. - * It may check characters preceeding pos as well as those - * after, so long as no checks exceed the bounds specified. - *

    - * It must return zero for no match, or a positive number if a match was found. - * The number indicates the number of characters that matched. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index (exclusive) of the active buffer, valid for buffer - * @return the number of matching characters, zero for no match - */ - public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd); - - /** - * Returns the number of matching characters, zero for no match. - *

    - * This method is called to check for a match. - * The parameter pos represents the current position to be - * checked in the string buffer (a character array which must - * not be changed). - * The API guarantees that pos is a valid index for buffer. - *

    - * The matching code may check one character or many. - * It may check characters preceeding pos as well as those after. - *

    - * It must return zero for no match, or a positive number if a match was found. - * The number indicates the number of characters that matched. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @return the number of matching characters, zero for no match - * @since 2.4 - */ - public int isMatch(char[] buffer, int pos) { - return isMatch(buffer, pos, 0, buffer.length); - } - - //----------------------------------------------------------------------- - /** - * Class used to define a set of characters for matching purposes. - */ - static final class CharSetMatcher extends StrMatcher { - /** The set of characters to match. */ - private final char[] chars; - - /** - * Constructor that creates a matcher from a character array. - * - * @param chars the characters to match, must not be null - */ - CharSetMatcher(char chars[]) { - super(); - this.chars = chars.clone(); - Arrays.sort(this.chars); - } - - /** - * Returns whether or not the given character matches. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index of the active buffer, valid for buffer - * @return the number of matching characters, zero for no match - */ - @Override - public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { - return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0; - } - } - - //----------------------------------------------------------------------- - /** - * Class used to define a character for matching purposes. - */ - static final class CharMatcher extends StrMatcher { - /** The character to match. */ - private final char ch; - - /** - * Constructor that creates a matcher that matches a single character. - * - * @param ch the character to match - */ - CharMatcher(char ch) { - super(); - this.ch = ch; - } - - /** - * Returns whether or not the given character matches. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index of the active buffer, valid for buffer - * @return the number of matching characters, zero for no match - */ - @Override - public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { - return ch == buffer[pos] ? 1 : 0; - } - } - - //----------------------------------------------------------------------- - /** - * Class used to define a set of characters for matching purposes. - */ - static final class StringMatcher extends StrMatcher { - /** The string to match, as a character array. */ - private final char[] chars; - - /** - * Constructor that creates a matcher from a String. - * - * @param str the string to match, must not be null - */ - StringMatcher(String str) { - super(); - chars = str.toCharArray(); - } - - /** - * Returns whether or not the given text matches the stored string. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index of the active buffer, valid for buffer - * @return the number of matching characters, zero for no match - */ - @Override - public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { - int len = chars.length; - if (pos + len > bufferEnd) { - return 0; - } - for (int i = 0; i < chars.length; i++, pos++) { - if (chars[i] != buffer[pos]) { - return 0; - } - } - return len; - } - } - - //----------------------------------------------------------------------- - /** - * Class used to match no characters. - */ - static final class NoMatcher extends StrMatcher { - - /** - * Constructs a new instance of NoMatcher. - */ - NoMatcher() { - super(); - } - - /** - * Always returns false. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index of the active buffer, valid for buffer - * @return the number of matching characters, zero for no match - */ - @Override - public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { - return 0; - } - } - - //----------------------------------------------------------------------- - /** - * Class used to match whitespace as per trim(). - */ - static final class TrimMatcher extends StrMatcher { - - /** - * Constructs a new instance of TrimMatcher. - */ - TrimMatcher() { - super(); - } - - /** - * Returns whether or not the given character matches. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index of the active buffer, valid for buffer - * @return the number of matching characters, zero for no match - */ - @Override - public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { - return buffer[pos] <= 32 ? 1 : 0; - } - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrSubstitutor.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrSubstitutor.java deleted file mode 100644 index 180acbc2..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrSubstitutor.java +++ /dev/null @@ -1,926 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * Substitutes variables within a string by values. - *

    - * This class takes a piece of text and substitutes all the variables within it. - * The default definition of a variable is ${variableName}. - * The prefix and suffix can be changed via constructors and set methods. - *

    - * Variable values are typically resolved from a map, but could also be resolved - * from system properties, or by supplying a custom variable resolver. - *

    - * The simplest example is to use this class to replace Java System properties. For example: - *

    - * StrSubstitutor.replaceSystemProperties(
    - *      "You are running with java.version = ${java.version} and os.name = ${os.name}.");
    - * 
    - *

    - * Typical usage of this class follows the following pattern: First an instance is created - * and initialized with the map that contains the values for the available variables. - * If a prefix and/or suffix for variables should be used other than the default ones, - * the appropriate settings can be performed. After that the replace() - * method can be called passing in the source text for interpolation. In the returned - * text all variable references (as long as their values are known) will be resolved. - * The following example demonstrates this: - *

    - * Map valuesMap = HashMap();
    - * valuesMap.put("animal", "quick brown fox");
    - * valuesMap.put("target", "lazy dog");
    - * String templateString = "The ${animal} jumped over the ${target}.";
    - * StrSubstitutor sub = new StrSubstitutor(valuesMap);
    - * String resolvedString = sub.replace(templateString);
    - * 
    - * yielding: - *
    - *      The quick brown fox jumped over the lazy dog.
    - * 
    - *

    - * In addition to this usage pattern there are some static convenience methods that - * cover the most common use cases. These methods can be used without the need of - * manually creating an instance. However if multiple replace operations are to be - * performed, creating and reusing an instance of this class will be more efficient. - *

    - * Variable replacement works in a recursive way. Thus, if a variable value contains - * a variable then that variable will also be replaced. Cyclic replacements are - * detected and will cause an exception to be thrown. - *

    - * Sometimes the interpolation's result must contain a variable prefix. As an example - * take the following source text: - *

    - *   The variable ${${name}} must be used.
    - * 
    - * Here only the variable's name referred to in the text should be replaced resulting - * in the text (assuming that the value of the name variable is x): - *
    - *   The variable ${x} must be used.
    - * 
    - * To achieve this effect there are two possibilities: Either set a different prefix - * and suffix for variables which do not conflict with the result text you want to - * produce. The other possibility is to use the escape character, by default '$'. - * If this character is placed before a variable reference, this reference is ignored - * and won't be replaced. For example: - *
    - *   The variable $${${name}} must be used.
    - * 
    - *

    - * In some complex scenarios you might even want to perform substitution in the - * names of variables, for instance - *

    - * ${jre-${java.specification.version}}
    - * 
    - * StrSubstitutor supports this recursive substitution in variable - * names, but it has to be enabled explicitly by setting the - * {@link #setEnableSubstitutionInVariables(boolean) enableSubstitutionInVariables} - * property to true. - * - * @version $Id: StrSubstitutor.java 1199894 2011-11-09 17:53:59Z ggregory $ - * @since 2.2 - */ -public class StrSubstitutor { - - /** - * Constant for the default escape character. - */ - public static final char DEFAULT_ESCAPE = '$'; - /** - * Constant for the default variable prefix. - */ - public static final StrMatcher DEFAULT_PREFIX = StrMatcher.stringMatcher("${"); - /** - * Constant for the default variable suffix. - */ - public static final StrMatcher DEFAULT_SUFFIX = StrMatcher.stringMatcher("}"); - - /** - * Stores the escape character. - */ - private char escapeChar; - /** - * Stores the variable prefix. - */ - private StrMatcher prefixMatcher; - /** - * Stores the variable suffix. - */ - private StrMatcher suffixMatcher; - /** - * Variable resolution is delegated to an implementor of VariableResolver. - */ - private StrLookup variableResolver; - /** - * The flag whether substitution in variable names is enabled. - */ - private boolean enableSubstitutionInVariables; - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables in the given source object with - * their matching values from the map. - * - * @param the type of the values in the map - * @param source the source text containing the variables to substitute, null returns null - * @param valueMap the map with the values, may be null - * @return the result of the replace operation - */ - public static String replace(Object source, Map valueMap) { - return new StrSubstitutor(valueMap).replace(source); - } - - /** - * Replaces all the occurrences of variables in the given source object with - * their matching values from the map. This method allows to specifiy a - * custom variable prefix and suffix - * - * @param the type of the values in the map - * @param source the source text containing the variables to substitute, null returns null - * @param valueMap the map with the values, may be null - * @param prefix the prefix of variables, not null - * @param suffix the suffix of variables, not null - * @return the result of the replace operation - * @throws IllegalArgumentException if the prefix or suffix is null - */ - public static String replace(Object source, Map valueMap, String prefix, String suffix) { - return new StrSubstitutor(valueMap, prefix, suffix).replace(source); - } - - /** - * Replaces all the occurrences of variables in the given source object with their matching - * values from the properties. - * - * @param source the source text containing the variables to substitute, null returns null - * @param valueProperties the properties with values, may be null - * @return the result of the replace operation - */ - public static String replace(Object source, Properties valueProperties) { - if (valueProperties == null) { - return source.toString(); - } - Map valueMap = new HashMap(); - Enumeration propNames = valueProperties.propertyNames(); - while (propNames.hasMoreElements()) { - String propName = (String)propNames.nextElement(); - String propValue = valueProperties.getProperty(propName); - valueMap.put(propName, propValue); - } - return StrSubstitutor.replace(source, valueMap); - } - - /** - * Replaces all the occurrences of variables in the given source object with - * their matching values from the system properties. - * - * @param source the source text containing the variables to substitute, null returns null - * @return the result of the replace operation - */ - public static String replaceSystemProperties(Object source) { - return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source); - } - - //----------------------------------------------------------------------- - /** - * Creates a new instance with defaults for variable prefix and suffix - * and the escaping character. - */ - public StrSubstitutor() { - this((StrLookup) null, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); - } - - /** - * Creates a new instance and initializes it. Uses defaults for variable - * prefix and suffix and the escaping character. - * - * @param the type of the values in the map - * @param valueMap the map with the variables' values, may be null - */ - public StrSubstitutor(Map valueMap) { - this(StrLookup.mapLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); - } - - /** - * Creates a new instance and initializes it. Uses a default escaping character. - * - * @param the type of the values in the map - * @param valueMap the map with the variables' values, may be null - * @param prefix the prefix for variables, not null - * @param suffix the suffix for variables, not null - * @throws IllegalArgumentException if the prefix or suffix is null - */ - public StrSubstitutor(Map valueMap, String prefix, String suffix) { - this(StrLookup.mapLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE); - } - - /** - * Creates a new instance and initializes it. - * - * @param the type of the values in the map - * @param valueMap the map with the variables' values, may be null - * @param prefix the prefix for variables, not null - * @param suffix the suffix for variables, not null - * @param escape the escape character - * @throws IllegalArgumentException if the prefix or suffix is null - */ - public StrSubstitutor(Map valueMap, String prefix, String suffix, char escape) { - this(StrLookup.mapLookup(valueMap), prefix, suffix, escape); - } - - /** - * Creates a new instance and initializes it. - * - * @param variableResolver the variable resolver, may be null - */ - public StrSubstitutor(StrLookup variableResolver) { - this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); - } - - /** - * Creates a new instance and initializes it. - * - * @param variableResolver the variable resolver, may be null - * @param prefix the prefix for variables, not null - * @param suffix the suffix for variables, not null - * @param escape the escape character - * @throws IllegalArgumentException if the prefix or suffix is null - */ - public StrSubstitutor(StrLookup variableResolver, String prefix, String suffix, char escape) { - this.setVariableResolver(variableResolver); - this.setVariablePrefix(prefix); - this.setVariableSuffix(suffix); - this.setEscapeChar(escape); - } - - /** - * Creates a new instance and initializes it. - * - * @param variableResolver the variable resolver, may be null - * @param prefixMatcher the prefix for variables, not null - * @param suffixMatcher the suffix for variables, not null - * @param escape the escape character - * @throws IllegalArgumentException if the prefix or suffix is null - */ - public StrSubstitutor( - StrLookup variableResolver, StrMatcher prefixMatcher, StrMatcher suffixMatcher, char escape) { - this.setVariableResolver(variableResolver); - this.setVariablePrefixMatcher(prefixMatcher); - this.setVariableSuffixMatcher(suffixMatcher); - this.setEscapeChar(escape); - } - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source string as a template. - * - * @param source the string to replace in, null returns null - * @return the result of the replace operation - */ - public String replace(String source) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(source); - if (substitute(buf, 0, source.length()) == false) { - return source; - } - return buf.toString(); - } - - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source string as a template. - *

    - * Only the specified portion of the string will be processed. - * The rest of the string is not processed, and is not returned. - * - * @param source the string to replace in, null returns null - * @param offset the start offset within the array, must be valid - * @param length the length within the array to be processed, must be valid - * @return the result of the replace operation - */ - public String replace(String source, int offset, int length) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(length).append(source, offset, length); - if (substitute(buf, 0, length) == false) { - return source.substring(offset, offset + length); - } - return buf.toString(); - } - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source array as a template. - * The array is not altered by this method. - * - * @param source the character array to replace in, not altered, null returns null - * @return the result of the replace operation - */ - public String replace(char[] source) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(source.length).append(source); - substitute(buf, 0, source.length); - return buf.toString(); - } - - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source array as a template. - * The array is not altered by this method. - *

    - * Only the specified portion of the array will be processed. - * The rest of the array is not processed, and is not returned. - * - * @param source the character array to replace in, not altered, null returns null - * @param offset the start offset within the array, must be valid - * @param length the length within the array to be processed, must be valid - * @return the result of the replace operation - */ - public String replace(char[] source, int offset, int length) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(length).append(source, offset, length); - substitute(buf, 0, length); - return buf.toString(); - } - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source buffer as a template. - * The buffer is not altered by this method. - * - * @param source the buffer to use as a template, not changed, null returns null - * @return the result of the replace operation - */ - public String replace(StringBuffer source) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(source.length()).append(source); - substitute(buf, 0, buf.length()); - return buf.toString(); - } - - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source buffer as a template. - * The buffer is not altered by this method. - *

    - * Only the specified portion of the buffer will be processed. - * The rest of the buffer is not processed, and is not returned. - * - * @param source the buffer to use as a template, not changed, null returns null - * @param offset the start offset within the array, must be valid - * @param length the length within the array to be processed, must be valid - * @return the result of the replace operation - */ - public String replace(StringBuffer source, int offset, int length) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(length).append(source, offset, length); - substitute(buf, 0, length); - return buf.toString(); - } - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source builder as a template. - * The builder is not altered by this method. - * - * @param source the builder to use as a template, not changed, null returns null - * @return the result of the replace operation - */ - public String replace(StrBuilder source) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(source.length()).append(source); - substitute(buf, 0, buf.length()); - return buf.toString(); - } - - /** - * Replaces all the occurrences of variables with their matching values - * from the resolver using the given source builder as a template. - * The builder is not altered by this method. - *

    - * Only the specified portion of the builder will be processed. - * The rest of the builder is not processed, and is not returned. - * - * @param source the builder to use as a template, not changed, null returns null - * @param offset the start offset within the array, must be valid - * @param length the length within the array to be processed, must be valid - * @return the result of the replace operation - */ - public String replace(StrBuilder source, int offset, int length) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder(length).append(source, offset, length); - substitute(buf, 0, length); - return buf.toString(); - } - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables in the given source object with - * their matching values from the resolver. The input source object is - * converted to a string using toString and is not altered. - * - * @param source the source to replace in, null returns null - * @return the result of the replace operation - */ - public String replace(Object source) { - if (source == null) { - return null; - } - StrBuilder buf = new StrBuilder().append(source); - substitute(buf, 0, buf.length()); - return buf.toString(); - } - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables within the given source buffer - * with their matching values from the resolver. - * The buffer is updated with the result. - * - * @param source the buffer to replace in, updated, null returns zero - * @return true if altered - */ - public boolean replaceIn(StringBuffer source) { - if (source == null) { - return false; - } - return replaceIn(source, 0, source.length()); - } - - /** - * Replaces all the occurrences of variables within the given source buffer - * with their matching values from the resolver. - * The buffer is updated with the result. - *

    - * Only the specified portion of the buffer will be processed. - * The rest of the buffer is not processed, but it is not deleted. - * - * @param source the buffer to replace in, updated, null returns zero - * @param offset the start offset within the array, must be valid - * @param length the length within the buffer to be processed, must be valid - * @return true if altered - */ - public boolean replaceIn(StringBuffer source, int offset, int length) { - if (source == null) { - return false; - } - StrBuilder buf = new StrBuilder(length).append(source, offset, length); - if (substitute(buf, 0, length) == false) { - return false; - } - source.replace(offset, offset + length, buf.toString()); - return true; - } - - //----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables within the given source - * builder with their matching values from the resolver. - * - * @param source the builder to replace in, updated, null returns zero - * @return true if altered - */ - public boolean replaceIn(StrBuilder source) { - if (source == null) { - return false; - } - return substitute(source, 0, source.length()); - } - - /** - * Replaces all the occurrences of variables within the given source - * builder with their matching values from the resolver. - *

    - * Only the specified portion of the builder will be processed. - * The rest of the builder is not processed, but it is not deleted. - * - * @param source the builder to replace in, null returns zero - * @param offset the start offset within the array, must be valid - * @param length the length within the builder to be processed, must be valid - * @return true if altered - */ - public boolean replaceIn(StrBuilder source, int offset, int length) { - if (source == null) { - return false; - } - return substitute(source, offset, length); - } - - //----------------------------------------------------------------------- - /** - * Internal method that substitutes the variables. - *

    - * Most users of this class do not need to call this method. This method will - * be called automatically by another (public) method. - *

    - * Writers of subclasses can override this method if they need access to - * the substitution process at the start or end. - * - * @param buf the string builder to substitute into, not null - * @param offset the start offset within the builder, must be valid - * @param length the length within the builder to be processed, must be valid - * @return true if altered - */ - protected boolean substitute(StrBuilder buf, int offset, int length) { - return substitute(buf, offset, length, null) > 0; - } - - /** - * Recursive handler for multiple levels of interpolation. This is the main - * interpolation method, which resolves the values of all variable references - * contained in the passed in text. - * - * @param buf the string builder to substitute into, not null - * @param offset the start offset within the builder, must be valid - * @param length the length within the builder to be processed, must be valid - * @param priorVariables the stack keeping track of the replaced variables, may be null - * @return the length change that occurs, unless priorVariables is null when the int - * represents a boolean flag as to whether any change occurred. - */ - private int substitute(StrBuilder buf, int offset, int length, List priorVariables) { - StrMatcher prefixMatcher = getVariablePrefixMatcher(); - StrMatcher suffixMatcher = getVariableSuffixMatcher(); - char escape = getEscapeChar(); - - boolean top = priorVariables == null; - boolean altered = false; - int lengthChange = 0; - char[] chars = buf.buffer; - int bufEnd = offset + length; - int pos = offset; - while (pos < bufEnd) { - int startMatchLen = prefixMatcher.isMatch(chars, pos, offset, - bufEnd); - if (startMatchLen == 0) { - pos++; - } else { - // found variable start marker - if (pos > offset && chars[pos - 1] == escape) { - // escaped - buf.deleteCharAt(pos - 1); - chars = buf.buffer; // in case buffer was altered - lengthChange--; - altered = true; - bufEnd--; - } else { - // find suffix - int startPos = pos; - pos += startMatchLen; - int endMatchLen = 0; - int nestedVarCount = 0; - while (pos < bufEnd) { - if (isEnableSubstitutionInVariables() - && (endMatchLen = prefixMatcher.isMatch(chars, - pos, offset, bufEnd)) != 0) { - // found a nested variable start - nestedVarCount++; - pos += endMatchLen; - continue; - } - - endMatchLen = suffixMatcher.isMatch(chars, pos, offset, - bufEnd); - if (endMatchLen == 0) { - pos++; - } else { - // found variable end marker - if (nestedVarCount == 0) { - String varName = new String(chars, startPos - + startMatchLen, pos - startPos - - startMatchLen); - if (isEnableSubstitutionInVariables()) { - StrBuilder bufName = new StrBuilder(varName); - substitute(bufName, 0, bufName.length()); - varName = bufName.toString(); - } - pos += endMatchLen; - int endPos = pos; - - // on the first call initialize priorVariables - if (priorVariables == null) { - priorVariables = new ArrayList(); - priorVariables.add(new String(chars, - offset, length)); - } - - // handle cyclic substitution - checkCyclicSubstitution(varName, priorVariables); - priorVariables.add(varName); - - // resolve the variable - String varValue = resolveVariable(varName, buf, - startPos, endPos); - if (varValue != null) { - // recursive replace - int varLen = varValue.length(); - buf.replace(startPos, endPos, varValue); - altered = true; - int change = substitute(buf, startPos, - varLen, priorVariables); - change = change - + varLen - (endPos - startPos); - pos += change; - bufEnd += change; - lengthChange += change; - chars = buf.buffer; // in case buffer was - // altered - } - - // remove variable from the cyclic stack - priorVariables - .remove(priorVariables.size() - 1); - break; - } else { - nestedVarCount--; - pos += endMatchLen; - } - } - } - } - } - } - if (top) { - return altered ? 1 : 0; - } - return lengthChange; - } - - /** - * Checks if the specified variable is already in the stack (list) of variables. - * - * @param varName the variable name to check - * @param priorVariables the list of prior variables - */ - private void checkCyclicSubstitution(String varName, List priorVariables) { - if (priorVariables.contains(varName) == false) { - return; - } - StrBuilder buf = new StrBuilder(256); - buf.append("Infinite loop in property interpolation of "); - buf.append(priorVariables.remove(0)); - buf.append(": "); - buf.appendWithSeparators(priorVariables, "->"); - throw new IllegalStateException(buf.toString()); - } - - /** - * Internal method that resolves the value of a variable. - *

    - * Most users of this class do not need to call this method. This method is - * called automatically by the substitution process. - *

    - * Writers of subclasses can override this method if they need to alter - * how each substitution occurs. The method is passed the variable's name - * and must return the corresponding value. This implementation uses the - * {@link #getVariableResolver()} with the variable's name as the key. - * - * @param variableName the name of the variable, not null - * @param buf the buffer where the substitution is occurring, not null - * @param startPos the start position of the variable including the prefix, valid - * @param endPos the end position of the variable including the suffix, valid - * @return the variable's value or null if the variable is unknown - */ - protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) { - StrLookup resolver = getVariableResolver(); - if (resolver == null) { - return null; - } - return resolver.lookup(variableName); - } - - // Escape - //----------------------------------------------------------------------- - /** - * Returns the escape character. - * - * @return the character used for escaping variable references - */ - public char getEscapeChar() { - return this.escapeChar; - } - - /** - * Sets the escape character. - * If this character is placed before a variable reference in the source - * text, this variable will be ignored. - * - * @param escapeCharacter the escape character (0 for disabling escaping) - */ - public void setEscapeChar(char escapeCharacter) { - this.escapeChar = escapeCharacter; - } - - // Prefix - //----------------------------------------------------------------------- - /** - * Gets the variable prefix matcher currently in use. - *

    - * The variable prefix is the characer or characters that identify the - * start of a variable. This prefix is expressed in terms of a matcher - * allowing advanced prefix matches. - * - * @return the prefix matcher in use - */ - public StrMatcher getVariablePrefixMatcher() { - return prefixMatcher; - } - - /** - * Sets the variable prefix matcher currently in use. - *

    - * The variable prefix is the characer or characters that identify the - * start of a variable. This prefix is expressed in terms of a matcher - * allowing advanced prefix matches. - * - * @param prefixMatcher the prefix matcher to use, null ignored - * @return this, to enable chaining - * @throws IllegalArgumentException if the prefix matcher is null - */ - public StrSubstitutor setVariablePrefixMatcher(StrMatcher prefixMatcher) { - if (prefixMatcher == null) { - throw new IllegalArgumentException("Variable prefix matcher must not be null!"); - } - this.prefixMatcher = prefixMatcher; - return this; - } - - /** - * Sets the variable prefix to use. - *

    - * The variable prefix is the character or characters that identify the - * start of a variable. This method allows a single character prefix to - * be easily set. - * - * @param prefix the prefix character to use - * @return this, to enable chaining - */ - public StrSubstitutor setVariablePrefix(char prefix) { - return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix)); - } - - /** - * Sets the variable prefix to use. - *

    - * The variable prefix is the characer or characters that identify the - * start of a variable. This method allows a string prefix to be easily set. - * - * @param prefix the prefix for variables, not null - * @return this, to enable chaining - * @throws IllegalArgumentException if the prefix is null - */ - public StrSubstitutor setVariablePrefix(String prefix) { - if (prefix == null) { - throw new IllegalArgumentException("Variable prefix must not be null!"); - } - return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix)); - } - - // Suffix - //----------------------------------------------------------------------- - /** - * Gets the variable suffix matcher currently in use. - *

    - * The variable suffix is the characer or characters that identify the - * end of a variable. This suffix is expressed in terms of a matcher - * allowing advanced suffix matches. - * - * @return the suffix matcher in use - */ - public StrMatcher getVariableSuffixMatcher() { - return suffixMatcher; - } - - /** - * Sets the variable suffix matcher currently in use. - *

    - * The variable suffix is the characer or characters that identify the - * end of a variable. This suffix is expressed in terms of a matcher - * allowing advanced suffix matches. - * - * @param suffixMatcher the suffix matcher to use, null ignored - * @return this, to enable chaining - * @throws IllegalArgumentException if the suffix matcher is null - */ - public StrSubstitutor setVariableSuffixMatcher(StrMatcher suffixMatcher) { - if (suffixMatcher == null) { - throw new IllegalArgumentException("Variable suffix matcher must not be null!"); - } - this.suffixMatcher = suffixMatcher; - return this; - } - - /** - * Sets the variable suffix to use. - *

    - * The variable suffix is the characer or characters that identify the - * end of a variable. This method allows a single character suffix to - * be easily set. - * - * @param suffix the suffix character to use - * @return this, to enable chaining - */ - public StrSubstitutor setVariableSuffix(char suffix) { - return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix)); - } - - /** - * Sets the variable suffix to use. - *

    - * The variable suffix is the character or characters that identify the - * end of a variable. This method allows a string suffix to be easily set. - * - * @param suffix the suffix for variables, not null - * @return this, to enable chaining - * @throws IllegalArgumentException if the suffix is null - */ - public StrSubstitutor setVariableSuffix(String suffix) { - if (suffix == null) { - throw new IllegalArgumentException("Variable suffix must not be null!"); - } - return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix)); - } - - // Resolver - //----------------------------------------------------------------------- - /** - * Gets the VariableResolver that is used to lookup variables. - * - * @return the VariableResolver - */ - public StrLookup getVariableResolver() { - return this.variableResolver; - } - - /** - * Sets the VariableResolver that is used to lookup variables. - * - * @param variableResolver the VariableResolver - */ - public void setVariableResolver(StrLookup variableResolver) { - this.variableResolver = variableResolver; - } - - // Substitution support in variable names - //----------------------------------------------------------------------- - /** - * Returns a flag whether substitution is done in variable names. - * - * @return the substitution in variable names flag - * @since 3.0 - */ - public boolean isEnableSubstitutionInVariables() { - return enableSubstitutionInVariables; - } - - /** - * Sets a flag whether substitution is done in variable names. If set to - * true, the names of variables can contain other variables which are - * processed first before the original variable is evaluated, e.g. - * ${jre-${java.version}}. The default value is false. - * - * @param enableSubstitutionInVariables the new value of the flag - * @since 3.0 - */ - public void setEnableSubstitutionInVariables( - boolean enableSubstitutionInVariables) { - this.enableSubstitutionInVariables = enableSubstitutionInVariables; - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrTokenizer.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrTokenizer.java deleted file mode 100644 index dc3a3f6c..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/StrTokenizer.java +++ /dev/null @@ -1,1104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -import external.org.apache.commons.lang3.ArrayUtils; - -/** - * Tokenizes a string based based on delimiters (separators) - * and supporting quoting and ignored character concepts. - *

    - * This class can split a String into many smaller strings. It aims - * to do a similar job to {@link java.util.StringTokenizer StringTokenizer}, - * however it offers much more control and flexibility including implementing - * the ListIterator interface. By default, it is set up - * like StringTokenizer. - *

    - * The input String is split into a number of tokens. - * Each token is separated from the next String by a delimiter. - * One or more delimiter characters must be specified. - *

    - * Each token may be surrounded by quotes. - * The quote matcher specifies the quote character(s). - * A quote may be escaped within a quoted section by duplicating itself. - *

    - * Between each token and the delimiter are potentially characters that need trimming. - * The trimmer matcher specifies these characters. - * One usage might be to trim whitespace characters. - *

    - * At any point outside the quotes there might potentially be invalid characters. - * The ignored matcher specifies these characters to be removed. - * One usage might be to remove new line characters. - *

    - * Empty tokens may be removed or returned as null. - *

    - * "a,b,c"         - Three tokens "a","b","c"   (comma delimiter)
    - * " a, b , c "    - Three tokens "a","b","c"   (default CSV processing trims whitespace)
    - * "a, ", b ,", c" - Three tokens "a, " , " b ", ", c" (quoted text untouched)
    - * 
    - *

    - * - * This tokenizer has the following properties and options: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
    PropertyTypeDefault
    delimCharSetMatcher{ \t\n\r\f}
    quoteNoneMatcher{}
    ignoreNoneMatcher{}
    emptyTokenAsNullbooleanfalse
    ignoreEmptyTokensbooleantrue
    - * - * @since 2.2 - * @version $Id: StrTokenizer.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class StrTokenizer implements ListIterator, Cloneable { - - private static final StrTokenizer CSV_TOKENIZER_PROTOTYPE; - private static final StrTokenizer TSV_TOKENIZER_PROTOTYPE; - static { - CSV_TOKENIZER_PROTOTYPE = new StrTokenizer(); - CSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.commaMatcher()); - CSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); - CSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher()); - CSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher()); - CSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false); - CSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false); - - TSV_TOKENIZER_PROTOTYPE = new StrTokenizer(); - TSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.tabMatcher()); - TSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); - TSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher()); - TSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher()); - TSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false); - TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false); - } - - /** The text to work on. */ - private char chars[]; - /** The parsed tokens */ - private String tokens[]; - /** The current iteration position */ - private int tokenPos; - - /** The delimiter matcher */ - private StrMatcher delimMatcher = StrMatcher.splitMatcher(); - /** The quote matcher */ - private StrMatcher quoteMatcher = StrMatcher.noneMatcher(); - /** The ignored matcher */ - private StrMatcher ignoredMatcher = StrMatcher.noneMatcher(); - /** The trimmer matcher */ - private StrMatcher trimmerMatcher = StrMatcher.noneMatcher(); - - /** Whether to return empty tokens as null */ - private boolean emptyAsNull = false; - /** Whether to ignore empty tokens */ - private boolean ignoreEmptyTokens = true; - - //----------------------------------------------------------------------- - - /** - * Returns a clone of CSV_TOKENIZER_PROTOTYPE. - * - * @return a clone of CSV_TOKENIZER_PROTOTYPE. - */ - private static StrTokenizer getCSVClone() { - return (StrTokenizer) CSV_TOKENIZER_PROTOTYPE.clone(); - } - - /** - * Gets a new tokenizer instance which parses Comma Separated Value strings - * initializing it with the given input. The default for CSV processing - * will be trim whitespace from both ends (which can be overridden with - * the setTrimmer method). - *

    - * You must call a "reset" method to set the string which you want to parse. - * @return a new tokenizer instance which parses Comma Separated Value strings - */ - public static StrTokenizer getCSVInstance() { - return getCSVClone(); - } - - /** - * Gets a new tokenizer instance which parses Comma Separated Value strings - * initializing it with the given input. The default for CSV processing - * will be trim whitespace from both ends (which can be overridden with - * the setTrimmer method). - * - * @param input the text to parse - * @return a new tokenizer instance which parses Comma Separated Value strings - */ - public static StrTokenizer getCSVInstance(String input) { - StrTokenizer tok = getCSVClone(); - tok.reset(input); - return tok; - } - - /** - * Gets a new tokenizer instance which parses Comma Separated Value strings - * initializing it with the given input. The default for CSV processing - * will be trim whitespace from both ends (which can be overridden with - * the setTrimmer method). - * - * @param input the text to parse - * @return a new tokenizer instance which parses Comma Separated Value strings - */ - public static StrTokenizer getCSVInstance(char[] input) { - StrTokenizer tok = getCSVClone(); - tok.reset(input); - return tok; - } - - /** - * Returns a clone of TSV_TOKENIZER_PROTOTYPE. - * - * @return a clone of TSV_TOKENIZER_PROTOTYPE. - */ - private static StrTokenizer getTSVClone() { - return (StrTokenizer) TSV_TOKENIZER_PROTOTYPE.clone(); - } - - - /** - * Gets a new tokenizer instance which parses Tab Separated Value strings. - * The default for CSV processing will be trim whitespace from both ends - * (which can be overridden with the setTrimmer method). - *

    - * You must call a "reset" method to set the string which you want to parse. - * @return a new tokenizer instance which parses Tab Separated Value strings. - */ - public static StrTokenizer getTSVInstance() { - return getTSVClone(); - } - - /** - * Gets a new tokenizer instance which parses Tab Separated Value strings. - * The default for CSV processing will be trim whitespace from both ends - * (which can be overridden with the setTrimmer method). - * @param input the string to parse - * @return a new tokenizer instance which parses Tab Separated Value strings. - */ - public static StrTokenizer getTSVInstance(String input) { - StrTokenizer tok = getTSVClone(); - tok.reset(input); - return tok; - } - - /** - * Gets a new tokenizer instance which parses Tab Separated Value strings. - * The default for CSV processing will be trim whitespace from both ends - * (which can be overridden with the setTrimmer method). - * @param input the string to parse - * @return a new tokenizer instance which parses Tab Separated Value strings. - */ - public static StrTokenizer getTSVInstance(char[] input) { - StrTokenizer tok = getTSVClone(); - tok.reset(input); - return tok; - } - - //----------------------------------------------------------------------- - /** - * Constructs a tokenizer splitting on space, tab, newline and formfeed - * as per StringTokenizer, but with no text to tokenize. - *

    - * This constructor is normally used with {@link #reset(String)}. - */ - public StrTokenizer() { - super(); - this.chars = null; - } - - /** - * Constructs a tokenizer splitting on space, tab, newline and formfeed - * as per StringTokenizer. - * - * @param input the string which is to be parsed - */ - public StrTokenizer(String input) { - super(); - if (input != null) { - chars = input.toCharArray(); - } else { - chars = null; - } - } - - /** - * Constructs a tokenizer splitting on the specified delimiter character. - * - * @param input the string which is to be parsed - * @param delim the field delimiter character - */ - public StrTokenizer(String input, char delim) { - this(input); - setDelimiterChar(delim); - } - - /** - * Constructs a tokenizer splitting on the specified delimiter string. - * - * @param input the string which is to be parsed - * @param delim the field delimiter string - */ - public StrTokenizer(String input, String delim) { - this(input); - setDelimiterString(delim); - } - - /** - * Constructs a tokenizer splitting using the specified delimiter matcher. - * - * @param input the string which is to be parsed - * @param delim the field delimiter matcher - */ - public StrTokenizer(String input, StrMatcher delim) { - this(input); - setDelimiterMatcher(delim); - } - - /** - * Constructs a tokenizer splitting on the specified delimiter character - * and handling quotes using the specified quote character. - * - * @param input the string which is to be parsed - * @param delim the field delimiter character - * @param quote the field quoted string character - */ - public StrTokenizer(String input, char delim, char quote) { - this(input, delim); - setQuoteChar(quote); - } - - /** - * Constructs a tokenizer splitting using the specified delimiter matcher - * and handling quotes using the specified quote matcher. - * - * @param input the string which is to be parsed - * @param delim the field delimiter matcher - * @param quote the field quoted string matcher - */ - public StrTokenizer(String input, StrMatcher delim, StrMatcher quote) { - this(input, delim); - setQuoteMatcher(quote); - } - - /** - * Constructs a tokenizer splitting on space, tab, newline and formfeed - * as per StringTokenizer. - * - * @param input the string which is to be parsed, not cloned - */ - public StrTokenizer(char[] input) { - super(); - this.chars = ArrayUtils.clone(input); - } - - /** - * Constructs a tokenizer splitting on the specified character. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter character - */ - public StrTokenizer(char[] input, char delim) { - this(input); - setDelimiterChar(delim); - } - - /** - * Constructs a tokenizer splitting on the specified string. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter string - */ - public StrTokenizer(char[] input, String delim) { - this(input); - setDelimiterString(delim); - } - - /** - * Constructs a tokenizer splitting using the specified delimiter matcher. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter matcher - */ - public StrTokenizer(char[] input, StrMatcher delim) { - this(input); - setDelimiterMatcher(delim); - } - - /** - * Constructs a tokenizer splitting on the specified delimiter character - * and handling quotes using the specified quote character. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter character - * @param quote the field quoted string character - */ - public StrTokenizer(char[] input, char delim, char quote) { - this(input, delim); - setQuoteChar(quote); - } - - /** - * Constructs a tokenizer splitting using the specified delimiter matcher - * and handling quotes using the specified quote matcher. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter character - * @param quote the field quoted string character - */ - public StrTokenizer(char[] input, StrMatcher delim, StrMatcher quote) { - this(input, delim); - setQuoteMatcher(quote); - } - - // API - //----------------------------------------------------------------------- - /** - * Gets the number of tokens found in the String. - * - * @return the number of matched tokens - */ - public int size() { - checkTokenized(); - return tokens.length; - } - - /** - * Gets the next token from the String. - * Equivalent to {@link #next()} except it returns null rather than - * throwing {@link NoSuchElementException} when no tokens remain. - * - * @return the next sequential token, or null when no more tokens are found - */ - public String nextToken() { - if (hasNext()) { - return tokens[tokenPos++]; - } - return null; - } - - /** - * Gets the previous token from the String. - * - * @return the previous sequential token, or null when no more tokens are found - */ - public String previousToken() { - if (hasPrevious()) { - return tokens[--tokenPos]; - } - return null; - } - - /** - * Gets a copy of the full token list as an independent modifiable array. - * - * @return the tokens as a String array - */ - public String[] getTokenArray() { - checkTokenized(); - return tokens.clone(); - } - - /** - * Gets a copy of the full token list as an independent modifiable list. - * - * @return the tokens as a String array - */ - public List getTokenList() { - checkTokenized(); - List list = new ArrayList(tokens.length); - for (String element : tokens) { - list.add(element); - } - return list; - } - - /** - * Resets this tokenizer, forgetting all parsing and iteration already completed. - *

    - * This method allows the same tokenizer to be reused for the same String. - * - * @return this, to enable chaining - */ - public StrTokenizer reset() { - tokenPos = 0; - tokens = null; - return this; - } - - /** - * Reset this tokenizer, giving it a new input string to parse. - * In this manner you can re-use a tokenizer with the same settings - * on multiple input lines. - * - * @param input the new string to tokenize, null sets no text to parse - * @return this, to enable chaining - */ - public StrTokenizer reset(String input) { - reset(); - if (input != null) { - this.chars = input.toCharArray(); - } else { - this.chars = null; - } - return this; - } - - /** - * Reset this tokenizer, giving it a new input string to parse. - * In this manner you can re-use a tokenizer with the same settings - * on multiple input lines. - * - * @param input the new character array to tokenize, not cloned, null sets no text to parse - * @return this, to enable chaining - */ - public StrTokenizer reset(char[] input) { - reset(); - this.chars = ArrayUtils.clone(input); - return this; - } - - // ListIterator - //----------------------------------------------------------------------- - /** - * Checks whether there are any more tokens. - * - * @return true if there are more tokens - */ - public boolean hasNext() { - checkTokenized(); - return tokenPos < tokens.length; - } - - /** - * Gets the next token. - * - * @return the next String token - * @throws NoSuchElementException if there are no more elements - */ - public String next() { - if (hasNext()) { - return tokens[tokenPos++]; - } - throw new NoSuchElementException(); - } - - /** - * Gets the index of the next token to return. - * - * @return the next token index - */ - public int nextIndex() { - return tokenPos; - } - - /** - * Checks whether there are any previous tokens that can be iterated to. - * - * @return true if there are previous tokens - */ - public boolean hasPrevious() { - checkTokenized(); - return tokenPos > 0; - } - - /** - * Gets the token previous to the last returned token. - * - * @return the previous token - */ - public String previous() { - if (hasPrevious()) { - return tokens[--tokenPos]; - } - throw new NoSuchElementException(); - } - - /** - * Gets the index of the previous token. - * - * @return the previous token index - */ - public int previousIndex() { - return tokenPos - 1; - } - - /** - * Unsupported ListIterator operation. - * - * @throws UnsupportedOperationException always - */ - public void remove() { - throw new UnsupportedOperationException("remove() is unsupported"); - } - - /** - * Unsupported ListIterator operation. - * @param obj this parameter ignored. - * @throws UnsupportedOperationException always - */ - public void set(String obj) { - throw new UnsupportedOperationException("set() is unsupported"); - } - - /** - * Unsupported ListIterator operation. - * @param obj this parameter ignored. - * @throws UnsupportedOperationException always - */ - public void add(String obj) { - throw new UnsupportedOperationException("add() is unsupported"); - } - - // Implementation - //----------------------------------------------------------------------- - /** - * Checks if tokenization has been done, and if not then do it. - */ - private void checkTokenized() { - if (tokens == null) { - if (chars == null) { - // still call tokenize as subclass may do some work - List split = tokenize(null, 0, 0); - tokens = split.toArray(new String[split.size()]); - } else { - List split = tokenize(chars, 0, chars.length); - tokens = split.toArray(new String[split.size()]); - } - } - } - - /** - * Internal method to performs the tokenization. - *

    - * Most users of this class do not need to call this method. This method - * will be called automatically by other (public) methods when required. - *

    - * This method exists to allow subclasses to add code before or after the - * tokenization. For example, a subclass could alter the character array, - * offset or count to be parsed, or call the tokenizer multiple times on - * multiple strings. It is also be possible to filter the results. - *

    - * StrTokenizer will always pass a zero offset and a count - * equal to the length of the array to this method, however a subclass - * may pass other values, or even an entirely different array. - * - * @param chars the character array being tokenized, may be null - * @param offset the start position within the character array, must be valid - * @param count the number of characters to tokenize, must be valid - * @return the modifiable list of String tokens, unmodifiable if null array or zero count - */ - protected List tokenize(char[] chars, int offset, int count) { - if (chars == null || count == 0) { - return Collections.emptyList(); - } - StrBuilder buf = new StrBuilder(); - List tokens = new ArrayList(); - int pos = offset; - - // loop around the entire buffer - while (pos >= 0 && pos < count) { - // find next token - pos = readNextToken(chars, pos, count, buf, tokens); - - // handle case where end of string is a delimiter - if (pos >= count) { - addToken(tokens, ""); - } - } - return tokens; - } - - /** - * Adds a token to a list, paying attention to the parameters we've set. - * - * @param list the list to add to - * @param tok the token to add - */ - private void addToken(List list, String tok) { - if (tok == null || tok.length() == 0) { - if (isIgnoreEmptyTokens()) { - return; - } - if (isEmptyTokenAsNull()) { - tok = null; - } - } - list.add(tok); - } - - /** - * Reads character by character through the String to get the next token. - * - * @param chars the character array being tokenized - * @param start the first character of field - * @param len the length of the character array being tokenized - * @param workArea a temporary work area - * @param tokens the list of parsed tokens - * @return the starting position of the next field (the character - * immediately after the delimiter), or -1 if end of string found - */ - private int readNextToken(char[] chars, int start, int len, StrBuilder workArea, List tokens) { - // skip all leading whitespace, unless it is the - // field delimiter or the quote character - while (start < len) { - int removeLen = Math.max( - getIgnoredMatcher().isMatch(chars, start, start, len), - getTrimmerMatcher().isMatch(chars, start, start, len)); - if (removeLen == 0 || - getDelimiterMatcher().isMatch(chars, start, start, len) > 0 || - getQuoteMatcher().isMatch(chars, start, start, len) > 0) { - break; - } - start += removeLen; - } - - // handle reaching end - if (start >= len) { - addToken(tokens, ""); - return -1; - } - - // handle empty token - int delimLen = getDelimiterMatcher().isMatch(chars, start, start, len); - if (delimLen > 0) { - addToken(tokens, ""); - return start + delimLen; - } - - // handle found token - int quoteLen = getQuoteMatcher().isMatch(chars, start, start, len); - if (quoteLen > 0) { - return readWithQuotes(chars, start + quoteLen, len, workArea, tokens, start, quoteLen); - } - return readWithQuotes(chars, start, len, workArea, tokens, 0, 0); - } - - /** - * Reads a possibly quoted string token. - * - * @param chars the character array being tokenized - * @param start the first character of field - * @param len the length of the character array being tokenized - * @param workArea a temporary work area - * @param tokens the list of parsed tokens - * @param quoteStart the start position of the matched quote, 0 if no quoting - * @param quoteLen the length of the matched quote, 0 if no quoting - * @return the starting position of the next field (the character - * immediately after the delimiter, or if end of string found, - * then the length of string - */ - private int readWithQuotes(char[] chars, int start, int len, StrBuilder workArea, - List tokens, int quoteStart, int quoteLen) { - // Loop until we've found the end of the quoted - // string or the end of the input - workArea.clear(); - int pos = start; - boolean quoting = quoteLen > 0; - int trimStart = 0; - - while (pos < len) { - // quoting mode can occur several times throughout a string - // we must switch between quoting and non-quoting until we - // encounter a non-quoted delimiter, or end of string - if (quoting) { - // In quoting mode - - // If we've found a quote character, see if it's - // followed by a second quote. If so, then we need - // to actually put the quote character into the token - // rather than end the token. - if (isQuote(chars, pos, len, quoteStart, quoteLen)) { - if (isQuote(chars, pos + quoteLen, len, quoteStart, quoteLen)) { - // matched pair of quotes, thus an escaped quote - workArea.append(chars, pos, quoteLen); - pos += quoteLen * 2; - trimStart = workArea.size(); - continue; - } - - // end of quoting - quoting = false; - pos += quoteLen; - continue; - } - - // copy regular character from inside quotes - workArea.append(chars[pos++]); - trimStart = workArea.size(); - - } else { - // Not in quoting mode - - // check for delimiter, and thus end of token - int delimLen = getDelimiterMatcher().isMatch(chars, pos, start, len); - if (delimLen > 0) { - // return condition when end of token found - addToken(tokens, workArea.substring(0, trimStart)); - return pos + delimLen; - } - - // check for quote, and thus back into quoting mode - if (quoteLen > 0 && isQuote(chars, pos, len, quoteStart, quoteLen)) { - quoting = true; - pos += quoteLen; - continue; - } - - // check for ignored (outside quotes), and ignore - int ignoredLen = getIgnoredMatcher().isMatch(chars, pos, start, len); - if (ignoredLen > 0) { - pos += ignoredLen; - continue; - } - - // check for trimmed character - // don't yet know if its at the end, so copy to workArea - // use trimStart to keep track of trim at the end - int trimmedLen = getTrimmerMatcher().isMatch(chars, pos, start, len); - if (trimmedLen > 0) { - workArea.append(chars, pos, trimmedLen); - pos += trimmedLen; - continue; - } - - // copy regular character from outside quotes - workArea.append(chars[pos++]); - trimStart = workArea.size(); - } - } - - // return condition when end of string found - addToken(tokens, workArea.substring(0, trimStart)); - return -1; - } - - /** - * Checks if the characters at the index specified match the quote - * already matched in readNextToken(). - * - * @param chars the character array being tokenized - * @param pos the position to check for a quote - * @param len the length of the character array being tokenized - * @param quoteStart the start position of the matched quote, 0 if no quoting - * @param quoteLen the length of the matched quote, 0 if no quoting - * @return true if a quote is matched - */ - private boolean isQuote(char[] chars, int pos, int len, int quoteStart, int quoteLen) { - for (int i = 0; i < quoteLen; i++) { - if (pos + i >= len || chars[pos + i] != chars[quoteStart + i]) { - return false; - } - } - return true; - } - - // Delimiter - //----------------------------------------------------------------------- - /** - * Gets the field delimiter matcher. - * - * @return the delimiter matcher in use - */ - public StrMatcher getDelimiterMatcher() { - return this.delimMatcher; - } - - /** - * Sets the field delimiter matcher. - *

    - * The delimitier is used to separate one token from another. - * - * @param delim the delimiter matcher to use - * @return this, to enable chaining - */ - public StrTokenizer setDelimiterMatcher(StrMatcher delim) { - if (delim == null) { - this.delimMatcher = StrMatcher.noneMatcher(); - } else { - this.delimMatcher = delim; - } - return this; - } - - /** - * Sets the field delimiter character. - * - * @param delim the delimiter character to use - * @return this, to enable chaining - */ - public StrTokenizer setDelimiterChar(char delim) { - return setDelimiterMatcher(StrMatcher.charMatcher(delim)); - } - - /** - * Sets the field delimiter string. - * - * @param delim the delimiter string to use - * @return this, to enable chaining - */ - public StrTokenizer setDelimiterString(String delim) { - return setDelimiterMatcher(StrMatcher.stringMatcher(delim)); - } - - // Quote - //----------------------------------------------------------------------- - /** - * Gets the quote matcher currently in use. - *

    - * The quote character is used to wrap data between the tokens. - * This enables delimiters to be entered as data. - * The default value is '"' (double quote). - * - * @return the quote matcher in use - */ - public StrMatcher getQuoteMatcher() { - return quoteMatcher; - } - - /** - * Set the quote matcher to use. - *

    - * The quote character is used to wrap data between the tokens. - * This enables delimiters to be entered as data. - * - * @param quote the quote matcher to use, null ignored - * @return this, to enable chaining - */ - public StrTokenizer setQuoteMatcher(StrMatcher quote) { - if (quote != null) { - this.quoteMatcher = quote; - } - return this; - } - - /** - * Sets the quote character to use. - *

    - * The quote character is used to wrap data between the tokens. - * This enables delimiters to be entered as data. - * - * @param quote the quote character to use - * @return this, to enable chaining - */ - public StrTokenizer setQuoteChar(char quote) { - return setQuoteMatcher(StrMatcher.charMatcher(quote)); - } - - // Ignored - //----------------------------------------------------------------------- - /** - * Gets the ignored character matcher. - *

    - * These characters are ignored when parsing the String, unless they are - * within a quoted region. - * The default value is not to ignore anything. - * - * @return the ignored matcher in use - */ - public StrMatcher getIgnoredMatcher() { - return ignoredMatcher; - } - - /** - * Set the matcher for characters to ignore. - *

    - * These characters are ignored when parsing the String, unless they are - * within a quoted region. - * - * @param ignored the ignored matcher to use, null ignored - * @return this, to enable chaining - */ - public StrTokenizer setIgnoredMatcher(StrMatcher ignored) { - if (ignored != null) { - this.ignoredMatcher = ignored; - } - return this; - } - - /** - * Set the character to ignore. - *

    - * This character is ignored when parsing the String, unless it is - * within a quoted region. - * - * @param ignored the ignored character to use - * @return this, to enable chaining - */ - public StrTokenizer setIgnoredChar(char ignored) { - return setIgnoredMatcher(StrMatcher.charMatcher(ignored)); - } - - // Trimmer - //----------------------------------------------------------------------- - /** - * Gets the trimmer character matcher. - *

    - * These characters are trimmed off on each side of the delimiter - * until the token or quote is found. - * The default value is not to trim anything. - * - * @return the trimmer matcher in use - */ - public StrMatcher getTrimmerMatcher() { - return trimmerMatcher; - } - - /** - * Sets the matcher for characters to trim. - *

    - * These characters are trimmed off on each side of the delimiter - * until the token or quote is found. - * - * @param trimmer the trimmer matcher to use, null ignored - * @return this, to enable chaining - */ - public StrTokenizer setTrimmerMatcher(StrMatcher trimmer) { - if (trimmer != null) { - this.trimmerMatcher = trimmer; - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets whether the tokenizer currently returns empty tokens as null. - * The default for this property is false. - * - * @return true if empty tokens are returned as null - */ - public boolean isEmptyTokenAsNull() { - return this.emptyAsNull; - } - - /** - * Sets whether the tokenizer should return empty tokens as null. - * The default for this property is false. - * - * @param emptyAsNull whether empty tokens are returned as null - * @return this, to enable chaining - */ - public StrTokenizer setEmptyTokenAsNull(boolean emptyAsNull) { - this.emptyAsNull = emptyAsNull; - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets whether the tokenizer currently ignores empty tokens. - * The default for this property is true. - * - * @return true if empty tokens are not returned - */ - public boolean isIgnoreEmptyTokens() { - return ignoreEmptyTokens; - } - - /** - * Sets whether the tokenizer should ignore and not return empty tokens. - * The default for this property is true. - * - * @param ignoreEmptyTokens whether empty tokens are not returned - * @return this, to enable chaining - */ - public StrTokenizer setIgnoreEmptyTokens(boolean ignoreEmptyTokens) { - this.ignoreEmptyTokens = ignoreEmptyTokens; - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets the String content that the tokenizer is parsing. - * - * @return the string content being parsed - */ - public String getContent() { - if (chars == null) { - return null; - } - return new String(chars); - } - - //----------------------------------------------------------------------- - /** - * Creates a new instance of this Tokenizer. The new instance is reset so - * that it will be at the start of the token list. - * If a {@link CloneNotSupportedException} is caught, return null. - * - * @return a new instance of this Tokenizer which has been reset. - */ - @Override - public Object clone() { - try { - return cloneReset(); - } catch (CloneNotSupportedException ex) { - return null; - } - } - - /** - * Creates a new instance of this Tokenizer. The new instance is reset so that - * it will be at the start of the token list. - * - * @return a new instance of this Tokenizer which has been reset. - * @throws CloneNotSupportedException if there is a problem cloning - */ - Object cloneReset() throws CloneNotSupportedException { - // this method exists to enable 100% test coverage - StrTokenizer cloned = (StrTokenizer) super.clone(); - if (cloned.chars != null) { - cloned.chars = cloned.chars.clone(); - } - cloned.reset(); - return cloned; - } - - //----------------------------------------------------------------------- - /** - * Gets the String content that the tokenizer is parsing. - * - * @return the string content being parsed - */ - @Override - public String toString() { - if (tokens == null) { - return "StrTokenizer[not tokenized yet]"; - } - return "StrTokenizer" + getTokenList(); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/WordUtils.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/WordUtils.java deleted file mode 100644 index 9c4d75f3..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/WordUtils.java +++ /dev/null @@ -1,497 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text; - -import external.org.apache.commons.lang3.StringUtils; -import external.org.apache.commons.lang3.SystemUtils; - -/** - *

    Operations on Strings that contain words.

    - * - *

    This class tries to handle null input gracefully. - * An exception will not be thrown for a null input. - * Each method documents its behaviour in more detail.

    - * - * @since 2.0 - * @version $Id: WordUtils.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class WordUtils { - - /** - *

    WordUtils instances should NOT be constructed in - * standard programming. Instead, the class should be used as - * WordUtils.wrap("foo bar", 20);.

    - * - *

    This constructor is public to permit tools that require a JavaBean - * instance to operate.

    - */ - public WordUtils() { - super(); - } - - // Wrapping - //-------------------------------------------------------------------------- - /** - *

    Wraps a single line of text, identifying words by ' '.

    - * - *

    New lines will be separated by the system property line separator. - * Very long words, such as URLs will not be wrapped.

    - * - *

    Leading spaces on a new line are stripped. - * Trailing spaces are not stripped.

    - * - *
    -     * WordUtils.wrap(null, *) = null
    -     * WordUtils.wrap("", *) = ""
    -     * 
    - * - * @param str the String to be word wrapped, may be null - * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 - * @return a line with newlines inserted, null if null input - */ - public static String wrap(String str, int wrapLength) { - return wrap(str, wrapLength, null, false); - } - - /** - *

    Wraps a single line of text, identifying words by ' '.

    - * - *

    Leading spaces on a new line are stripped. - * Trailing spaces are not stripped.

    - * - *
    -     * WordUtils.wrap(null, *, *, *) = null
    -     * WordUtils.wrap("", *, *, *) = ""
    -     * 
    - * - * @param str the String to be word wrapped, may be null - * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 - * @param newLineStr the string to insert for a new line, - * null uses the system property line separator - * @param wrapLongWords true if long words (such as URLs) should be wrapped - * @return a line with newlines inserted, null if null input - */ - public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) { - if (str == null) { - return null; - } - if (newLineStr == null) { - newLineStr = SystemUtils.LINE_SEPARATOR; - } - if (wrapLength < 1) { - wrapLength = 1; - } - int inputLineLength = str.length(); - int offset = 0; - StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32); - - while (inputLineLength - offset > wrapLength) { - if (str.charAt(offset) == ' ') { - offset++; - continue; - } - int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset); - - if (spaceToWrapAt >= offset) { - // normal case - wrappedLine.append(str.substring(offset, spaceToWrapAt)); - wrappedLine.append(newLineStr); - offset = spaceToWrapAt + 1; - - } else { - // really long word or URL - if (wrapLongWords) { - // wrap really long word one line at a time - wrappedLine.append(str.substring(offset, wrapLength + offset)); - wrappedLine.append(newLineStr); - offset += wrapLength; - } else { - // do not wrap really long word, just extend beyond limit - spaceToWrapAt = str.indexOf(' ', wrapLength + offset); - if (spaceToWrapAt >= 0) { - wrappedLine.append(str.substring(offset, spaceToWrapAt)); - wrappedLine.append(newLineStr); - offset = spaceToWrapAt + 1; - } else { - wrappedLine.append(str.substring(offset)); - offset = inputLineLength; - } - } - } - } - - // Whatever is left in line is short enough to just pass through - wrappedLine.append(str.substring(offset)); - - return wrappedLine.toString(); - } - - // Capitalizing - //----------------------------------------------------------------------- - /** - *

    Capitalizes all the whitespace separated words in a String. - * Only the first letter of each word is changed. To convert the - * rest of each word to lowercase at the same time, - * use {@link #capitalizeFully(String)}.

    - * - *

    Whitespace is defined by {@link Character#isWhitespace(char)}. - * A null input String returns null. - * Capitalization uses the Unicode title case, normally equivalent to - * upper case.

    - * - *
    -     * WordUtils.capitalize(null)        = null
    -     * WordUtils.capitalize("")          = ""
    -     * WordUtils.capitalize("i am FINE") = "I Am FINE"
    -     * 
    - * - * @param str the String to capitalize, may be null - * @return capitalized String, null if null String input - * @see #uncapitalize(String) - * @see #capitalizeFully(String) - */ - public static String capitalize(String str) { - return capitalize(str, null); - } - - /** - *

    Capitalizes all the delimiter separated words in a String. - * Only the first letter of each word is changed. To convert the - * rest of each word to lowercase at the same time, - * use {@link #capitalizeFully(String, char[])}.

    - * - *

    The delimiters represent a set of characters understood to separate words. - * The first string character and the first non-delimiter character after a - * delimiter will be capitalized.

    - * - *

    A null input String returns null. - * Capitalization uses the Unicode title case, normally equivalent to - * upper case.

    - * - *
    -     * WordUtils.capitalize(null, *)            = null
    -     * WordUtils.capitalize("", *)              = ""
    -     * WordUtils.capitalize(*, new char[0])     = *
    -     * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
    -     * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
    -     * 
    - * - * @param str the String to capitalize, may be null - * @param delimiters set of characters to determine capitalization, null means whitespace - * @return capitalized String, null if null String input - * @see #uncapitalize(String) - * @see #capitalizeFully(String) - * @since 2.1 - */ - public static String capitalize(String str, char... delimiters) { - int delimLen = delimiters == null ? -1 : delimiters.length; - if (StringUtils.isEmpty(str) || delimLen == 0) { - return str; - } - char[] buffer = str.toCharArray(); - boolean capitalizeNext = true; - for (int i = 0; i < buffer.length; i++) { - char ch = buffer[i]; - if (isDelimiter(ch, delimiters)) { - capitalizeNext = true; - } else if (capitalizeNext) { - buffer[i] = Character.toTitleCase(ch); - capitalizeNext = false; - } - } - return new String(buffer); - } - - //----------------------------------------------------------------------- - /** - *

    Converts all the whitespace separated words in a String into capitalized words, - * that is each word is made up of a titlecase character and then a series of - * lowercase characters.

    - * - *

    Whitespace is defined by {@link Character#isWhitespace(char)}. - * A null input String returns null. - * Capitalization uses the Unicode title case, normally equivalent to - * upper case.

    - * - *
    -     * WordUtils.capitalizeFully(null)        = null
    -     * WordUtils.capitalizeFully("")          = ""
    -     * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
    -     * 
    - * - * @param str the String to capitalize, may be null - * @return capitalized String, null if null String input - */ - public static String capitalizeFully(String str) { - return capitalizeFully(str, null); - } - - /** - *

    Converts all the delimiter separated words in a String into capitalized words, - * that is each word is made up of a titlecase character and then a series of - * lowercase characters.

    - * - *

    The delimiters represent a set of characters understood to separate words. - * The first string character and the first non-delimiter character after a - * delimiter will be capitalized.

    - * - *

    A null input String returns null. - * Capitalization uses the Unicode title case, normally equivalent to - * upper case.

    - * - *
    -     * WordUtils.capitalizeFully(null, *)            = null
    -     * WordUtils.capitalizeFully("", *)              = ""
    -     * WordUtils.capitalizeFully(*, null)            = *
    -     * WordUtils.capitalizeFully(*, new char[0])     = *
    -     * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
    -     * 
    - * - * @param str the String to capitalize, may be null - * @param delimiters set of characters to determine capitalization, null means whitespace - * @return capitalized String, null if null String input - * @since 2.1 - */ - public static String capitalizeFully(String str, char... delimiters) { - int delimLen = delimiters == null ? -1 : delimiters.length; - if (StringUtils.isEmpty(str) || delimLen == 0) { - return str; - } - str = str.toLowerCase(); - return capitalize(str, delimiters); - } - - //----------------------------------------------------------------------- - /** - *

    Uncapitalizes all the whitespace separated words in a String. - * Only the first letter of each word is changed.

    - * - *

    Whitespace is defined by {@link Character#isWhitespace(char)}. - * A null input String returns null.

    - * - *
    -     * WordUtils.uncapitalize(null)        = null
    -     * WordUtils.uncapitalize("")          = ""
    -     * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
    -     * 
    - * - * @param str the String to uncapitalize, may be null - * @return uncapitalized String, null if null String input - * @see #capitalize(String) - */ - public static String uncapitalize(String str) { - return uncapitalize(str, null); - } - - /** - *

    Uncapitalizes all the whitespace separated words in a String. - * Only the first letter of each word is changed.

    - * - *

    The delimiters represent a set of characters understood to separate words. - * The first string character and the first non-delimiter character after a - * delimiter will be uncapitalized.

    - * - *

    Whitespace is defined by {@link Character#isWhitespace(char)}. - * A null input String returns null.

    - * - *
    -     * WordUtils.uncapitalize(null, *)            = null
    -     * WordUtils.uncapitalize("", *)              = ""
    -     * WordUtils.uncapitalize(*, null)            = *
    -     * WordUtils.uncapitalize(*, new char[0])     = *
    -     * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
    -     * 
    - * - * @param str the String to uncapitalize, may be null - * @param delimiters set of characters to determine uncapitalization, null means whitespace - * @return uncapitalized String, null if null String input - * @see #capitalize(String) - * @since 2.1 - */ - public static String uncapitalize(String str, char... delimiters) { - int delimLen = delimiters == null ? -1 : delimiters.length; - if (StringUtils.isEmpty(str) || delimLen == 0) { - return str; - } - char[] buffer = str.toCharArray(); - boolean uncapitalizeNext = true; - for (int i = 0; i < buffer.length; i++) { - char ch = buffer[i]; - if (isDelimiter(ch, delimiters)) { - uncapitalizeNext = true; - } else if (uncapitalizeNext) { - buffer[i] = Character.toLowerCase(ch); - uncapitalizeNext = false; - } - } - return new String(buffer); - } - - //----------------------------------------------------------------------- - /** - *

    Swaps the case of a String using a word based algorithm.

    - * - *
      - *
    • Upper case character converts to Lower case
    • - *
    • Title case character converts to Lower case
    • - *
    • Lower case character after Whitespace or at start converts to Title case
    • - *
    • Other Lower case character converts to Upper case
    • - *
    - * - *

    Whitespace is defined by {@link Character#isWhitespace(char)}. - * A null input String returns null.

    - * - *
    -     * StringUtils.swapCase(null)                 = null
    -     * StringUtils.swapCase("")                   = ""
    -     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
    -     * 
    - * - * @param str the String to swap case, may be null - * @return the changed String, null if null String input - */ - public static String swapCase(String str) { - if (StringUtils.isEmpty(str)) { - return str; - } - char[] buffer = str.toCharArray(); - - boolean whitespace = true; - - for (int i = 0; i < buffer.length; i++) { - char ch = buffer[i]; - if (Character.isUpperCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - whitespace = false; - } else if (Character.isTitleCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - whitespace = false; - } else if (Character.isLowerCase(ch)) { - if (whitespace) { - buffer[i] = Character.toTitleCase(ch); - whitespace = false; - } else { - buffer[i] = Character.toUpperCase(ch); - } - } else { - whitespace = Character.isWhitespace(ch); - } - } - return new String(buffer); - } - - //----------------------------------------------------------------------- - /** - *

    Extracts the initial letters from each word in the String.

    - * - *

    The first letter of the string and all first letters after - * whitespace are returned as a new string. - * Their case is not changed.

    - * - *

    Whitespace is defined by {@link Character#isWhitespace(char)}. - * A null input String returns null.

    - * - *
    -     * WordUtils.initials(null)             = null
    -     * WordUtils.initials("")               = ""
    -     * WordUtils.initials("Ben John Lee")   = "BJL"
    -     * WordUtils.initials("Ben J.Lee")      = "BJ"
    -     * 
    - * - * @param str the String to get initials from, may be null - * @return String of initial letters, null if null String input - * @see #initials(String,char[]) - * @since 2.2 - */ - public static String initials(String str) { - return initials(str, null); - } - - /** - *

    Extracts the initial letters from each word in the String.

    - * - *

    The first letter of the string and all first letters after the - * defined delimiters are returned as a new string. - * Their case is not changed.

    - * - *

    If the delimiters array is null, then Whitespace is used. - * Whitespace is defined by {@link Character#isWhitespace(char)}. - * A null input String returns null. - * An empty delimiter array returns an empty String.

    - * - *
    -     * WordUtils.initials(null, *)                = null
    -     * WordUtils.initials("", *)                  = ""
    -     * WordUtils.initials("Ben John Lee", null)   = "BJL"
    -     * WordUtils.initials("Ben J.Lee", null)      = "BJ"
    -     * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
    -     * WordUtils.initials(*, new char[0])         = ""
    -     * 
    - * - * @param str the String to get initials from, may be null - * @param delimiters set of characters to determine words, null means whitespace - * @return String of initial letters, null if null String input - * @see #initials(String) - * @since 2.2 - */ - public static String initials(String str, char... delimiters) { - if (StringUtils.isEmpty(str)) { - return str; - } - if (delimiters != null && delimiters.length == 0) { - return ""; - } - int strLen = str.length(); - char[] buf = new char[strLen / 2 + 1]; - int count = 0; - boolean lastWasGap = true; - for (int i = 0; i < strLen; i++) { - char ch = str.charAt(i); - - if (isDelimiter(ch, delimiters)) { - lastWasGap = true; - } else if (lastWasGap) { - buf[count++] = ch; - lastWasGap = false; - } else { - continue; // ignore ch - } - } - return new String(buf, 0, count); - } - - //----------------------------------------------------------------------- - /** - * Is the character a delimiter. - * - * @param ch the character to check - * @param delimiters the delimiters - * @return true if it is a delimiter - */ - private static boolean isDelimiter(char ch, char[] delimiters) { - if (delimiters == null) { - return Character.isWhitespace(ch); - } - for (char delimiter : delimiters) { - if (ch == delimiter) { - return true; - } - } - return false; - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/package.html b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/package.html deleted file mode 100644 index bf39f039..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - -

    -Provides classes for handling and manipulating text, partly as an extension to {@link java.text}. -The classes in this package are, for the most part, intended to be instantiated. -(ie. they are not utility classes with lots of static methods) -

    -@since 2.1 - - diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/AggregateTranslator.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/AggregateTranslator.java deleted file mode 100644 index 8164041c..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/AggregateTranslator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text.translate; - -import java.io.IOException; -import java.io.Writer; - -import external.org.apache.commons.lang3.ArrayUtils; - -/** - * Executes a sequence of translators one after the other. Execution ends whenever - * the first translator consumes codepoints from the input. - * - * @since 3.0 - * @version $Id: AggregateTranslator.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class AggregateTranslator extends CharSequenceTranslator { - - private final CharSequenceTranslator[] translators; - - /** - * Specify the translators to be used at creation time. - * - * @param translators CharSequenceTranslator array to aggregate - */ - public AggregateTranslator(CharSequenceTranslator... translators) { - this.translators = ArrayUtils.clone(translators); - } - - /** - * The first translator to consume codepoints from the input is the 'winner'. - * Execution stops with the number of consumed codepoints being returned. - * {@inheritDoc} - */ - @Override - public int translate(CharSequence input, int index, Writer out) throws IOException { - for (CharSequenceTranslator translator : translators) { - int consumed = translator.translate(input, index, out); - if(consumed != 0) { - return consumed; - } - } - return 0; - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java deleted file mode 100644 index c02d7a40..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text.translate; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Locale; - -/** - * An API for translating text. - * Its core use is to escape and unescape text. Because escaping and unescaping - * is completely contextual, the API does not present two separate signatures. - * - * @since 3.0 - * @version $Id: CharSequenceTranslator.java 1146844 2011-07-14 18:49:51Z mbenson $ - */ -public abstract class CharSequenceTranslator { - - /** - * Translate a set of codepoints, represented by an int index into a CharSequence, - * into another set of codepoints. The number of codepoints consumed must be returned, - * and the only IOExceptions thrown must be from interacting with the Writer so that - * the top level API may reliable ignore StringWriter IOExceptions. - * - * @param input CharSequence that is being translated - * @param index int representing the current point of translation - * @param out Writer to translate the text to - * @return int count of codepoints consumed - * @throws IOException if and only if the Writer produces an IOException - */ - public abstract int translate(CharSequence input, int index, Writer out) throws IOException; - - /** - * Helper for non-Writer usage. - * @param input CharSequence to be translated - * @return String output of translation - */ - public final String translate(CharSequence input) { - if (input == null) { - return null; - } - try { - StringWriter writer = new StringWriter(input.length() * 2); - translate(input, writer); - return writer.toString(); - } catch (IOException ioe) { - // this should never ever happen while writing to a StringWriter - throw new RuntimeException(ioe); - } - } - - /** - * Translate an input onto a Writer. This is intentionally final as its algorithm is - * tightly coupled with the abstract method of this class. - * - * @param input CharSequence that is being translated - * @param out Writer to translate the text to - * @throws IOException if and only if the Writer produces an IOException - */ - public final void translate(CharSequence input, Writer out) throws IOException { - if (out == null) { - throw new IllegalArgumentException("The Writer must not be null"); - } - if (input == null) { - return; - } - int pos = 0; - int len = input.length(); - while (pos < len) { - int consumed = translate(input, pos, out); - if (consumed == 0) { - char[] c = Character.toChars(Character.codePointAt(input, pos)); - out.write(c); - pos+= c.length; - continue; - } -// // contract with translators is that they have to understand codepoints -// // and they just took care of a surrogate pair - for (int pt = 0; pt < consumed; pt++) { - pos += Character.charCount(Character.codePointAt(input, pos)); - } - } - } - - /** - * Helper method to create a merger of this translator with another set of - * translators. Useful in customizing the standard functionality. - * - * @param translators CharSequenceTranslator array of translators to merge with this one - * @return CharSequenceTranslator merging this translator with the others - */ - public final CharSequenceTranslator with(CharSequenceTranslator... translators) { - CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1]; - newArray[0] = this; - System.arraycopy(translators, 0, newArray, 1, translators.length); - return new AggregateTranslator(newArray); - } - - /** - *

    Returns an upper case hexadecimal String for the given - * character.

    - * - * @param codepoint The codepoint to convert. - * @return An upper case hexadecimal String - */ - public static String hex(int codepoint) { - return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH); - } - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CodePointTranslator.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CodePointTranslator.java deleted file mode 100644 index dc56c246..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/CodePointTranslator.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text.translate; - -import java.io.IOException; -import java.io.Writer; - -/** - * Helper subclass to CharSequenceTranslator to allow for translations that - * will replace up to one character at a time. - * - * @since 3.0 - * @version $Id: CodePointTranslator.java 1139924 2011-06-26 19:32:14Z mbenson $ - */ -public abstract class CodePointTranslator extends CharSequenceTranslator { - - /** - * Implementation of translate that maps onto the abstract translate(int, Writer) method. - * {@inheritDoc} - */ - @Override - public final int translate(CharSequence input, int index, Writer out) throws IOException { - int codepoint = Character.codePointAt(input, index); - boolean consumed = translate(codepoint, out); - if (consumed) { - return 1; - } else { - return 0; - } - } - - /** - * Translate the specified codepoint into another. - * - * @param codepoint int character input to translate - * @param out Writer to optionally push the translated output to - * @return boolean as to whether translation occurred or not - * @throws IOException if and only if the Writer produces an IOException - */ - public abstract boolean translate(int codepoint, Writer out) throws IOException; - -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/EntityArrays.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/EntityArrays.java deleted file mode 100644 index 4a74e16c..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/EntityArrays.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text.translate; - -/** - * Class holding various entity data for HTML and XML - generally for use with - * the LookupTranslator. - * All arrays are of length [*][2]. - * - * @since 3.0 - * @version $Id: EntityArrays.java 1088899 2011-04-05 05:31:27Z bayard $ - */ -public class EntityArrays { - - /** - * Mapping to escape ISO-8859-1 - * characters to their named HTML 3.x equivalents. - * @return the mapping table - */ - public static String[][] ISO8859_1_ESCAPE() { return ISO8859_1_ESCAPE.clone(); } - private static final String[][] ISO8859_1_ESCAPE = { - {"\u00A0", " "}, // non-breaking space - {"\u00A1", "¡"}, // inverted exclamation mark - {"\u00A2", "¢"}, // cent sign - {"\u00A3", "£"}, // pound sign - {"\u00A4", "¤"}, // currency sign - {"\u00A5", "¥"}, // yen sign = yuan sign - {"\u00A6", "¦"}, // broken bar = broken vertical bar - {"\u00A7", "§"}, // section sign - {"\u00A8", "¨"}, // diaeresis = spacing diaeresis - {"\u00A9", "©"}, // © - copyright sign - {"\u00AA", "ª"}, // feminine ordinal indicator - {"\u00AB", "«"}, // left-pointing double angle quotation mark = left pointing guillemet - {"\u00AC", "¬"}, // not sign - {"\u00AD", "­"}, // soft hyphen = discretionary hyphen - {"\u00AE", "®"}, // ® - registered trademark sign - {"\u00AF", "¯"}, // macron = spacing macron = overline = APL overbar - {"\u00B0", "°"}, // degree sign - {"\u00B1", "±"}, // plus-minus sign = plus-or-minus sign - {"\u00B2", "²"}, // superscript two = superscript digit two = squared - {"\u00B3", "³"}, // superscript three = superscript digit three = cubed - {"\u00B4", "´"}, // acute accent = spacing acute - {"\u00B5", "µ"}, // micro sign - {"\u00B6", "¶"}, // pilcrow sign = paragraph sign - {"\u00B7", "·"}, // middle dot = Georgian comma = Greek middle dot - {"\u00B8", "¸"}, // cedilla = spacing cedilla - {"\u00B9", "¹"}, // superscript one = superscript digit one - {"\u00BA", "º"}, // masculine ordinal indicator - {"\u00BB", "»"}, // right-pointing double angle quotation mark = right pointing guillemet - {"\u00BC", "¼"}, // vulgar fraction one quarter = fraction one quarter - {"\u00BD", "½"}, // vulgar fraction one half = fraction one half - {"\u00BE", "¾"}, // vulgar fraction three quarters = fraction three quarters - {"\u00BF", "¿"}, // inverted question mark = turned question mark - {"\u00C0", "À"}, // À - uppercase A, grave accent - {"\u00C1", "Á"}, // Á - uppercase A, acute accent - {"\u00C2", "Â"}, //  - uppercase A, circumflex accent - {"\u00C3", "Ã"}, // à - uppercase A, tilde - {"\u00C4", "Ä"}, // Ä - uppercase A, umlaut - {"\u00C5", "Å"}, // Å - uppercase A, ring - {"\u00C6", "Æ"}, // Æ - uppercase AE - {"\u00C7", "Ç"}, // Ç - uppercase C, cedilla - {"\u00C8", "È"}, // È - uppercase E, grave accent - {"\u00C9", "É"}, // É - uppercase E, acute accent - {"\u00CA", "Ê"}, // Ê - uppercase E, circumflex accent - {"\u00CB", "Ë"}, // Ë - uppercase E, umlaut - {"\u00CC", "Ì"}, // Ì - uppercase I, grave accent - {"\u00CD", "Í"}, // Í - uppercase I, acute accent - {"\u00CE", "Î"}, // Î - uppercase I, circumflex accent - {"\u00CF", "Ï"}, // Ï - uppercase I, umlaut - {"\u00D0", "Ð"}, // Ð - uppercase Eth, Icelandic - {"\u00D1", "Ñ"}, // Ñ - uppercase N, tilde - {"\u00D2", "Ò"}, // Ò - uppercase O, grave accent - {"\u00D3", "Ó"}, // Ó - uppercase O, acute accent - {"\u00D4", "Ô"}, // Ô - uppercase O, circumflex accent - {"\u00D5", "Õ"}, // Õ - uppercase O, tilde - {"\u00D6", "Ö"}, // Ö - uppercase O, umlaut - {"\u00D7", "×"}, // multiplication sign - {"\u00D8", "Ø"}, // Ø - uppercase O, slash - {"\u00D9", "Ù"}, // Ù - uppercase U, grave accent - {"\u00DA", "Ú"}, // Ú - uppercase U, acute accent - {"\u00DB", "Û"}, // Û - uppercase U, circumflex accent - {"\u00DC", "Ü"}, // Ü - uppercase U, umlaut - {"\u00DD", "Ý"}, // Ý - uppercase Y, acute accent - {"\u00DE", "Þ"}, // Þ - uppercase THORN, Icelandic - {"\u00DF", "ß"}, // ß - lowercase sharps, German - {"\u00E0", "à"}, // à - lowercase a, grave accent - {"\u00E1", "á"}, // á - lowercase a, acute accent - {"\u00E2", "â"}, // â - lowercase a, circumflex accent - {"\u00E3", "ã"}, // ã - lowercase a, tilde - {"\u00E4", "ä"}, // ä - lowercase a, umlaut - {"\u00E5", "å"}, // å - lowercase a, ring - {"\u00E6", "æ"}, // æ - lowercase ae - {"\u00E7", "ç"}, // ç - lowercase c, cedilla - {"\u00E8", "è"}, // è - lowercase e, grave accent - {"\u00E9", "é"}, // é - lowercase e, acute accent - {"\u00EA", "ê"}, // ê - lowercase e, circumflex accent - {"\u00EB", "ë"}, // ë - lowercase e, umlaut - {"\u00EC", "ì"}, // ì - lowercase i, grave accent - {"\u00ED", "í"}, // í - lowercase i, acute accent - {"\u00EE", "î"}, // î - lowercase i, circumflex accent - {"\u00EF", "ï"}, // ï - lowercase i, umlaut - {"\u00F0", "ð"}, // ð - lowercase eth, Icelandic - {"\u00F1", "ñ"}, // ñ - lowercase n, tilde - {"\u00F2", "ò"}, // ò - lowercase o, grave accent - {"\u00F3", "ó"}, // ó - lowercase o, acute accent - {"\u00F4", "ô"}, // ô - lowercase o, circumflex accent - {"\u00F5", "õ"}, // õ - lowercase o, tilde - {"\u00F6", "ö"}, // ö - lowercase o, umlaut - {"\u00F7", "÷"}, // division sign - {"\u00F8", "ø"}, // ø - lowercase o, slash - {"\u00F9", "ù"}, // ù - lowercase u, grave accent - {"\u00FA", "ú"}, // ú - lowercase u, acute accent - {"\u00FB", "û"}, // û - lowercase u, circumflex accent - {"\u00FC", "ü"}, // ü - lowercase u, umlaut - {"\u00FD", "ý"}, // ý - lowercase y, acute accent - {"\u00FE", "þ"}, // þ - lowercase thorn, Icelandic - {"\u00FF", "ÿ"}, // ÿ - lowercase y, umlaut - }; - - /** - * Reverse of {@link #ISO8859_1_ESCAPE()} for unescaping purposes. - * @return the mapping table - */ - public static String[][] ISO8859_1_UNESCAPE() { return ISO8859_1_UNESCAPE.clone(); } - private static final String[][] ISO8859_1_UNESCAPE = invert(ISO8859_1_ESCAPE); - - /** - * Mapping to escape additional character entity - * references. Note that this must be used with {@link #ISO8859_1_ESCAPE()} to get the full list of - * HTML 4.0 character entities. - * @return the mapping table - */ - public static String[][] HTML40_EXTENDED_ESCAPE() { return HTML40_EXTENDED_ESCAPE.clone(); } - private static final String[][] HTML40_EXTENDED_ESCAPE = { - // - {"\u0192", "ƒ"}, // latin small f with hook = function= florin, U+0192 ISOtech --> - // - {"\u0391", "Α"}, // greek capital letter alpha, U+0391 --> - {"\u0392", "Β"}, // greek capital letter beta, U+0392 --> - {"\u0393", "Γ"}, // greek capital letter gamma,U+0393 ISOgrk3 --> - {"\u0394", "Δ"}, // greek capital letter delta,U+0394 ISOgrk3 --> - {"\u0395", "Ε"}, // greek capital letter epsilon, U+0395 --> - {"\u0396", "Ζ"}, // greek capital letter zeta, U+0396 --> - {"\u0397", "Η"}, // greek capital letter eta, U+0397 --> - {"\u0398", "Θ"}, // greek capital letter theta,U+0398 ISOgrk3 --> - {"\u0399", "Ι"}, // greek capital letter iota, U+0399 --> - {"\u039A", "Κ"}, // greek capital letter kappa, U+039A --> - {"\u039B", "Λ"}, // greek capital letter lambda,U+039B ISOgrk3 --> - {"\u039C", "Μ"}, // greek capital letter mu, U+039C --> - {"\u039D", "Ν"}, // greek capital letter nu, U+039D --> - {"\u039E", "Ξ"}, // greek capital letter xi, U+039E ISOgrk3 --> - {"\u039F", "Ο"}, // greek capital letter omicron, U+039F --> - {"\u03A0", "Π"}, // greek capital letter pi, U+03A0 ISOgrk3 --> - {"\u03A1", "Ρ"}, // greek capital letter rho, U+03A1 --> - // - {"\u03A3", "Σ"}, // greek capital letter sigma,U+03A3 ISOgrk3 --> - {"\u03A4", "Τ"}, // greek capital letter tau, U+03A4 --> - {"\u03A5", "Υ"}, // greek capital letter upsilon,U+03A5 ISOgrk3 --> - {"\u03A6", "Φ"}, // greek capital letter phi,U+03A6 ISOgrk3 --> - {"\u03A7", "Χ"}, // greek capital letter chi, U+03A7 --> - {"\u03A8", "Ψ"}, // greek capital letter psi,U+03A8 ISOgrk3 --> - {"\u03A9", "Ω"}, // greek capital letter omega,U+03A9 ISOgrk3 --> - {"\u03B1", "α"}, // greek small letter alpha,U+03B1 ISOgrk3 --> - {"\u03B2", "β"}, // greek small letter beta, U+03B2 ISOgrk3 --> - {"\u03B3", "γ"}, // greek small letter gamma,U+03B3 ISOgrk3 --> - {"\u03B4", "δ"}, // greek small letter delta,U+03B4 ISOgrk3 --> - {"\u03B5", "ε"}, // greek small letter epsilon,U+03B5 ISOgrk3 --> - {"\u03B6", "ζ"}, // greek small letter zeta, U+03B6 ISOgrk3 --> - {"\u03B7", "η"}, // greek small letter eta, U+03B7 ISOgrk3 --> - {"\u03B8", "θ"}, // greek small letter theta,U+03B8 ISOgrk3 --> - {"\u03B9", "ι"}, // greek small letter iota, U+03B9 ISOgrk3 --> - {"\u03BA", "κ"}, // greek small letter kappa,U+03BA ISOgrk3 --> - {"\u03BB", "λ"}, // greek small letter lambda,U+03BB ISOgrk3 --> - {"\u03BC", "μ"}, // greek small letter mu, U+03BC ISOgrk3 --> - {"\u03BD", "ν"}, // greek small letter nu, U+03BD ISOgrk3 --> - {"\u03BE", "ξ"}, // greek small letter xi, U+03BE ISOgrk3 --> - {"\u03BF", "ο"}, // greek small letter omicron, U+03BF NEW --> - {"\u03C0", "π"}, // greek small letter pi, U+03C0 ISOgrk3 --> - {"\u03C1", "ρ"}, // greek small letter rho, U+03C1 ISOgrk3 --> - {"\u03C2", "ς"}, // greek small letter final sigma,U+03C2 ISOgrk3 --> - {"\u03C3", "σ"}, // greek small letter sigma,U+03C3 ISOgrk3 --> - {"\u03C4", "τ"}, // greek small letter tau, U+03C4 ISOgrk3 --> - {"\u03C5", "υ"}, // greek small letter upsilon,U+03C5 ISOgrk3 --> - {"\u03C6", "φ"}, // greek small letter phi, U+03C6 ISOgrk3 --> - {"\u03C7", "χ"}, // greek small letter chi, U+03C7 ISOgrk3 --> - {"\u03C8", "ψ"}, // greek small letter psi, U+03C8 ISOgrk3 --> - {"\u03C9", "ω"}, // greek small letter omega,U+03C9 ISOgrk3 --> - {"\u03D1", "ϑ"}, // greek small letter theta symbol,U+03D1 NEW --> - {"\u03D2", "ϒ"}, // greek upsilon with hook symbol,U+03D2 NEW --> - {"\u03D6", "ϖ"}, // greek pi symbol, U+03D6 ISOgrk3 --> - // - {"\u2022", "•"}, // bullet = black small circle,U+2022 ISOpub --> - // - {"\u2026", "…"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub --> - {"\u2032", "′"}, // prime = minutes = feet, U+2032 ISOtech --> - {"\u2033", "″"}, // double prime = seconds = inches,U+2033 ISOtech --> - {"\u203E", "‾"}, // overline = spacing overscore,U+203E NEW --> - {"\u2044", "⁄"}, // fraction slash, U+2044 NEW --> - // - {"\u2118", "℘"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso --> - {"\u2111", "ℑ"}, // blackletter capital I = imaginary part,U+2111 ISOamso --> - {"\u211C", "ℜ"}, // blackletter capital R = real part symbol,U+211C ISOamso --> - {"\u2122", "™"}, // trade mark sign, U+2122 ISOnum --> - {"\u2135", "ℵ"}, // alef symbol = first transfinite cardinal,U+2135 NEW --> - // - // - {"\u2190", "←"}, // leftwards arrow, U+2190 ISOnum --> - {"\u2191", "↑"}, // upwards arrow, U+2191 ISOnum--> - {"\u2192", "→"}, // rightwards arrow, U+2192 ISOnum --> - {"\u2193", "↓"}, // downwards arrow, U+2193 ISOnum --> - {"\u2194", "↔"}, // left right arrow, U+2194 ISOamsa --> - {"\u21B5", "↵"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW --> - {"\u21D0", "⇐"}, // leftwards double arrow, U+21D0 ISOtech --> - // - {"\u21D1", "⇑"}, // upwards double arrow, U+21D1 ISOamsa --> - {"\u21D2", "⇒"}, // rightwards double arrow,U+21D2 ISOtech --> - // - {"\u21D3", "⇓"}, // downwards double arrow, U+21D3 ISOamsa --> - {"\u21D4", "⇔"}, // left right double arrow,U+21D4 ISOamsa --> - // - {"\u2200", "∀"}, // for all, U+2200 ISOtech --> - {"\u2202", "∂"}, // partial differential, U+2202 ISOtech --> - {"\u2203", "∃"}, // there exists, U+2203 ISOtech --> - {"\u2205", "∅"}, // empty set = null set = diameter,U+2205 ISOamso --> - {"\u2207", "∇"}, // nabla = backward difference,U+2207 ISOtech --> - {"\u2208", "∈"}, // element of, U+2208 ISOtech --> - {"\u2209", "∉"}, // not an element of, U+2209 ISOtech --> - {"\u220B", "∋"}, // contains as member, U+220B ISOtech --> - // - {"\u220F", "∏"}, // n-ary product = product sign,U+220F ISOamsb --> - // - {"\u2211", "∑"}, // n-ary summation, U+2211 ISOamsb --> - // - {"\u2212", "−"}, // minus sign, U+2212 ISOtech --> - {"\u2217", "∗"}, // asterisk operator, U+2217 ISOtech --> - {"\u221A", "√"}, // square root = radical sign,U+221A ISOtech --> - {"\u221D", "∝"}, // proportional to, U+221D ISOtech --> - {"\u221E", "∞"}, // infinity, U+221E ISOtech --> - {"\u2220", "∠"}, // angle, U+2220 ISOamso --> - {"\u2227", "∧"}, // logical and = wedge, U+2227 ISOtech --> - {"\u2228", "∨"}, // logical or = vee, U+2228 ISOtech --> - {"\u2229", "∩"}, // intersection = cap, U+2229 ISOtech --> - {"\u222A", "∪"}, // union = cup, U+222A ISOtech --> - {"\u222B", "∫"}, // integral, U+222B ISOtech --> - {"\u2234", "∴"}, // therefore, U+2234 ISOtech --> - {"\u223C", "∼"}, // tilde operator = varies with = similar to,U+223C ISOtech --> - // - {"\u2245", "≅"}, // approximately equal to, U+2245 ISOtech --> - {"\u2248", "≈"}, // almost equal to = asymptotic to,U+2248 ISOamsr --> - {"\u2260", "≠"}, // not equal to, U+2260 ISOtech --> - {"\u2261", "≡"}, // identical to, U+2261 ISOtech --> - {"\u2264", "≤"}, // less-than or equal to, U+2264 ISOtech --> - {"\u2265", "≥"}, // greater-than or equal to,U+2265 ISOtech --> - {"\u2282", "⊂"}, // subset of, U+2282 ISOtech --> - {"\u2283", "⊃"}, // superset of, U+2283 ISOtech --> - // - {"\u2286", "⊆"}, // subset of or equal to, U+2286 ISOtech --> - {"\u2287", "⊇"}, // superset of or equal to,U+2287 ISOtech --> - {"\u2295", "⊕"}, // circled plus = direct sum,U+2295 ISOamsb --> - {"\u2297", "⊗"}, // circled times = vector product,U+2297 ISOamsb --> - {"\u22A5", "⊥"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech --> - {"\u22C5", "⋅"}, // dot operator, U+22C5 ISOamsb --> - // - // - {"\u2308", "⌈"}, // left ceiling = apl upstile,U+2308 ISOamsc --> - {"\u2309", "⌉"}, // right ceiling, U+2309 ISOamsc --> - {"\u230A", "⌊"}, // left floor = apl downstile,U+230A ISOamsc --> - {"\u230B", "⌋"}, // right floor, U+230B ISOamsc --> - {"\u2329", "⟨"}, // left-pointing angle bracket = bra,U+2329 ISOtech --> - // - {"\u232A", "⟩"}, // right-pointing angle bracket = ket,U+232A ISOtech --> - // - // - {"\u25CA", "◊"}, // lozenge, U+25CA ISOpub --> - // - {"\u2660", "♠"}, // black spade suit, U+2660 ISOpub --> - // - {"\u2663", "♣"}, // black club suit = shamrock,U+2663 ISOpub --> - {"\u2665", "♥"}, // black heart suit = valentine,U+2665 ISOpub --> - {"\u2666", "♦"}, // black diamond suit, U+2666 ISOpub --> - - // - {"\u0152", "Œ"}, // -- latin capital ligature OE,U+0152 ISOlat2 --> - {"\u0153", "œ"}, // -- latin small ligature oe, U+0153 ISOlat2 --> - // - {"\u0160", "Š"}, // -- latin capital letter S with caron,U+0160 ISOlat2 --> - {"\u0161", "š"}, // -- latin small letter s with caron,U+0161 ISOlat2 --> - {"\u0178", "Ÿ"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 --> - // - {"\u02C6", "ˆ"}, // -- modifier letter circumflex accent,U+02C6 ISOpub --> - {"\u02DC", "˜"}, // small tilde, U+02DC ISOdia --> - // - {"\u2002", " "}, // en space, U+2002 ISOpub --> - {"\u2003", " "}, // em space, U+2003 ISOpub --> - {"\u2009", " "}, // thin space, U+2009 ISOpub --> - {"\u200C", "‌"}, // zero width non-joiner,U+200C NEW RFC 2070 --> - {"\u200D", "‍"}, // zero width joiner, U+200D NEW RFC 2070 --> - {"\u200E", "‎"}, // left-to-right mark, U+200E NEW RFC 2070 --> - {"\u200F", "‏"}, // right-to-left mark, U+200F NEW RFC 2070 --> - {"\u2013", "–"}, // en dash, U+2013 ISOpub --> - {"\u2014", "—"}, // em dash, U+2014 ISOpub --> - {"\u2018", "‘"}, // left single quotation mark,U+2018 ISOnum --> - {"\u2019", "’"}, // right single quotation mark,U+2019 ISOnum --> - {"\u201A", "‚"}, // single low-9 quotation mark, U+201A NEW --> - {"\u201C", "“"}, // left double quotation mark,U+201C ISOnum --> - {"\u201D", "”"}, // right double quotation mark,U+201D ISOnum --> - {"\u201E", "„"}, // double low-9 quotation mark, U+201E NEW --> - {"\u2020", "†"}, // dagger, U+2020 ISOpub --> - {"\u2021", "‡"}, // double dagger, U+2021 ISOpub --> - {"\u2030", "‰"}, // per mille sign, U+2030 ISOtech --> - {"\u2039", "‹"}, // single left-pointing angle quotation mark,U+2039 ISO proposed --> - // - {"\u203A", "›"}, // single right-pointing angle quotation mark,U+203A ISO proposed --> - // - {"\u20AC", "€"}, // -- euro sign, U+20AC NEW --> - }; - - /** - * Reverse of {@link #HTML40_EXTENDED_ESCAPE()} for unescaping purposes. - * @return the mapping table - */ - public static String[][] HTML40_EXTENDED_UNESCAPE() { return HTML40_EXTENDED_UNESCAPE.clone(); } - private static final String[][] HTML40_EXTENDED_UNESCAPE = invert(HTML40_EXTENDED_ESCAPE); - - /** - * Mapping to escape the basic XML and HTML character entities. - * - * Namely: {@code " & < >} - * @return the mapping table - */ - public static String[][] BASIC_ESCAPE() { return BASIC_ESCAPE.clone(); } - private static final String[][] BASIC_ESCAPE = { - {"\"", """}, // " - double-quote - {"&", "&"}, // & - ampersand - {"<", "<"}, // < - less-than - {">", ">"}, // > - greater-than - }; - - /** - * Reverse of {@link #BASIC_ESCAPE()} for unescaping purposes. - * @return the mapping table - */ - public static String[][] BASIC_UNESCAPE() { return BASIC_UNESCAPE.clone(); } - private static final String[][] BASIC_UNESCAPE = invert(BASIC_ESCAPE); - - /** - * Mapping to escape the apostrophe character to its XML character entity. - * @return the mapping table - */ - public static String[][] APOS_ESCAPE() { return APOS_ESCAPE.clone(); } - private static final String[][] APOS_ESCAPE = { - {"'", "'"}, // XML apostrophe - }; - - /** - * Reverse of {@link #APOS_ESCAPE()} for unescaping purposes. - * @return the mapping table - */ - public static String[][] APOS_UNESCAPE() { return APOS_UNESCAPE.clone(); } - private static final String[][] APOS_UNESCAPE = invert(APOS_ESCAPE); - - /** - * Mapping to escape the Java control characters. - * - * Namely: {@code \b \n \t \f \r} - * @return the mapping table - */ - public static String[][] JAVA_CTRL_CHARS_ESCAPE() { return JAVA_CTRL_CHARS_ESCAPE.clone(); } - private static final String[][] JAVA_CTRL_CHARS_ESCAPE = { - {"\b", "\\b"}, - {"\n", "\\n"}, - {"\t", "\\t"}, - {"\f", "\\f"}, - {"\r", "\\r"} - }; - - /** - * Reverse of {@link #JAVA_CTRL_CHARS_ESCAPE()} for unescaping purposes. - * @return the mapping table - */ - public static String[][] JAVA_CTRL_CHARS_UNESCAPE() { return JAVA_CTRL_CHARS_UNESCAPE.clone(); } - private static final String[][] JAVA_CTRL_CHARS_UNESCAPE = invert(JAVA_CTRL_CHARS_ESCAPE); - - /** - * Used to invert an escape array into an unescape array - * @param array String[][] to be inverted - * @return String[][] inverted array - */ - public static String[][] invert(String[][] array) { - String[][] newarray = new String[array.length][2]; - for(int i = 0; i lookupMap; - private final int shortest; - private final int longest; - - /** - * Define the lookup table to be used in translation - * - * @param lookup CharSequence[][] table of size [*][2] - */ - public LookupTranslator(CharSequence[]... lookup) { - lookupMap = new HashMap(); - int _shortest = Integer.MAX_VALUE; - int _longest = 0; - if (lookup != null) { - for (CharSequence[] seq : lookup) { - this.lookupMap.put(seq[0], seq[1]); - int sz = seq[0].length(); - if (sz < _shortest) { - _shortest = sz; - } - if (sz > _longest) { - _longest = sz; - } - } - } - shortest = _shortest; - longest = _longest; - } - - /** - * {@inheritDoc} - */ - @Override - public int translate(CharSequence input, int index, Writer out) throws IOException { - int max = longest; - if (index + longest > input.length()) { - max = input.length() - index; - } - // descend so as to get a greedy algorithm - for (int i = max; i >= shortest; i--) { - CharSequence subSeq = input.subSequence(index, index + i); - CharSequence result = lookupMap.get(subSeq); - if (result != null) { - out.write(result.toString()); - return i; - } - } - return 0; - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityEscaper.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityEscaper.java deleted file mode 100644 index da999689..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityEscaper.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text.translate; - -import java.io.IOException; -import java.io.Writer; - -/** - * Translates codepoints to their XML numeric entity escaped value. - * - * @since 3.0 - * @version $Id: NumericEntityEscaper.java 1142151 2011-07-02 04:06:23Z bayard $ - */ -public class NumericEntityEscaper extends CodePointTranslator { - - private final int below; - private final int above; - private final boolean between; - - /** - *

    Constructs a NumericEntityEscaper for the specified range. This is - * the underlying method for the other constructors/builders. The below - * and above boundaries are inclusive when between is - * true and exclusive when it is false.

    - * - * @param below int value representing the lowest codepoint boundary - * @param above int value representing the highest codepoint boundary - * @param between whether to escape between the boundaries or outside them - */ - private NumericEntityEscaper(int below, int above, boolean between) { - this.below = below; - this.above = above; - this.between = between; - } - - /** - *

    Constructs a NumericEntityEscaper for all characters.

    - */ - public NumericEntityEscaper() { - this(0, Integer.MAX_VALUE, true); - } - - /** - *

    Constructs a NumericEntityEscaper below the specified value (exclusive).

    - * - * @param codepoint below which to escape - * @return the newly created {@code NumericEntityEscaper} instance - */ - public static NumericEntityEscaper below(int codepoint) { - return outsideOf(codepoint, Integer.MAX_VALUE); - } - - /** - *

    Constructs a NumericEntityEscaper above the specified value (exclusive).

    - * - * @param codepoint above which to escape - * @return the newly created {@code NumericEntityEscaper} instance - */ - public static NumericEntityEscaper above(int codepoint) { - return outsideOf(0, codepoint); - } - - /** - *

    Constructs a NumericEntityEscaper between the specified values (inclusive).

    - * - * @param codepointLow above which to escape - * @param codepointHigh below which to escape - * @return the newly created {@code NumericEntityEscaper} instance - */ - public static NumericEntityEscaper between(int codepointLow, int codepointHigh) { - return new NumericEntityEscaper(codepointLow, codepointHigh, true); - } - - /** - *

    Constructs a NumericEntityEscaper outside of the specified values (exclusive).

    - * - * @param codepointLow below which to escape - * @param codepointHigh above which to escape - * @return the newly created {@code NumericEntityEscaper} instance - */ - public static NumericEntityEscaper outsideOf(int codepointLow, int codepointHigh) { - return new NumericEntityEscaper(codepointLow, codepointHigh, false); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean translate(int codepoint, Writer out) throws IOException { - if(between) { - if (codepoint < below || codepoint > above) { - return false; - } - } else { - if (codepoint >= below && codepoint <= above) { - return false; - } - } - - out.write("&#"); - out.write(Integer.toString(codepoint, 10)); - out.write(';'); - return true; - } -} diff --git a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java b/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java deleted file mode 100644 index 338c0fc4..00000000 --- a/lib/apache-commons-lang/external/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package external.org.apache.commons.lang3.text.translate; - -import java.io.IOException; -import java.io.Writer; -import java.util.Arrays; -import java.util.EnumSet; - -/** - * Translate XML numeric entities of the form &#[xX]?\d+;? to - * the specific codepoint. - * - * Note that the semi-colon is optional. - * - * @since 3.0 - * @version $Id: NumericEntityUnescaper.java 1199894 2011-11-09 17:53:59Z ggregory $ - */ -public class NumericEntityUnescaper extends CharSequenceTranslator { - - public static enum OPTION { semiColonRequired, semiColonOptional, errorIfNoSemiColon } - - // TODO?: Create an OptionsSet class to hide some of the conditional logic below - private final EnumSet